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

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