TraceableEventDispatcher.php 11 KB

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