TraceableEventDispatcher.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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 array $dispatchDepth = [];
  36. private array $calledListenerInfos = [];
  37. private array $calledOriginalListeners = [];
  38. private string $currentRequestHash = '';
  39. public function __construct(
  40. private EventDispatcherInterface $dispatcher,
  41. protected Stopwatch $stopwatch,
  42. protected ?LoggerInterface $logger = null,
  43. private ?RequestStack $requestStack = null,
  44. protected readonly ?\Closure $disabled = null,
  45. ) {
  46. }
  47. public function addListener(string $eventName, callable|array $listener, int $priority = 0): void
  48. {
  49. $this->dispatcher->addListener($eventName, $listener, $priority);
  50. }
  51. public function addSubscriber(EventSubscriberInterface $subscriber): void
  52. {
  53. $this->dispatcher->addSubscriber($subscriber);
  54. }
  55. public function removeListener(string $eventName, callable|array $listener): void
  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. $this->dispatcher->removeListener($eventName, $listener);
  67. }
  68. public function removeSubscriber(EventSubscriberInterface $subscriber): void
  69. {
  70. $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 $event, ?string $eventName = null): object
  94. {
  95. if ($this->disabled?->__invoke()) {
  96. return $this->dispatcher->dispatch($event, $eventName);
  97. }
  98. $eventName ??= $event::class;
  99. $this->callStack ??= new \SplObjectStorage();
  100. $currentRequestHash = $this->currentRequestHash = $this->requestStack && ($request = $this->requestStack->getCurrentRequest()) ? spl_object_hash($request) : '';
  101. if (null !== $this->logger && $event instanceof StoppableEventInterface && $event->isPropagationStopped()) {
  102. $this->logger->debug(\sprintf('The "%s" event is already stopped. No listeners have been called.', $eventName));
  103. }
  104. $this->preProcess($eventName);
  105. try {
  106. $this->beforeDispatch($eventName, $event);
  107. try {
  108. $e = $this->stopwatch->start($eventName, 'section');
  109. try {
  110. $this->dispatcher->dispatch($event, $eventName);
  111. } finally {
  112. if ($e->isStarted()) {
  113. $e->stop();
  114. }
  115. }
  116. } finally {
  117. $this->afterDispatch($eventName, $event);
  118. }
  119. } finally {
  120. $this->currentRequestHash = $currentRequestHash;
  121. $this->postProcess($eventName);
  122. }
  123. return $event;
  124. }
  125. public function getCalledListeners(?Request $request = null): array
  126. {
  127. if (!$this->calledListenerInfos) {
  128. return [];
  129. }
  130. $hash = $request ? spl_object_hash($request) : null;
  131. $called = [];
  132. foreach ($this->calledListenerInfos as $requestHash => $infos) {
  133. if (null === $hash || $hash === $requestHash) {
  134. $called[] = $infos;
  135. }
  136. }
  137. return $called ? array_merge(...$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. foreach ($this->calledOriginalListeners as $requestHash => $eventListeners) {
  151. if (null === $hash || $hash === $requestHash) {
  152. $calledListeners[] = array_merge(...array_values($eventListeners));
  153. }
  154. }
  155. $calledListeners = $calledListeners ? array_merge(...$calledListeners) : [];
  156. $notCalled = [];
  157. foreach ($allListeners as $eventName => $listeners) {
  158. foreach ($listeners as [$listener, $priority]) {
  159. if (!\in_array($listener, $calledListeners, true)) {
  160. if (!$listener instanceof WrappedListener) {
  161. $listener = new WrappedListener($listener, null, $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(): void
  181. {
  182. $this->callStack = null;
  183. $this->orphanedEvents = [];
  184. $this->currentRequestHash = '';
  185. $this->dispatchDepth = [];
  186. $this->calledListenerInfos = [];
  187. $this->calledOriginalListeners = [];
  188. }
  189. /**
  190. * Proxies all method calls to the original event dispatcher.
  191. *
  192. * @param string $method The method name
  193. * @param array $arguments The method arguments
  194. */
  195. public function __call(string $method, array $arguments): mixed
  196. {
  197. return $this->dispatcher->{$method}(...$arguments);
  198. }
  199. /**
  200. * Called before dispatching the event.
  201. */
  202. protected function beforeDispatch(string $eventName, object $event): void
  203. {
  204. }
  205. /**
  206. * Called after dispatching the event.
  207. */
  208. protected function afterDispatch(string $eventName, object $event): void
  209. {
  210. }
  211. private function preProcess(string $eventName): void
  212. {
  213. $this->dispatchDepth[$eventName] = ($this->dispatchDepth[$eventName] ?? 0) + 1;
  214. if (!$this->dispatcher->hasListeners($eventName)) {
  215. $this->orphanedEvents[$this->currentRequestHash][] = $eventName;
  216. return;
  217. }
  218. foreach ($this->dispatcher->getListeners($eventName) as $listener) {
  219. $priority = $this->getListenerPriority($eventName, $listener) ?? 0;
  220. $wrappedListener = new WrappedListener($listener instanceof WrappedListener ? $listener->getWrappedListener() : $listener, null, $this->stopwatch, $this);
  221. $this->wrappedListeners[$eventName][] = $wrappedListener;
  222. $this->dispatcher->removeListener($eventName, $listener);
  223. $this->dispatcher->addListener($eventName, $wrappedListener, $priority);
  224. $this->callStack[$wrappedListener] = [$eventName, $this->currentRequestHash];
  225. }
  226. }
  227. private function postProcess(string $eventName): void
  228. {
  229. if (null === $this->callStack) {
  230. return;
  231. }
  232. $this->dispatchDepth[$eventName] = ($this->dispatchDepth[$eventName] ?? 1) - 1;
  233. unset($this->wrappedListeners[$eventName]);
  234. $skipped = false;
  235. foreach ($this->dispatcher->getListeners($eventName) as $listener) {
  236. if (!$listener instanceof WrappedListener) { // #12845: a new listener was added during dispatch.
  237. continue;
  238. }
  239. // Unwrap listener
  240. $priority = $this->getListenerPriority($eventName, $listener);
  241. $this->dispatcher->removeListener($eventName, $listener);
  242. $this->dispatcher->addListener($eventName, $listener->getWrappedListener(), $priority);
  243. if (null !== $this->logger) {
  244. $context = ['event' => $eventName, 'listener' => $listener->getPretty()];
  245. }
  246. if ($listener->wasCalled()) {
  247. $this->logger?->debug('Notified event "{event}" to listener "{listener}".', $context);
  248. $original = $listener->getWrappedListener();
  249. if (!\in_array($original, $this->calledOriginalListeners[$this->currentRequestHash][$eventName] ?? [], true)) {
  250. $this->calledOriginalListeners[$this->currentRequestHash][$eventName][] = $original;
  251. $this->calledListenerInfos[$this->currentRequestHash][] = $listener->getInfo($eventName);
  252. }
  253. }
  254. unset($this->callStack[$listener]);
  255. if (null !== $this->logger && $skipped) {
  256. $this->logger->debug('Listener "{listener}" was not called for event "{event}".', $context);
  257. }
  258. if ($listener->stoppedPropagation()) {
  259. $this->logger?->debug('Listener "{listener}" stopped propagation of the event "{event}".', $context);
  260. $skipped = true;
  261. }
  262. }
  263. if (0 < $this->dispatchDepth[$eventName]) {
  264. return;
  265. }
  266. // Clean up stale callStack entries left by nested same-event dispatches
  267. $stale = [];
  268. foreach ($this->callStack as $listener) {
  269. if ($this->callStack->getInfo()[0] === $eventName) {
  270. $stale[] = $listener;
  271. }
  272. }
  273. foreach ($stale as $listener) {
  274. if ($listener->wasCalled()) {
  275. $original = $listener->getWrappedListener();
  276. if (!\in_array($original, $this->calledOriginalListeners[$this->currentRequestHash][$eventName] ?? [], true)) {
  277. $this->calledOriginalListeners[$this->currentRequestHash][$eventName][] = $original;
  278. $this->calledListenerInfos[$this->currentRequestHash][] = $listener->getInfo($eventName);
  279. }
  280. }
  281. unset($this->callStack[$listener]);
  282. }
  283. }
  284. private function sortNotCalledListeners(array $a, array $b): int
  285. {
  286. if (0 !== $cmp = strcmp($a['event'], $b['event'])) {
  287. return $cmp;
  288. }
  289. if (\is_int($a['priority']) && !\is_int($b['priority'])) {
  290. return 1;
  291. }
  292. if (!\is_int($a['priority']) && \is_int($b['priority'])) {
  293. return -1;
  294. }
  295. if ($a['priority'] === $b['priority']) {
  296. return 0;
  297. }
  298. if ($a['priority'] > $b['priority']) {
  299. return -1;
  300. }
  301. return 1;
  302. }
  303. private function getListenersWithPriority(): array
  304. {
  305. $result = [];
  306. $allListeners = new \ReflectionProperty(EventDispatcher::class, 'listeners');
  307. foreach ($allListeners->getValue($this->dispatcher) as $eventName => $listenersByPriority) {
  308. foreach ($listenersByPriority as $priority => $listeners) {
  309. foreach ($listeners as $listener) {
  310. $result[$eventName][] = [$listener, $priority];
  311. }
  312. }
  313. }
  314. return $result;
  315. }
  316. private function getListenersWithoutPriority(): array
  317. {
  318. $result = [];
  319. foreach ($this->getListeners() as $eventName => $listeners) {
  320. foreach ($listeners as $listener) {
  321. $result[$eventName][] = [$listener, null];
  322. }
  323. }
  324. return $result;
  325. }
  326. }