vendor/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php line 153

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Component\EventDispatcher\Debug;
  11. use Psr\EventDispatcher\StoppableEventInterface;
  12. use Psr\Log\LoggerInterface;
  13. use Symfony\Component\EventDispatcher\EventDispatcher;
  14. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  15. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use Symfony\Component\HttpFoundation\RequestStack;
  18. use Symfony\Component\Stopwatch\Stopwatch;
  19. use Symfony\Contracts\Service\ResetInterface;
  20. /**
  21.  * Collects some data about event listeners.
  22.  *
  23.  * This event dispatcher delegates the dispatching to another one.
  24.  *
  25.  * @author Fabien Potencier <fabien@symfony.com>
  26.  */
  27. class TraceableEventDispatcher implements EventDispatcherInterfaceResetInterface
  28. {
  29.     protected $logger;
  30.     protected $stopwatch;
  31.     /**
  32.      * @var \SplObjectStorage<WrappedListener, array{string, string}>|null
  33.      */
  34.     private ?\SplObjectStorage $callStack null;
  35.     private EventDispatcherInterface $dispatcher;
  36.     private array $wrappedListeners = [];
  37.     private array $orphanedEvents = [];
  38.     private ?RequestStack $requestStack;
  39.     private string $currentRequestHash '';
  40.     public function __construct(EventDispatcherInterface $dispatcherStopwatch $stopwatchLoggerInterface $logger nullRequestStack $requestStack null)
  41.     {
  42.         $this->dispatcher $dispatcher;
  43.         $this->stopwatch $stopwatch;
  44.         $this->logger $logger;
  45.         $this->requestStack $requestStack;
  46.     }
  47.     /**
  48.      * {@inheritdoc}
  49.      */
  50.     public function addListener(string $eventName, callable|array $listenerint $priority 0)
  51.     {
  52.         $this->dispatcher->addListener($eventName$listener$priority);
  53.     }
  54.     /**
  55.      * {@inheritdoc}
  56.      */
  57.     public function addSubscriber(EventSubscriberInterface $subscriber)
  58.     {
  59.         $this->dispatcher->addSubscriber($subscriber);
  60.     }
  61.     /**
  62.      * {@inheritdoc}
  63.      */
  64.     public function removeListener(string $eventName, callable|array $listener)
  65.     {
  66.         if (isset($this->wrappedListeners[$eventName])) {
  67.             foreach ($this->wrappedListeners[$eventName] as $index => $wrappedListener) {
  68.                 if ($wrappedListener->getWrappedListener() === $listener || ($listener instanceof \Closure && $wrappedListener->getWrappedListener() == $listener)) {
  69.                     $listener $wrappedListener;
  70.                     unset($this->wrappedListeners[$eventName][$index]);
  71.                     break;
  72.                 }
  73.             }
  74.         }
  75.         return $this->dispatcher->removeListener($eventName$listener);
  76.     }
  77.     /**
  78.      * {@inheritdoc}
  79.      */
  80.     public function removeSubscriber(EventSubscriberInterface $subscriber)
  81.     {
  82.         return $this->dispatcher->removeSubscriber($subscriber);
  83.     }
  84.     /**
  85.      * {@inheritdoc}
  86.      */
  87.     public function getListeners(string $eventName null): array
  88.     {
  89.         return $this->dispatcher->getListeners($eventName);
  90.     }
  91.     /**
  92.      * {@inheritdoc}
  93.      */
  94.     public function getListenerPriority(string $eventName, callable|array $listener): ?int
  95.     {
  96.         // we might have wrapped listeners for the event (if called while dispatching)
  97.         // in that case get the priority by wrapper
  98.         if (isset($this->wrappedListeners[$eventName])) {
  99.             foreach ($this->wrappedListeners[$eventName] as $wrappedListener) {
  100.                 if ($wrappedListener->getWrappedListener() === $listener || ($listener instanceof \Closure && $wrappedListener->getWrappedListener() == $listener)) {
  101.                     return $this->dispatcher->getListenerPriority($eventName$wrappedListener);
  102.                 }
  103.             }
  104.         }
  105.         return $this->dispatcher->getListenerPriority($eventName$listener);
  106.     }
  107.     /**
  108.      * {@inheritdoc}
  109.      */
  110.     public function hasListeners(string $eventName null): bool
  111.     {
  112.         return $this->dispatcher->hasListeners($eventName);
  113.     }
  114.     /**
  115.      * {@inheritdoc}
  116.      */
  117.     public function dispatch(object $eventstring $eventName null): object
  118.     {
  119.         $eventName ??= \get_class($event);
  120.         if (null === $this->callStack) {
  121.             $this->callStack = new \SplObjectStorage();
  122.         }
  123.         $currentRequestHash $this->currentRequestHash $this->requestStack && ($request $this->requestStack->getCurrentRequest()) ? spl_object_hash($request) : '';
  124.         if (null !== $this->logger && $event instanceof StoppableEventInterface && $event->isPropagationStopped()) {
  125.             $this->logger->debug(sprintf('The "%s" event is already stopped. No listeners have been called.'$eventName));
  126.         }
  127.         $this->preProcess($eventName);
  128.         try {
  129.             $this->beforeDispatch($eventName$event);
  130.             try {
  131.                 $e $this->stopwatch->start($eventName'section');
  132.                 try {
  133.                     $this->dispatcher->dispatch($event$eventName);
  134.                 } finally {
  135.                     if ($e->isStarted()) {
  136.                         $e->stop();
  137.                     }
  138.                 }
  139.             } finally {
  140.                 $this->afterDispatch($eventName$event);
  141.             }
  142.         } finally {
  143.             $this->currentRequestHash $currentRequestHash;
  144.             $this->postProcess($eventName);
  145.         }
  146.         return $event;
  147.     }
  148.     public function getCalledListeners(Request $request null): array
  149.     {
  150.         if (null === $this->callStack) {
  151.             return [];
  152.         }
  153.         $hash $request spl_object_hash($request) : null;
  154.         $called = [];
  155.         foreach ($this->callStack as $listener) {
  156.             [$eventName$requestHash] = $this->callStack->getInfo();
  157.             if (null === $hash || $hash === $requestHash) {
  158.                 $called[] = $listener->getInfo($eventName);
  159.             }
  160.         }
  161.         return $called;
  162.     }
  163.     public function getNotCalledListeners(Request $request null): array
  164.     {
  165.         try {
  166.             $allListeners $this->dispatcher instanceof EventDispatcher $this->getListenersWithPriority() : $this->getListenersWithoutPriority();
  167.         } catch (\Exception $e) {
  168.             $this->logger?->info('An exception was thrown while getting the uncalled listeners.', ['exception' => $e]);
  169.             // unable to retrieve the uncalled listeners
  170.             return [];
  171.         }
  172.         $hash $request spl_object_hash($request) : null;
  173.         $calledListeners = [];
  174.         if (null !== $this->callStack) {
  175.             foreach ($this->callStack as $calledListener) {
  176.                 [, $requestHash] = $this->callStack->getInfo();
  177.                 if (null === $hash || $hash === $requestHash) {
  178.                     $calledListeners[] = $calledListener->getWrappedListener();
  179.                 }
  180.             }
  181.         }
  182.         $notCalled = [];
  183.         foreach ($allListeners as $eventName => $listeners) {
  184.             foreach ($listeners as [$listener$priority]) {
  185.                 if (!\in_array($listener$calledListenerstrue)) {
  186.                     if (!$listener instanceof WrappedListener) {
  187.                         $listener = new WrappedListener($listenernull$this->stopwatch$this$priority);
  188.                     }
  189.                     $notCalled[] = $listener->getInfo($eventName);
  190.                 }
  191.             }
  192.         }
  193.         uasort($notCalled$this->sortNotCalledListeners(...));
  194.         return $notCalled;
  195.     }
  196.     public function getOrphanedEvents(Request $request null): array
  197.     {
  198.         if ($request) {
  199.             return $this->orphanedEvents[spl_object_hash($request)] ?? [];
  200.         }
  201.         if (!$this->orphanedEvents) {
  202.             return [];
  203.         }
  204.         return array_merge(...array_values($this->orphanedEvents));
  205.     }
  206.     public function reset()
  207.     {
  208.         $this->callStack null;
  209.         $this->orphanedEvents = [];
  210.         $this->currentRequestHash '';
  211.     }
  212.     /**
  213.      * Proxies all method calls to the original event dispatcher.
  214.      *
  215.      * @param string $method    The method name
  216.      * @param array  $arguments The method arguments
  217.      */
  218.     public function __call(string $method, array $arguments): mixed
  219.     {
  220.         return $this->dispatcher->{$method}(...$arguments);
  221.     }
  222.     /**
  223.      * Called before dispatching the event.
  224.      */
  225.     protected function beforeDispatch(string $eventNameobject $event)
  226.     {
  227.     }
  228.     /**
  229.      * Called after dispatching the event.
  230.      */
  231.     protected function afterDispatch(string $eventNameobject $event)
  232.     {
  233.     }
  234.     private function preProcess(string $eventName): void
  235.     {
  236.         if (!$this->dispatcher->hasListeners($eventName)) {
  237.             $this->orphanedEvents[$this->currentRequestHash][] = $eventName;
  238.             return;
  239.         }
  240.         foreach ($this->dispatcher->getListeners($eventName) as $listener) {
  241.             $priority $this->getListenerPriority($eventName$listener);
  242.             $wrappedListener = new WrappedListener($listener instanceof WrappedListener $listener->getWrappedListener() : $listenernull$this->stopwatch$this);
  243.             $this->wrappedListeners[$eventName][] = $wrappedListener;
  244.             $this->dispatcher->removeListener($eventName$listener);
  245.             $this->dispatcher->addListener($eventName$wrappedListener$priority);
  246.             $this->callStack->attach($wrappedListener, [$eventName$this->currentRequestHash]);
  247.         }
  248.     }
  249.     private function postProcess(string $eventName): void
  250.     {
  251.         unset($this->wrappedListeners[$eventName]);
  252.         $skipped false;
  253.         foreach ($this->dispatcher->getListeners($eventName) as $listener) {
  254.             if (!$listener instanceof WrappedListener) { // #12845: a new listener was added during dispatch.
  255.                 continue;
  256.             }
  257.             // Unwrap listener
  258.             $priority $this->getListenerPriority($eventName$listener);
  259.             $this->dispatcher->removeListener($eventName$listener);
  260.             $this->dispatcher->addListener($eventName$listener->getWrappedListener(), $priority);
  261.             if (null !== $this->logger) {
  262.                 $context = ['event' => $eventName'listener' => $listener->getPretty()];
  263.             }
  264.             if ($listener->wasCalled()) {
  265.                 $this->logger?->debug('Notified event "{event}" to listener "{listener}".'$context);
  266.             } else {
  267.                 $this->callStack->detach($listener);
  268.             }
  269.             if (null !== $this->logger && $skipped) {
  270.                 $this->logger->debug('Listener "{listener}" was not called for event "{event}".'$context);
  271.             }
  272.             if ($listener->stoppedPropagation()) {
  273.                 $this->logger?->debug('Listener "{listener}" stopped propagation of the event "{event}".'$context);
  274.                 $skipped true;
  275.             }
  276.         }
  277.     }
  278.     private function sortNotCalledListeners(array $a, array $b): int
  279.     {
  280.         if (!== $cmp strcmp($a['event'], $b['event'])) {
  281.             return $cmp;
  282.         }
  283.         if (\is_int($a['priority']) && !\is_int($b['priority'])) {
  284.             return 1;
  285.         }
  286.         if (!\is_int($a['priority']) && \is_int($b['priority'])) {
  287.             return -1;
  288.         }
  289.         if ($a['priority'] === $b['priority']) {
  290.             return 0;
  291.         }
  292.         if ($a['priority'] > $b['priority']) {
  293.             return -1;
  294.         }
  295.         return 1;
  296.     }
  297.     private function getListenersWithPriority(): array
  298.     {
  299.         $result = [];
  300.         $allListeners = new \ReflectionProperty(EventDispatcher::class, 'listeners');
  301.         $allListeners->setAccessible(true);
  302.         foreach ($allListeners->getValue($this->dispatcher) as $eventName => $listenersByPriority) {
  303.             foreach ($listenersByPriority as $priority => $listeners) {
  304.                 foreach ($listeners as $listener) {
  305.                     $result[$eventName][] = [$listener$priority];
  306.                 }
  307.             }
  308.         }
  309.         return $result;
  310.     }
  311.     private function getListenersWithoutPriority(): array
  312.     {
  313.         $result = [];
  314.         foreach ($this->getListeners() as $eventName => $listeners) {
  315.             foreach ($listeners as $listener) {
  316.                 $result[$eventName][] = [$listenernull];
  317.             }
  318.         }
  319.         return $result;
  320.     }
  321. }