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

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 array $dispatchDepth = [];
  39.     private array $calledListenerInfos = [];
  40.     private array $calledOriginalListeners = [];
  41.     private ?RequestStack $requestStack;
  42.     private string $currentRequestHash '';
  43.     public function __construct(EventDispatcherInterface $dispatcherStopwatch $stopwatch, ?LoggerInterface $logger null, ?RequestStack $requestStack null)
  44.     {
  45.         $this->dispatcher $dispatcher;
  46.         $this->stopwatch $stopwatch;
  47.         $this->logger $logger;
  48.         $this->requestStack $requestStack;
  49.     }
  50.     /**
  51.      * @return void
  52.      */
  53.     public function addListener(string $eventName, callable|array $listenerint $priority 0)
  54.     {
  55.         $this->dispatcher->addListener($eventName$listener$priority);
  56.     }
  57.     /**
  58.      * @return void
  59.      */
  60.     public function addSubscriber(EventSubscriberInterface $subscriber)
  61.     {
  62.         $this->dispatcher->addSubscriber($subscriber);
  63.     }
  64.     /**
  65.      * @return void
  66.      */
  67.     public function removeListener(string $eventName, callable|array $listener)
  68.     {
  69.         if (isset($this->wrappedListeners[$eventName])) {
  70.             foreach ($this->wrappedListeners[$eventName] as $index => $wrappedListener) {
  71.                 if ($wrappedListener->getWrappedListener() === $listener || ($listener instanceof \Closure && $wrappedListener->getWrappedListener() == $listener)) {
  72.                     $listener $wrappedListener;
  73.                     unset($this->wrappedListeners[$eventName][$index]);
  74.                     break;
  75.                 }
  76.             }
  77.         }
  78.         $this->dispatcher->removeListener($eventName$listener);
  79.     }
  80.     /**
  81.      * @return void
  82.      */
  83.     public function removeSubscriber(EventSubscriberInterface $subscriber)
  84.     {
  85.         $this->dispatcher->removeSubscriber($subscriber);
  86.     }
  87.     public function getListeners(?string $eventName null): array
  88.     {
  89.         return $this->dispatcher->getListeners($eventName);
  90.     }
  91.     public function getListenerPriority(string $eventName, callable|array $listener): ?int
  92.     {
  93.         // we might have wrapped listeners for the event (if called while dispatching)
  94.         // in that case get the priority by wrapper
  95.         if (isset($this->wrappedListeners[$eventName])) {
  96.             foreach ($this->wrappedListeners[$eventName] as $wrappedListener) {
  97.                 if ($wrappedListener->getWrappedListener() === $listener || ($listener instanceof \Closure && $wrappedListener->getWrappedListener() == $listener)) {
  98.                     return $this->dispatcher->getListenerPriority($eventName$wrappedListener);
  99.                 }
  100.             }
  101.         }
  102.         return $this->dispatcher->getListenerPriority($eventName$listener);
  103.     }
  104.     public function hasListeners(?string $eventName null): bool
  105.     {
  106.         return $this->dispatcher->hasListeners($eventName);
  107.     }
  108.     public function dispatch(object $event, ?string $eventName null): object
  109.     {
  110.         $eventName ??= $event::class;
  111.         $this->callStack ??= new \SplObjectStorage();
  112.         $currentRequestHash $this->currentRequestHash $this->requestStack && ($request $this->requestStack->getCurrentRequest()) ? spl_object_hash($request) : '';
  113.         if (null !== $this->logger && $event instanceof StoppableEventInterface && $event->isPropagationStopped()) {
  114.             $this->logger->debug(\sprintf('The "%s" event is already stopped. No listeners have been called.'$eventName));
  115.         }
  116.         $this->preProcess($eventName);
  117.         try {
  118.             $this->beforeDispatch($eventName$event);
  119.             try {
  120.                 $e $this->stopwatch->start($eventName'section');
  121.                 try {
  122.                     $this->dispatcher->dispatch($event$eventName);
  123.                 } finally {
  124.                     if ($e->isStarted()) {
  125.                         $e->stop();
  126.                     }
  127.                 }
  128.             } finally {
  129.                 $this->afterDispatch($eventName$event);
  130.             }
  131.         } finally {
  132.             $this->currentRequestHash $currentRequestHash;
  133.             $this->postProcess($eventName);
  134.         }
  135.         return $event;
  136.     }
  137.     public function getCalledListeners(?Request $request null): array
  138.     {
  139.         if (!$this->calledListenerInfos) {
  140.             return [];
  141.         }
  142.         $hash $request spl_object_hash($request) : null;
  143.         $called = [];
  144.         foreach ($this->calledListenerInfos as $requestHash => $infos) {
  145.             if (null === $hash || $hash === $requestHash) {
  146.                 $called[] = $infos;
  147.             }
  148.         }
  149.         return $called array_merge(...$called) : [];
  150.     }
  151.     public function getNotCalledListeners(?Request $request null): array
  152.     {
  153.         try {
  154.             $allListeners $this->dispatcher instanceof EventDispatcher $this->getListenersWithPriority() : $this->getListenersWithoutPriority();
  155.         } catch (\Exception $e) {
  156.             $this->logger?->info('An exception was thrown while getting the uncalled listeners.', ['exception' => $e]);
  157.             // unable to retrieve the uncalled listeners
  158.             return [];
  159.         }
  160.         $hash $request spl_object_hash($request) : null;
  161.         $calledListeners = [];
  162.         foreach ($this->calledOriginalListeners as $requestHash => $eventListeners) {
  163.             if (null === $hash || $hash === $requestHash) {
  164.                 $calledListeners[] = array_merge(...array_values($eventListeners));
  165.             }
  166.         }
  167.         $calledListeners $calledListeners array_merge(...$calledListeners) : [];
  168.         $notCalled = [];
  169.         foreach ($allListeners as $eventName => $listeners) {
  170.             foreach ($listeners as [$listener$priority]) {
  171.                 if (!\in_array($listener$calledListenerstrue)) {
  172.                     if (!$listener instanceof WrappedListener) {
  173.                         $listener = new WrappedListener($listenernull$this->stopwatch$this$priority);
  174.                     }
  175.                     $notCalled[] = $listener->getInfo($eventName);
  176.                 }
  177.             }
  178.         }
  179.         uasort($notCalled$this->sortNotCalledListeners(...));
  180.         return $notCalled;
  181.     }
  182.     public function getOrphanedEvents(?Request $request null): array
  183.     {
  184.         if ($request) {
  185.             return $this->orphanedEvents[spl_object_hash($request)] ?? [];
  186.         }
  187.         if (!$this->orphanedEvents) {
  188.             return [];
  189.         }
  190.         return array_merge(...array_values($this->orphanedEvents));
  191.     }
  192.     /**
  193.      * @return void
  194.      */
  195.     public function reset()
  196.     {
  197.         $this->callStack null;
  198.         $this->orphanedEvents = [];
  199.         $this->currentRequestHash '';
  200.         $this->dispatchDepth = [];
  201.         $this->calledListenerInfos = [];
  202.         $this->calledOriginalListeners = [];
  203.     }
  204.     /**
  205.      * Proxies all method calls to the original event dispatcher.
  206.      *
  207.      * @param string $method    The method name
  208.      * @param array  $arguments The method arguments
  209.      */
  210.     public function __call(string $method, array $arguments): mixed
  211.     {
  212.         return $this->dispatcher->{$method}(...$arguments);
  213.     }
  214.     /**
  215.      * Called before dispatching the event.
  216.      *
  217.      * @return void
  218.      */
  219.     protected function beforeDispatch(string $eventNameobject $event)
  220.     {
  221.     }
  222.     /**
  223.      * Called after dispatching the event.
  224.      *
  225.      * @return void
  226.      */
  227.     protected function afterDispatch(string $eventNameobject $event)
  228.     {
  229.     }
  230.     private function preProcess(string $eventName): void
  231.     {
  232.         $this->dispatchDepth[$eventName] = ($this->dispatchDepth[$eventName] ?? 0) + 1;
  233.         if (!$this->dispatcher->hasListeners($eventName)) {
  234.             $this->orphanedEvents[$this->currentRequestHash][] = $eventName;
  235.             return;
  236.         }
  237.         foreach ($this->dispatcher->getListeners($eventName) as $listener) {
  238.             $priority $this->getListenerPriority($eventName$listener) ?? 0;
  239.             $wrappedListener = new WrappedListener($listener instanceof WrappedListener $listener->getWrappedListener() : $listenernull$this->stopwatch$this);
  240.             $this->wrappedListeners[$eventName][] = $wrappedListener;
  241.             $this->dispatcher->removeListener($eventName$listener);
  242.             $this->dispatcher->addListener($eventName$wrappedListener$priority);
  243.             $this->callStack[$wrappedListener] = [$eventName$this->currentRequestHash];
  244.         }
  245.     }
  246.     private function postProcess(string $eventName): void
  247.     {
  248.         if (null === $this->callStack) {
  249.             return;
  250.         }
  251.         $this->dispatchDepth[$eventName] = ($this->dispatchDepth[$eventName] ?? 1) - 1;
  252.         unset($this->wrappedListeners[$eventName]);
  253.         $skipped false;
  254.         foreach ($this->dispatcher->getListeners($eventName) as $listener) {
  255.             if (!$listener instanceof WrappedListener) { // #12845: a new listener was added during dispatch.
  256.                 continue;
  257.             }
  258.             // Unwrap listener
  259.             $priority $this->getListenerPriority($eventName$listener);
  260.             $this->dispatcher->removeListener($eventName$listener);
  261.             $this->dispatcher->addListener($eventName$listener->getWrappedListener(), $priority);
  262.             if (null !== $this->logger) {
  263.                 $context = ['event' => $eventName'listener' => $listener->getPretty()];
  264.             }
  265.             if ($listener->wasCalled()) {
  266.                 $this->logger?->debug('Notified event "{event}" to listener "{listener}".'$context);
  267.                 $original $listener->getWrappedListener();
  268.                 if (!\in_array($original$this->calledOriginalListeners[$this->currentRequestHash][$eventName] ?? [], true)) {
  269.                     $this->calledOriginalListeners[$this->currentRequestHash][$eventName][] = $original;
  270.                     $this->calledListenerInfos[$this->currentRequestHash][] = $listener->getInfo($eventName);
  271.                 }
  272.             }
  273.             unset($this->callStack[$listener]);
  274.             if (null !== $this->logger && $skipped) {
  275.                 $this->logger->debug('Listener "{listener}" was not called for event "{event}".'$context);
  276.             }
  277.             if ($listener->stoppedPropagation()) {
  278.                 $this->logger?->debug('Listener "{listener}" stopped propagation of the event "{event}".'$context);
  279.                 $skipped true;
  280.             }
  281.         }
  282.         if ($this->dispatchDepth[$eventName]) {
  283.             return;
  284.         }
  285.         // Clean up stale callStack entries left by nested same-event dispatches
  286.         $stale = [];
  287.         foreach ($this->callStack as $listener) {
  288.             if ($this->callStack->getInfo()[0] === $eventName) {
  289.                 $stale[] = $listener;
  290.             }
  291.         }
  292.         foreach ($stale as $listener) {
  293.             if ($listener->wasCalled()) {
  294.                 $original $listener->getWrappedListener();
  295.                 if (!\in_array($original$this->calledOriginalListeners[$this->currentRequestHash][$eventName] ?? [], true)) {
  296.                     $this->calledOriginalListeners[$this->currentRequestHash][$eventName][] = $original;
  297.                     $this->calledListenerInfos[$this->currentRequestHash][] = $listener->getInfo($eventName);
  298.                 }
  299.             }
  300.             unset($this->callStack[$listener]);
  301.         }
  302.     }
  303.     private function sortNotCalledListeners(array $a, array $b): int
  304.     {
  305.         if (!== $cmp strcmp($a['event'], $b['event'])) {
  306.             return $cmp;
  307.         }
  308.         if (\is_int($a['priority']) && !\is_int($b['priority'])) {
  309.             return 1;
  310.         }
  311.         if (!\is_int($a['priority']) && \is_int($b['priority'])) {
  312.             return -1;
  313.         }
  314.         if ($a['priority'] === $b['priority']) {
  315.             return 0;
  316.         }
  317.         if ($a['priority'] > $b['priority']) {
  318.             return -1;
  319.         }
  320.         return 1;
  321.     }
  322.     private function getListenersWithPriority(): array
  323.     {
  324.         $result = [];
  325.         $allListeners = new \ReflectionProperty(EventDispatcher::class, 'listeners');
  326.         foreach ($allListeners->getValue($this->dispatcher) as $eventName => $listenersByPriority) {
  327.             foreach ($listenersByPriority as $priority => $listeners) {
  328.                 foreach ($listeners as $listener) {
  329.                     $result[$eventName][] = [$listener$priority];
  330.                 }
  331.             }
  332.         }
  333.         return $result;
  334.     }
  335.     private function getListenersWithoutPriority(): array
  336.     {
  337.         $result = [];
  338.         foreach ($this->getListeners() as $eventName => $listeners) {
  339.             foreach ($listeners as $listener) {
  340.                 $result[$eventName][] = [$listenernull];
  341.             }
  342.         }
  343.         return $result;
  344.     }
  345. }