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

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