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

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