Last active
May 24, 2016 23:16
-
-
Save pavarnos/e76f19b24ec3702b267ec92bf1c64885 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Add this to your container builder with | |
* $containerBuilder->addCompilerPass(new ConfigureLazyEventDispatcher(new LazyEventDispatcher($containerBuilder)); | |
*/ | |
class ConfigureLazyEventDispatcher implements CompilerPassInterface | |
{ | |
/** @var LazyEventDispatcher */ | |
private $dispatcher; | |
/** | |
* @param LazyEventDispatcher $dispatcher | |
*/ | |
public function __construct(LazyEventDispatcher $dispatcher) | |
{ | |
$this->dispatcher = $dispatcher; | |
} | |
/** | |
* @param ContainerBuilder $container | |
*/ | |
public function process(ContainerBuilder $container) | |
{ | |
$container->addResource(new FileResource(__FILE__)); | |
foreach ($container->getDefinitions() as $serviceName => $definition) { | |
$reflection = new \ReflectionClass($definition->getClass()); | |
if (!$reflection->isInstantiable()) { | |
continue; | |
} | |
if (!$reflection->hasMethod('getSubscribedEvents')) { | |
// you could check here for handlers that you forgot to connect to events | |
continue; | |
} | |
foreach ($this->getSubscribedEvents($reflection->getName()) as $event) { | |
$this->dispatcher->addLazyListener($event['name'], $serviceName, $event['method'], $event['priority']); | |
} | |
} | |
$this->dispatcher->saveLazyListeners(); | |
} | |
/** | |
* traverse the tricky structure returned by getSubscribedEvents() and make it nice and linear | |
* @param string $className | |
* @return array [event name, method name, priority] | |
*/ | |
private function getSubscribedEvents($className) | |
{ | |
// * array('eventName' => 'methodName') | |
// * array('eventName' => array('methodName', $priority)) | |
// * array('eventName' => array(array('methodName1', $priority), array('methodName2')) | |
$method = []; | |
$rawEvents = call_user_func($className . '::getSubscribedEvents'); | |
foreach ($rawEvents as $eventName => $params) { | |
if (is_string($params)) { | |
$method[] = ['name' => $eventName, 'method' => $params, 'priority' => 0]; | |
} elseif (is_string($params[0])) { | |
$method[] = [ | |
'name' => $eventName, | |
'method' => $params[0], | |
'priority' => isset($params[1]) ? $params[1] : 0, | |
]; | |
} else { | |
foreach ($params as $listener) { | |
$method[] = [ | |
'name' => $eventName, | |
'method' => $listener[0], | |
'priority' => isset($listener[1]) ? $listener[1] : 0, | |
]; | |
} | |
} | |
} | |
return $method; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment