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

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