Skip to content

Instantly share code, notes, and snippets.

@pavarnos
Last active May 24, 2016 23:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pavarnos/e76f19b24ec3702b267ec92bf1c64885 to your computer and use it in GitHub Desktop.
Save pavarnos/e76f19b24ec3702b267ec92bf1c64885 to your computer and use it in GitHub Desktop.
<?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