Skip to content

Commit

Permalink
Inject EventManager on client factory
Browse files Browse the repository at this point in the history
  • Loading branch information
thomasvargiu committed Nov 25, 2016
1 parent 75ba8a0 commit 98af892
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions src/Service/ClientFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use PamiModule\Event\EventForwarder;
use PamiModule\Options\Client as ClientOptions;
use PamiModule\Options\Connection;
use Zend\EventManager\EventManager;
use Zend\ServiceManager\Exception\ServiceNotCreatedException;
use Zend\ServiceManager\Exception\ServiceNotFoundException;
use Zend\ServiceManager\ServiceLocatorInterface;
Expand Down Expand Up @@ -62,6 +63,7 @@ public function __invoke(ContainerInterface $container, $requestedName, array $o
$connection = $container->get(sprintf('pami.connection.%s', $connectionName));

$client = new Client($connectionOptions->getHost(), $connection);
$client->setEventManager($this->createEventManager($container));

if ($options) {
$client->setParams($options->getParams());
Expand All @@ -73,6 +75,46 @@ public function __invoke(ContainerInterface $container, $requestedName, array $o
return $client;
}

/**
* @param ContainerInterface $container
*
* @return EventManager
*/
protected function createEventManager(ContainerInterface $container)
{
if ($this->acceptsSharedManagerToConstructor()) {
// zend-eventmanager v3
return new EventManager(
$container->has('SharedEventManager') ? $container->get('SharedEventManager') : null
);
}

// zend-eventmanager v2
$events = new EventManager();

if ($container->has('SharedEventManager')) {
$events->setSharedManager($container->get('SharedEventManager'));
}

return $events;
}

/**
* Does the EventManager accept the shared manager to the constructor?
*
* In zend-eventmanager v3, the EventManager accepts the shared manager
* instance to the constructor *only*, while in v2, it must be injected
* via the setSharedManager() method.
*
* @return bool
*/
private function acceptsSharedManagerToConstructor()
{
$r = new \ReflectionClass(EventManager::class);

return !$r->hasMethod('setSharedManager');
}

/**
* Create service.
*
Expand Down

0 comments on commit 98af892

Please sign in to comment.