Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[EventDispatcher] Add Drupal EventDispatcher #12521

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 18 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
249 changes: 249 additions & 0 deletions src/Symfony/Component/EventDispatcher/CompiledEventDispatcher.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,249 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\EventDispatcher;

use Symfony\Component\DependencyInjection\IntrospectableContainerInterface;

/**
* A performance optimized container aware event dispatcher.
*
* This version of the event dispatcher contains the following optimizations
* in comparison to the Symfony event dispatcher component:
*
* <dl>
* <dt>Faster instantiation of the event dispatcher service</dt>
* <dd>
* Instead of calling <code>addSubscriberService</code> once for each
* subscriber, a precompiled array of listener definitions is passed
* directly to the constructor. This is faster by an order of magnitude.
* The listeners are collected and prepared using a compiler
* pass.
* </dd>
* <dt>Lazy instantiation of listeners</dt>
* <dd>
* Services are only retrieved from the container just before invocation.
* Especially when dispatching the KernelEvents::REQUEST event, this leads
* to a more timely invocation of the first listener. Overall dispatch
* runtime is not affected by this change though.
* </dd>
* </dl>
*/
class CompiledEventDispatcher implements EventDispatcherInterface
{
/**
* The service container.
*
* @var IntrospectableContainerInterface
*/
private $container;

/**
* Listener definitions.
*
* A nested array of listener definitions keyed by event name and priority.
* A listener definition is an associative array with one of the following key
* value pairs:
* - callable: A callable listener
* - service: An array of the form
* array('id' => service id, 'method' => method name)
*
* A service entry will be resolved to a callable only just before its
* invocation.
*
* @var array
*/
private $listeners;

/**
* Whether listeners need to be sorted prior to dispatch, keyed by event name.
*
* @var array
*/
private $unsorted = array();

/**
* Constructs a container aware event dispatcher.
*
* @param IntrospectableContainerInterface $container
* The service container.
* @param array $listeners
* A nested array of listener definitions keyed by event name and priority.
* The array is expected to be ordered by priority. A listener definition is
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Several listeners can have the same priority, which means your array representation here is broken. You should support having multiple definitions by priority (and addListener is currently expecting a different structure for this array)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Btw, the compiler pass sets the same structure than expected by addListener. But dispatch and removeListener are the broken places

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah sorry, I misread the implementation. Forget these 2 comments

* an associative array with one of the following key value pairs:
* - callable: A callable listener
* - service: An array of the form
* array('id' => service id, 'method' => method name)
* A service entry will be resolved to a callable only just before its
* invocation.
*/
public function __construct(IntrospectableContainerInterface $container, array $listeners = array())
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just curious why we don't just use ContainerAwareInterface ?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dawehner ContainerAwareInterface is a totally different interface.

{
$this->container = $container;
$this->listeners = $listeners;
}

/**
* {@inheritdoc}
*/
public function dispatch($eventName, Event $event = null)
{
if (null === $event) {
$event = new Event();
}

$event->setDispatcher($this);
$event->setName($eventName);

if (isset($this->listeners[$eventName])) {
// Sort listeners if necessary.
if (isset($this->unsorted[$eventName])) {
krsort($this->listeners[$eventName]);
unset($this->unsorted[$eventName]);
}

// Invoke listeners and resolve callables if necessary.
foreach ($this->listeners[$eventName] as &$definitions) {
foreach ($definitions as &$definition) {
if (!isset($definition['callable'])) {
$definition['callable'] = array($this->container->get($definition['service']['id']), $definition['service']['method']);
}

call_user_func($definition['callable'], $event, $eventName, $this);
if ($event->isPropagationStopped()) {
return $event;
}
}
}
}

return $event;
}

/**
* {@inheritdoc}
*/
public function getListeners($eventName = null)
{
$result = array();

if (null === $eventName) {
// If event name was omitted, collect all listeners of all events.
foreach (array_keys($this->listeners) as $eventName) {
$listeners = $this->getListeners($eventName);
if (!empty($listeners)) {
$result[$eventName] = $listeners;
}
}

return $result;
}

if (!isset($this->listeners[$eventName])) {
return $result;
}

// Sort listeners if necessary.
if (isset($this->unsorted[$eventName])) {
krsort($this->listeners[$eventName]);
unset($this->unsorted[$eventName]);
}

// Collect listeners and resolve callables if necessary.
foreach ($this->listeners[$eventName] as &$definitions) {
foreach ($definitions as &$definition) {
if (!isset($definition['callable'])) {
$definition['callable'] = array($this->container->get($definition['service']['id']), $definition['service']['method']);
}

$result[] = $definition['callable'];
}
}

return $result;
}

/**
* {@inheritdoc}
*/
public function hasListeners($eventName = null)
{
return (bool) count($this->getListeners($eventName));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this should be optimized by checking $this->listeners[$eventName] directly. There is no need to sort and resolve callables just to know whether we have listeners register.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This does not work because $this->listeners[$eventName] contains an array (keyed by priority) of arrays (the actual definitions). After adding and then removing a listener, $this->listeners[$eventName] will still contain entries, despite the fact that there are no listeners anymore. Also as long as there are no services to resolve, getListeners is cheap. I do not expect hasListeners being used exclusively (i.e. without a call to getListeners or dispatch), thus this optimization wouldn't bring too much anyway.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On removal of the last listener for $eventName, you could unset the array. Though that logic might be just as costly as this.

}

/**
* {@inheritdoc}
*/
public function addListener($eventName, $listener, $priority = 0)
{
$this->listeners[$eventName][$priority][] = array('callable' => $listener);
$this->unsorted[$eventName] = true;
}

/**
* {@inheritdoc}
*/
public function removeListener($eventName, $listener)
{
if (!isset($this->listeners[$eventName])) {
return;
}

foreach ($this->listeners[$eventName] as $priority => $definitions) {
foreach ($definitions as $key => $definition) {
if (!isset($definition['callable'])) {
if (!$this->container->initialized($definition['service']['id'])) {
continue;
}
$definition['callable'] = array($this->container->get($definition['service']['id']), $definition['service']['method']);
}

if ($definition['callable'] === $listener) {
unset($this->listeners[$eventName][$priority][$key]);
}
}
}
}

/**
* {@inheritdoc}
*/
public function addSubscriber(EventSubscriberInterface $subscriber)
{
foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
if (is_string($params)) {
$this->addListener($eventName, array($subscriber, $params));
} elseif (is_string($params[0])) {
$this->addListener($eventName, array($subscriber, $params[0]), isset($params[1]) ? $params[1] : 0);
} else {
foreach ($params as $listener) {
$this->addListener($eventName, array($subscriber, $listener[0]), isset($listener[1]) ? $listener[1] : 0);
}
}
}
}

