diff --git a/src/Plugin/ServiceLocatorPlugin.php b/src/Plugin/ServiceLocatorPlugin.php index bcd4b43..1cba163 100644 --- a/src/Plugin/ServiceLocatorPlugin.php +++ b/src/Plugin/ServiceLocatorPlugin.php @@ -46,15 +46,16 @@ function (ActionEvent $actionEvent): void { } // for event bus only - $eventListeners = []; - foreach ($actionEvent->getParam(EventBus::EVENT_PARAM_EVENT_LISTENERS, []) as $eventListenerAlias) { + $currentEventListeners = $actionEvent->getParam(EventBus::EVENT_PARAM_EVENT_LISTENERS, []); + $newEventListeners = []; + + foreach ($currentEventListeners as $eventListenerAlias) { if (is_string($eventListenerAlias) && $this->serviceLocator->has($eventListenerAlias)) { - $eventListeners[] = $this->serviceLocator->get($eventListenerAlias); + $newEventListeners[] = $this->serviceLocator->get($eventListenerAlias); } } - if (! empty($eventListeners)) { - $actionEvent->setParam(EventBus::EVENT_PARAM_EVENT_LISTENERS, $eventListeners); - } + + $actionEvent->setParam(EventBus::EVENT_PARAM_EVENT_LISTENERS, array_merge($currentEventListeners, $newEventListeners)); }, MessageBus::PRIORITY_LOCATE_HANDLER ); diff --git a/tests/Plugin/ServiceLocatorPluginTest.php b/tests/Plugin/ServiceLocatorPluginTest.php index ac30c75..069b8b8 100644 --- a/tests/Plugin/ServiceLocatorPluginTest.php +++ b/tests/Plugin/ServiceLocatorPluginTest.php @@ -15,8 +15,11 @@ use PHPUnit\Framework\TestCase; use Prooph\Common\Event\ActionEvent; use Prooph\ServiceBus\CommandBus; +use Prooph\ServiceBus\EventBus; +use Prooph\ServiceBus\Plugin\Router\EventRouter; use Prooph\ServiceBus\Plugin\ServiceLocatorPlugin; use ProophTest\ServiceBus\Mock\MessageHandler; +use ProophTest\ServiceBus\Mock\SomethingDone; use Psr\Container\ContainerInterface; class ServiceLocatorPluginTest extends TestCase @@ -49,4 +52,41 @@ function (ActionEvent $actionEvent): void { $commandBus->dispatch('foo'); } + + /** + * @test + * @group by + */ + public function it_doesnt_override_previous_event_handlers(): void + { + $handledOne = false; + + $handlerOne = function (SomethingDone $event) use (&$handledOne): void { + $handledOne = true; + }; + + $handlerTwo = new MessageHandler(); + + $container = $this->prophesize(ContainerInterface::class); + + $container->has('custom-handler')->willReturn(true)->shouldBeCalled(); + + $container->get('custom-handler')->willReturn($handlerTwo)->shouldBeCalled(); + + $eventBus = new EventBus(); + + $router = new EventRouter(); + $router->route(SomethingDone::class)->to($handlerOne)->andTo('custom-handler'); + + $router->attachToMessageBus($eventBus); + + $locatorPlugin = new ServiceLocatorPlugin($container->reveal()); + + $locatorPlugin->attachToMessageBus($eventBus); + + $eventBus->dispatch(new SomethingDone(['foo' => 'bar'])); + + $this->assertTrue($handledOne); + $this->assertSame(1, $handlerTwo->getInvokeCounter()); + } }