RegisterEventSubscribersPass.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. namespace Drupal\Core\DependencyInjection\Compiler;
  3. use Symfony\Component\DependencyInjection\ContainerBuilder;
  4. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  5. /**
  6. * Registers all event subscribers to the event dispatcher.
  7. */
  8. class RegisterEventSubscribersPass implements CompilerPassInterface {
  9. /**
  10. * {@inheritdoc}
  11. */
  12. public function process(ContainerBuilder $container) {
  13. if (!$container->hasDefinition('event_dispatcher')) {
  14. return;
  15. }
  16. $definition = $container->getDefinition('event_dispatcher');
  17. $event_subscriber_info = [];
  18. foreach ($container->findTaggedServiceIds('event_subscriber') as $id => $attributes) {
  19. // We must assume that the class value has been correctly filled, even if
  20. // the service is created by a factory.
  21. $class = $container->getDefinition($id)->getClass();
  22. $refClass = new \ReflectionClass($class);
  23. $interface = 'Symfony\Component\EventDispatcher\EventSubscriberInterface';
  24. if (!$refClass->implementsInterface($interface)) {
  25. throw new \InvalidArgumentException(sprintf('Service "%s" must implement interface "%s".', $id, $interface));
  26. }
  27. // Get all subscribed events.
  28. foreach ($class::getSubscribedEvents() as $event_name => $params) {
  29. if (is_string($params)) {
  30. $priority = 0;
  31. $event_subscriber_info[$event_name][$priority][] = ['service' => [$id, $params]];
  32. }
  33. elseif (is_string($params[0])) {
  34. $priority = isset($params[1]) ? $params[1] : 0;
  35. $event_subscriber_info[$event_name][$priority][] = ['service' => [$id, $params[0]]];
  36. }
  37. else {
  38. foreach ($params as $listener) {
  39. $priority = isset($listener[1]) ? $listener[1] : 0;
  40. $event_subscriber_info[$event_name][$priority][] = ['service' => [$id, $listener[0]]];
  41. }
  42. }
  43. }
  44. }
  45. foreach (array_keys($event_subscriber_info) as $event_name) {
  46. krsort($event_subscriber_info[$event_name]);
  47. }
  48. $definition->addArgument($event_subscriber_info);
  49. }
  50. }