EventDispatcher.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer\EventDispatcher;
  12. use Composer\IO\IOInterface;
  13. use Composer\Composer;
  14. use Composer\DependencyResolver\Operation\OperationInterface;
  15. use Composer\Script;
  16. use Composer\Script\CommandEvent;
  17. use Composer\Script\PackageEvent;
  18. use Composer\Util\ProcessExecutor;
  19. /**
  20. * The Event Dispatcher.
  21. *
  22. * Example in command:
  23. * $dispatcher = new EventDispatcher($this->getComposer(), $this->getApplication()->getIO());
  24. * // ...
  25. * $dispatcher->dispatch(ScriptEvents::POST_INSTALL_CMD);
  26. * // ...
  27. *
  28. * @author François Pluchino <francois.pluchino@opendisplay.com>
  29. * @author Jordi Boggiano <j.boggiano@seld.be>
  30. * @author Nils Adermann <naderman@naderman.de>
  31. */
  32. class EventDispatcher
  33. {
  34. protected $composer;
  35. protected $io;
  36. protected $loader;
  37. protected $process;
  38. /**
  39. * Constructor.
  40. *
  41. * @param Composer $composer The composer instance
  42. * @param IOInterface $io The IOInterface instance
  43. * @param ProcessExecutor $process
  44. */
  45. public function __construct(Composer $composer, IOInterface $io, ProcessExecutor $process = null)
  46. {
  47. $this->composer = $composer;
  48. $this->io = $io;
  49. $this->process = $process ?: new ProcessExecutor($io);
  50. }
  51. /**
  52. * Dispatch an event
  53. *
  54. * @param string $eventName An event name
  55. * @param Event $event
  56. */
  57. public function dispatch($eventName, Event $event = null)
  58. {
  59. if (null == $event) {
  60. $event = new Event($eventName);
  61. }
  62. $this->doDispatch($event);
  63. }
  64. /**
  65. * Dispatch a script event.
  66. *
  67. * @param string $eventName The constant in ScriptEvents
  68. * @param Script\Event $event
  69. */
  70. public function dispatchScript($eventName, $devMode = false)
  71. {
  72. $this->doDispatch(new Script\Event($eventName, $this->composer, $this->io, $devMode));
  73. }
  74. /**
  75. * Dispatch a package event.
  76. *
  77. * @param string $eventName The constant in ScriptEvents
  78. * @param boolean $devMode Whether or not we are in dev mode
  79. * @param OperationInterface $operation The package being installed/updated/removed
  80. */
  81. public function dispatchPackageEvent($eventName, $devMode, OperationInterface $operation)
  82. {
  83. $this->doDispatch(new PackageEvent($eventName, $this->composer, $this->io, $devMode, $operation));
  84. }
  85. /**
  86. * Dispatch a command event.
  87. *
  88. * @param string $eventName The constant in ScriptEvents
  89. * @param boolean $devMode Whether or not we are in dev mode
  90. */
  91. public function dispatchCommandEvent($eventName, $devMode)
  92. {
  93. $this->doDispatch(new CommandEvent($eventName, $this->composer, $this->io, $devMode));
  94. }
  95. /**
  96. * Triggers the listeners of an event.
  97. *
  98. * @param Event $event The event object to pass to the event handlers/listeners.
  99. * @throws \RuntimeException
  100. * @throws \Exception
  101. */
  102. protected function doDispatch(Event $event)
  103. {
  104. $listeners = $this->getListeners($event);
  105. foreach ($listeners as $callable) {
  106. if (!is_string($callable) && is_callable($callable)) {
  107. call_user_func($callable, $event);
  108. } elseif ($this->isPhpScript($callable)) {
  109. $className = substr($callable, 0, strpos($callable, '::'));
  110. $methodName = substr($callable, strpos($callable, '::') + 2);
  111. if (!class_exists($className)) {
  112. $this->io->write('<warning>Class '.$className.' is not autoloadable, can not call '.$event->getName().' script</warning>');
  113. continue;
  114. }
  115. if (!is_callable($callable)) {
  116. $this->io->write('<warning>Method '.$callable.' is not callable, can not call '.$event->getName().' script</warning>');
  117. continue;
  118. }
  119. try {
  120. $this->executeEventPhpScript($className, $methodName, $event);
  121. } catch (\Exception $e) {
  122. $message = "Script %s handling the %s event terminated with an exception";
  123. $this->io->write('<error>'.sprintf($message, $callable, $event->getName()).'</error>');
  124. throw $e;
  125. }
  126. } else {
  127. if (0 !== ($exitCode = $this->process->execute($callable))) {
  128. $event->getIO()->write(sprintf('<error>Script %s handling the %s event returned with an error</error>', $callable, $event->getName()));
  129. throw new \RuntimeException('Error Output: '.$this->process->getErrorOutput(), $exitCode);
  130. }
  131. }
  132. if ($event->isPropagationStopped()) {
  133. break;
  134. }
  135. }
  136. }
  137. /**
  138. * @param string $className
  139. * @param string $methodName
  140. * @param Event $event Event invoking the PHP callable
  141. */
  142. protected function executeEventPhpScript($className, $methodName, Event $event)
  143. {
  144. $className::$methodName($event);
  145. }
  146. /**
  147. * Add a listener for a particular event
  148. *
  149. * @param string $eventName The event name - typically a constant
  150. * @param Callable $listener A callable expecting an event argument
  151. * @param integer $priority A higher value represents a higher priority
  152. */
  153. protected function addListener($eventName, $listener, $priority = 0)
  154. {
  155. $this->listeners[$eventName][$priority][] = $listener;
  156. }
  157. /**
  158. * Adds object methods as listeners for the events in getSubscribedEvents
  159. *
  160. * @see EventSubscriberInterface
  161. *
  162. * @param EventSubscriberInterface $subscriber
  163. */
  164. public function addSubscriber(EventSubscriberInterface $subscriber)
  165. {
  166. foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
  167. if (is_string($params)) {
  168. $this->addListener($eventName, array($subscriber, $params));
  169. } elseif (is_string($params[0])) {
  170. $this->addListener($eventName, array($subscriber, $params[0]), isset($params[1]) ? $params[1] : 0);
  171. } else {
  172. foreach ($params as $listener) {
  173. $this->addListener($eventName, array($subscriber, $listener[0]), isset($listener[1]) ? $listener[1] : 0);
  174. }
  175. }
  176. }
  177. }
  178. /**
  179. * Retrieves all listeners for a given event
  180. *
  181. * @param Event $event
  182. * @return array All listeners: callables and scripts
  183. */
  184. protected function getListeners(Event $event)
  185. {
  186. $scriptListeners = $this->getScriptListeners($event);
  187. if (!isset($this->listeners[$event->getName()][0])) {
  188. $this->listeners[$event->getName()][0] = array();
  189. }
  190. krsort($this->listeners[$event->getName()]);
  191. $listeners = $this->listeners;
  192. $listeners[$event->getName()][0] = array_merge($listeners[$event->getName()][0], $scriptListeners);
  193. return call_user_func_array('array_merge', $listeners[$event->getName()]);
  194. }
  195. /**
  196. * Checks if an event has listeners registered
  197. *
  198. * @param Event $event
  199. * @return boolean
  200. */
  201. public function hasEventListeners(Event $event)
  202. {
  203. $listeners = $this->getListeners($event);
  204. return (sizeof($listeners) > 0);
  205. }
  206. /**
  207. * Finds all listeners defined as scripts in the package
  208. *
  209. * @param Event $event Event object
  210. * @return array Listeners
  211. */
  212. protected function getScriptListeners(Event $event)
  213. {
  214. $package = $this->composer->getPackage();
  215. $scripts = $package->getScripts();
  216. if (empty($scripts[$event->getName()])) {
  217. return array();
  218. }
  219. if ($this->loader) {
  220. $this->loader->unregister();
  221. }
  222. $generator = $this->composer->getAutoloadGenerator();
  223. $packages = $this->composer->getRepositoryManager()->getLocalRepository()->getCanonicalPackages();
  224. $packageMap = $generator->buildPackageMap($this->composer->getInstallationManager(), $package, $packages);
  225. $map = $generator->parseAutoloads($packageMap, $package);
  226. $this->loader = $generator->createLoader($map);
  227. $this->loader->register();
  228. return $scripts[$event->getName()];
  229. }
  230. /**
  231. * Checks if string given references a class path and method
  232. *
  233. * @param string $callable
  234. * @return boolean
  235. */
  236. protected function isPhpScript($callable)
  237. {
  238. return false === strpos($callable, ' ') && false !== strpos($callable, '::');
  239. }
  240. }