Beacon/tests/Unit/CoreDispatcherTest.php

68 lines
1.8 KiB
PHP
Raw Permalink Normal View History

<?php
declare(strict_types=1);
namespace Phred\Beacon\Tests\Unit;
use PHPUnit\Framework\TestCase;
use Phred\Beacon\EventDispatcher;
use Phred\Beacon\ListenerProvider;
use Phred\Beacon\CanStopPropagation;
use Phred\BeaconContracts\StoppableEventInterface;
class CoreDispatcherTest extends TestCase
{
public function test_it_dispatches_events_to_listeners(): void
{
$provider = new ListenerProvider();
$dispatcher = new EventDispatcher($provider);
$event = new class { public int $count = 0; };
$provider->addListener($event::class, function($e) {
$e->count++;
});
$dispatchedEvent = $dispatcher->dispatch($event);
$this->assertSame($event, $dispatchedEvent);
$this->assertEquals(1, $event->count);
}
public function test_it_respects_stoppable_events(): void
{
$provider = new ListenerProvider();
$dispatcher = new EventDispatcher($provider);
$event = new class implements StoppableEventInterface {
use CanStopPropagation;
public int $count = 0;
};
$provider->addListener($event::class, function($e) {
$e->count++;
$e->stopPropagation();
});
$provider->addListener($event::class, function($e) {
$e->count++; // Should not run
});
$dispatcher->dispatch($event);
$this->assertEquals(1, $event->count);
$this->assertTrue($event->isPropagationStopped());
}
public function test_it_returns_the_event_object(): void
{
$provider = new ListenerProvider();
$dispatcher = new EventDispatcher($provider);
$event = new \stdClass();
$result = $dispatcher->dispatch($event);
$this->assertSame($event, $result);
}
}