TraceableEventDispatcher.php 10 KB

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