ContainerAwareEventDispatcher.php 9.46 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\Component\EventDispatcher;

5
use Symfony\Component\DependencyInjection\ContainerInterface;
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * 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 roughly 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 ContainerAwareEventDispatcher implements EventDispatcherInterface {

  /**
   * The service container.
   *
39
   * @var \Symfony\Component\DependencyInjection\ContainerInterface
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
   */
  protected $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 [service id, method]
   *
   * A service entry will be resolved to a callable only just before its
   * invocation.
   *
   * @var array
   */
  protected $listeners;

  /**
   * Whether listeners need to be sorted prior to dispatch, keyed by event name.
   *
   * @var TRUE[]
   */
  protected $unsorted;

  /**
   * Constructs a container aware event dispatcher.
   *
69
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
70 71 72 73 74 75 76 77 78 79
   *   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
   *   an associative array with one of the following key value pairs:
   *   - callable: A callable listener
   *   - service: An array of the form [service id, method]
   *   A service entry will be resolved to a callable only just before its
   *   invocation.
   */
80
  public function __construct(ContainerInterface $container, array $listeners = []) {
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
    $this->container = $container;
    $this->listeners = $listeners;
    $this->unsorted = [];
  }

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

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

      // Invoke listeners and resolve callables if necessary.
      foreach ($this->listeners[$event_name] as $priority => &$definitions) {
        foreach ($definitions as $key => &$definition) {
          if (!isset($definition['callable'])) {
            $definition['callable'] = [$this->container->get($definition['service'][0]), $definition['service'][1]];
          }
107 108 109
          if (is_array($definition['callable']) && isset($definition['callable'][0]) && $definition['callable'][0] instanceof \Closure) {
            $definition['callable'][0] = $definition['callable'][0]();
          }
110

111
          call_user_func($definition['callable'], $event, $event_name, $this);
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
          if ($event->isPropagationStopped()) {
            return $event;
          }
        }
      }
    }

    return $event;
  }

  /**
   * {@inheritdoc}
   */
  public function getListeners($event_name = NULL) {
    $result = [];

    if ($event_name === NULL) {
      // If event name was omitted, collect all listeners of all events.
      foreach (array_keys($this->listeners) as $event_name) {
        $listeners = $this->getListeners($event_name);
        if (!empty($listeners)) {
          $result[$event_name] = $listeners;
        }
      }
    }
    elseif (isset($this->listeners[$event_name])) {
      // Sort listeners if necessary.
      if (isset($this->unsorted[$event_name])) {
        krsort($this->listeners[$event_name]);
        unset($this->unsorted[$event_name]);
      }

      // Collect listeners and resolve callables if necessary.
      foreach ($this->listeners[$event_name] as $priority => &$definitions) {
        foreach ($definitions as $key => &$definition) {
          if (!isset($definition['callable'])) {
            $definition['callable'] = [$this->container->get($definition['service'][0]), $definition['service'][1]];
          }
150 151 152
          if (is_array($definition['callable']) && isset($definition['callable'][0]) && $definition['callable'][0] instanceof \Closure) {
            $definition['callable'][0] = $definition['callable'][0]();
          }
153 154 155 156 157 158 159 160 161

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

    return $result;
  }

162 163 164
  /**
   * {@inheritdoc}
   */
165 166
  public function getListenerPriority($event_name, $listener) {
    if (!isset($this->listeners[$event_name])) {
167 168
      return;
    }
169 170
    if (is_array($listener) && isset($listener[0]) && $listener[0] instanceof \Closure) {
      $listener[0] = $listener[0]();
171 172
    }
    // Resolve service definitions if the listener has not been found so far.
173
    foreach ($this->listeners[$event_name] as $priority => &$definitions) {
174 175 176 177
      foreach ($definitions as $key => &$definition) {
        if (!isset($definition['callable'])) {
          // Once the callable is retrieved we keep it for subsequent method
          // invocations on this class.
178 179 180 181 182 183 184 185 186 187
          $definition['callable'] = [
            $this->container->get($definition['service'][0]),
            $definition['service'][1],
          ];
        }
        if (is_array($definition['callable']) && isset($definition['callable'][0]) && $definition['callable'][0] instanceof \Closure) {
          $definition['callable'][0] = $definition['callable'][0]();
        }
        if ($definition['callable'] === $listener) {
          return $priority;
188 189 190 191 192
        }
      }
    }
  }

193 194 195 196
  /**
   * {@inheritdoc}
   */
  public function hasListeners($event_name = NULL) {
197 198 199 200 201 202 203 204 205 206 207
    if ($event_name !== NULL) {
      return !empty($this->listeners[$event_name]);
    }

    foreach ($this->listeners as $event_listeners) {
      if ($event_listeners) {
        return TRUE;
      }
    }

    return FALSE;
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
  }

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

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

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

235 236 237 238 239 240 241
        if (is_array($definition['callable']) && isset($definition['callable'][0]) && $definition['callable'][0] instanceof \Closure && !$listener instanceof \Closure) {
          $definition['callable'][0] = $definition['callable'][0]();
        }

        if (is_array($definition['callable']) && isset($definition['callable'][0]) && !$definition['callable'][0] instanceof \Closure && is_array($listener) && isset($listener[0]) && $listener[0] instanceof \Closure) {
          $listener[0] = $listener[0]();
        }
242
        if ($definition['callable'] === $listener) {
243
          unset($definitions[$key]);
244 245
        }
      }
246 247 248 249 250 251
      if ($definitions) {
        $this->listeners[$event_name][$priority] = $definitions;
      }
      else {
        unset($this->listeners[$event_name][$priority]);
      }
252 253 254 255 256 257 258 259 260
    }
  }

  /**
   * {@inheritdoc}
   */
  public function addSubscriber(EventSubscriberInterface $subscriber) {
    foreach ($subscriber->getSubscribedEvents() as $event_name => $params) {
      if (is_string($params)) {
261
        $this->addListener($event_name, [$subscriber, $params]);
262 263
      }
      elseif (is_string($params[0])) {
264
        $this->addListener($event_name, [$subscriber, $params[0]], isset($params[1]) ? $params[1] : 0);
265 266 267
      }
      else {
        foreach ($params as $listener) {
268
          $this->addListener($event_name, [$subscriber, $listener[0]], isset($listener[1]) ? $listener[1] : 0);
269 270 271 272 273 274 275 276 277 278 279 280
        }
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function removeSubscriber(EventSubscriberInterface $subscriber) {
    foreach ($subscriber->getSubscribedEvents() as $event_name => $params) {
      if (is_array($params) && is_array($params[0])) {
        foreach ($params as $listener) {
281
          $this->removeListener($event_name, [$subscriber, $listener[0]]);
282 283 284
        }
      }
      else {
285
        $this->removeListener($event_name, [$subscriber, is_string($params) ? $params : $params[0]]);
286 287 288 289 290
      }
    }
  }

}