/**
* {@inheritdoc}
*/
public function removeSubscriber(EventSubscriberInterface $subscriber)
{
foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
if (is_array($params) && is_array($params[0])) {
foreach ($params as $listener) {
$this->removeListener($eventName, array($subscriber, $listener[0]));
}
} else {
$this->removeListener($eventName, array($subscriber, is_string($params) ? $params : $params[0]));
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\EventDispatcher\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;

/**
* Compiler pass to register tagged services for a compiled event dispatcher.
*/
class CompiledRegisterListenersPass implements CompilerPassInterface
{
/**
* Service name of the event dispatcher in processed container.
*
* @var string
*/
private $dispatcherService;

/**
* Tag name used for listeners.
*
* @var string
*/
private $listenerTag;

/**
* Tag name used for subscribers.
*
* @var string
*/
private $subscriberTag;

/**
* Constructor.
*
* @param string $dispatcherService Service name of the event dispatcher in processed container
* @param string $listenerTag Tag name used for listeners
* @param string $subscriberTag Tag name used for subscribers
*/
public function __construct($dispatcherService = 'event_dispatcher', $listenerTag = 'kernel.event_listener', $subscriberTag = 'kernel.event_subscriber')
{
$this->dispatcherService = $dispatcherService;
$this->listenerTag = $listenerTag;
$this->subscriberTag = $subscriberTag;
}

/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition($this->dispatcherService) && !$container->hasAlias($this->dispatcherService)) {
return;
}

$definition = $container->findDefinition($this->dispatcherService);

$listeners = array();

foreach ($container->findTaggedServiceIds($this->listenerTag) as $id => $events) {
$def = $container->getDefinition($id);
if (!$def->isPublic()) {
throw new \InvalidArgumentException(sprintf('The service "%s" must be public as event listeners are lazy-loaded.', $id));
}

if ($def->isAbstract()) {
throw new \InvalidArgumentException(sprintf('The service "%s" must not be abstract as event listeners are lazy-loaded.', $id));
}

foreach ($events as $event) {
$priority = isset($event['priority']) ? $event['priority'] : 0;

if (!isset($event['event'])) {
throw new \InvalidArgumentException(sprintf('Service "%s" must define the "event" attribute on "%s" tags.', $id, $this->listenerTag));
}

if (!isset($event['method'])) {
$event['method'] = 'on'.preg_replace_callback(array(
'/(?<=\b)[a-z]/i',
'/[^a-z0-9]/i',
), function ($matches) { return strtoupper($matches[0]); }, $event['event']);
$event['method'] = preg_replace('/[^a-z0-9]/i', '', $event['method']);
}

$listeners[$event['event']][$priority][] = array('service' => array('id' => $id, 'method' => $event['method']));
}
}

foreach ($container->findTaggedServiceIds($this->subscriberTag) as $id => $attributes) {
$def = $container->getDefinition($id);
if (!$def->isPublic()) {
throw new \InvalidArgumentException(sprintf('The service "%s" must be public as event subscribers are lazy-loaded.', $id));
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the handling of abstract definitions is missing here (similar to what you do above for the listener tag)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is also absent in RegisterListenersPass. Given that CompiledRegisterListenersPass shares quite a bit of code with the other pass, it would make sense to extract an abstract base class and fix those things there after this PR was merged. Opinions?

if ($def->isAbstract()) {
throw new \InvalidArgumentException(sprintf('The service "%s" must not be abstract as event subscribers are lazy-loaded.', $id));
}

// We must assume that the class value has been correctly filled, even if the service is created by a factory
$class = $container->getParameterBag()->resolveValue($def->getClass());

$refClass = new \ReflectionClass($class);
$interface = 'Symfony\Component\EventDispatcher\EventSubscriberInterface';
if (!$refClass->implementsInterface($interface)) {
throw new \InvalidArgumentException(sprintf('The service "%s" must implement interface "%s".', $id, $interface));
}

// Get all subscribed events.
foreach ($class::getSubscribedEvents() as $eventName => $params) {
if (is_string($params)) {
$priority = 0;
$listeners[$eventName][$priority][] = array('service' => array('id' => $id, 'method' => $params));
} elseif (is_string($params[0])) {
$priority = isset($params[1]) ? $params[1] : 0;
$listeners[$eventName][$priority][] = array('service' => array('id' => $id, 'method' => $params[0]));
} else {
foreach ($params as $listener) {
$priority = isset($listener[1]) ? $listener[1] : 0;
$listeners[$eventName][$priority][] = array('service' => array('id' => $id, 'method' => $listener[0]));
}
}
}
}

foreach (array_keys($listeners) as $eventName) {
krsort($listeners[$eventName]);
}

$definition->addArgument($listeners);
}
}
Loading