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

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