Skip to content

Commit

Permalink
fix service locator plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
prolic committed Jun 27, 2017
1 parent 280eb61 commit ba6ad16
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 6 deletions.
13 changes: 7 additions & 6 deletions src/Plugin/ServiceLocatorPlugin.php
Expand Up @@ -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
);
Expand Down
40 changes: 40 additions & 0 deletions tests/Plugin/ServiceLocatorPluginTest.php
Expand Up @@ -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
Expand Down Expand Up @@ -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());
}
}

0 comments on commit ba6ad16

Please sign in to comment.