TraceableEventDispatcher.php 11 KB

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