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. 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 $dispatcher, Stopwatch $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 $listener, int $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, $calledListeners, true)) {
  172. if (!$listener instanceof WrappedListener) {
  173. $listener = new WrappedListener($listener, null, $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 $eventName, object $event)
  220. {
  221. }
  222. /**
  223. * Called after dispatching the event.
  224. *
  225. * @return void
  226. */
  227. protected function afterDispatch(string $eventName, object $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);
  239. $wrappedListener = new WrappedListener($listener instanceof WrappedListener ? $listener->getWrappedListener() : $listener, null, $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. --$this->dispatchDepth[$eventName];
  249. unset($this->wrappedListeners[$eventName]);
  250. $skipped = false;
  251. foreach ($this->dispatcher->getListeners($eventName) as $listener) {
  252. if (!$listener instanceof WrappedListener) { // #12845: a new listener was added during dispatch.
  253. continue;
  254. }
  255. // Unwrap listener
  256. $priority = $this->getListenerPriority($eventName, $listener);
  257. $this->dispatcher->removeListener($eventName, $listener);
  258. $this->dispatcher->addListener($eventName, $listener->getWrappedListener(), $priority);
  259. if (null !== $this->logger) {
  260. $context = ['event' => $eventName, 'listener' => $listener->getPretty()];
  261. }
  262. if ($listener->wasCalled()) {
  263. $this->logger?->debug('Notified event "{event}" to listener "{listener}".', $context);
  264. $original = $listener->getWrappedListener();
  265. if (!\in_array($original, $this->calledOriginalListeners[$this->currentRequestHash][$eventName] ?? [], true)) {
  266. $this->calledOriginalListeners[$this->currentRequestHash][$eventName][] = $original;
  267. $this->calledListenerInfos[$this->currentRequestHash][] = $listener->getInfo($eventName);
  268. }
  269. }
  270. unset($this->callStack[$listener]);
  271. if (null !== $this->logger && $skipped) {
  272. $this->logger->debug('Listener "{listener}" was not called for event "{event}".', $context);
  273. }
  274. if ($listener->stoppedPropagation()) {
  275. $this->logger?->debug('Listener "{listener}" stopped propagation of the event "{event}".', $context);
  276. $skipped = true;
  277. }
  278. }
  279. if (0 < $this->dispatchDepth[$eventName]) {
  280. return;
  281. }
  282. // Clean up stale callStack entries left by nested same-event dispatches
  283. $stale = [];
  284. foreach ($this->callStack as $listener) {
  285. if ($this->callStack->getInfo()[0] === $eventName) {
  286. $stale[] = $listener;
  287. }
  288. }
  289. foreach ($stale as $listener) {
  290. if ($listener->wasCalled()) {
  291. $original = $listener->getWrappedListener();
  292. if (!\in_array($original, $this->calledOriginalListeners[$this->currentRequestHash][$eventName] ?? [], true)) {
  293. $this->calledOriginalListeners[$this->currentRequestHash][$eventName][] = $original;
  294. $this->calledListenerInfos[$this->currentRequestHash][] = $listener->getInfo($eventName);
  295. }
  296. }
  297. unset($this->callStack[$listener]);
  298. }
  299. }
  300. private function sortNotCalledListeners(array $a, array $b): int
  301. {
  302. if (0 !== $cmp = strcmp($a['event'], $b['event'])) {
  303. return $cmp;
  304. }
  305. if (\is_int($a['priority']) && !\is_int($b['priority'])) {
  306. return 1;
  307. }
  308. if (!\is_int($a['priority']) && \is_int($b['priority'])) {
  309. return -1;
  310. }
  311. if ($a['priority'] === $b['priority']) {
  312. return 0;
  313. }
  314. if ($a['priority'] > $b['priority']) {
  315. return -1;
  316. }
  317. return 1;
  318. }
  319. private function getListenersWithPriority(): array
  320. {
  321. $result = [];
  322. $allListeners = new \ReflectionProperty(EventDispatcher::class, 'listeners');
  323. foreach ($allListeners->getValue($this->dispatcher) as $eventName => $listenersByPriority) {
  324. foreach ($listenersByPriority as $priority => $listeners) {
  325. foreach ($listeners as $listener) {
  326. $result[$eventName][] = [$listener, $priority];
  327. }
  328. }
  329. }
  330. return $result;
  331. }
  332. private function getListenersWithoutPriority(): array
  333. {
  334. $result = [];
  335. foreach ($this->getListeners() as $eventName => $listeners) {
  336. foreach ($listeners as $listener) {
  337. $result[$eventName][] = [$listener, null];
  338. }
  339. }
  340. return $result;
  341. }
  342. }