TraceableEventDispatcher.php 11 KB

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