. */ namespace SP\Tests\Core\Events; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Group; use PHPUnit\Framework\MockObject\MockObject; use SP\Core\Events\Event; use SP\Core\Events\EventDispatcher; use SP\Domain\Core\Events\EventReceiver; use SP\Tests\UnitaryTestCase; /** * Class EventDispatcherTest * */ #[Group('unitary')] class EventDispatcherTest extends UnitaryTestCase { private const VALID_EVENTS = 'test|foo.bar.event'; private EventReceiver|MockObject $eventReceiver; private EventDispatcher $eventDispatcher; public static function eventNameProvider(): array { return [ ['test'], ['foo.bar.event'] ]; } public function testAttach() { $this->eventDispatcher->attach($this->eventReceiver); self::assertTrue($this->eventDispatcher->has($this->eventReceiver)); } public function testDetach() { $this->eventDispatcher->attach($this->eventReceiver); $this->eventDispatcher->detach($this->eventReceiver); self::assertFalse($this->eventDispatcher->has($this->eventReceiver)); } /** * @param string $eventName */ #[DataProvider('eventNameProvider')] public function testNotify(string $eventName) { $event = new Event($this); $this->eventReceiver->expects(self::once()) ->method('getEventsString') ->willReturn(self::VALID_EVENTS); $this->eventReceiver->expects(self::once()) ->method('update') ->with($eventName, $event); $this->eventDispatcher->attach($this->eventReceiver); $this->eventDispatcher->notify($eventName, $event); } public function testNotifyWithWildcard() { $event = new Event($this); $this->eventReceiver->expects(self::once()) ->method('getEventsString') ->willReturn('*'); $this->eventReceiver->expects(self::once()) ->method('update') ->with('test', $event); $this->eventDispatcher->attach($this->eventReceiver); $this->eventDispatcher->notify('test', $event); } public function testNotifyWithInvalidEvent() { $this->eventReceiver->expects(self::once()) ->method('getEventsString') ->willReturn('anotherEvent'); $this->eventReceiver->expects(self::never()) ->method('update'); $this->eventDispatcher->attach($this->eventReceiver); $this->eventDispatcher->notify('test', new Event($this)); } protected function setUp(): void { parent::setUp(); $this->eventReceiver = $this->createMock(EventReceiver::class); $this->eventDispatcher = new EventDispatcher(); } }