Testing the Event Dispatcher class.

This commit is contained in:
Ilya Bakhlin 2021-12-28 22:09:06 +01:00
parent 1f789219d9
commit c4e87066e2
2 changed files with 86 additions and 2 deletions

View file

@ -11,22 +11,35 @@ use Chandler\Patterns\TSimpleSingleton;
*/ */
class EventDispatcher class EventDispatcher
{ {
/**
* @var array
*/
private $hooks = []; private $hooks = [];
/**
* @param mixed $hook
*
* @return bool
*/
function addListener($hook): bool function addListener($hook): bool
{ {
$this->hooks[] = $hook; $this->hooks[] = $hook;
return true; return true;
} }
/**
* @param \Chandler\Eventing\Events\Event $event
*
* @return \Chandler\Eventing\Events\Event
*/
function pushEvent(Events\Event $event): Events\Event function pushEvent(Events\Event $event): Events\Event
{ {
foreach ($hooks as $hook) { foreach ($this->hooks as $hook) {
if ($event instanceof Events\Cancelable) if ($event instanceof Events\Cancelable)
if ($event->isCancelled()) if ($event->isCancelled())
break; break;
$method = "on" . str_replace("Event", "", get_class($event)); $method = "on" . str_replace("Event", "", get_class($event));
if (!method_exists($hook, $methodName)) continue; if (!method_exists($hook, $method)) continue;
$hook->$method($event); $hook->$method($event);
} }
return $event; return $event;

View file

@ -0,0 +1,71 @@
<?php
declare(strict_types = 1);
namespace Chandler\Tests\Chandler\Eventing;
use Chandler\Eventing\EventDispatcher;
use Chandler\Eventing\Events\Event;
use PHPUnit\Framework\TestCase;
/**
* @package Chandler\Tests\Chandler\Eventing
*/
class EventDispatcherTest extends TestCase
{
/**
* @return array
*/
public function provideMethodAddListener(): array // IMPROVE: Add more values.
{
return [
[
null,
],
];
}
/**
* @return array
*/
public function provideMethodPushEvent(): array
{
return [
[
new Event(),
],
];
}
/**
* @dataProvider provideMethodAddListener
*
* @param mixed $hook
*
* @return void
*/
public function testMethodAddListener($hook): void
{
$this->assertTrue(EventDispatcher::i()->addListener($hook));
}
/**
* @return void
*/
public function testMethodI(): void
{
$this->assertSame(EventDispatcher::i(), EventDispatcher::i());
}
/**
* @dataProvider provideMethodPushEvent
*
* @param \Chandler\Eventing\Events\Event $event
*
* @return void
*/
public function testMethodPushEvent(Event $event): void
{
$this->assertSame($event, EventDispatcher::i()->pushEvent($event));
}
}