EventDispatcher.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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\DependencyResolver\PolicyInterface;
  13. use Composer\DependencyResolver\Pool;
  14. use Composer\DependencyResolver\Request;
  15. use Composer\Installer\InstallerEvent;
  16. use Composer\IO\IOInterface;
  17. use Composer\Composer;
  18. use Composer\DependencyResolver\Operation\OperationInterface;
  19. use Composer\Repository\CompositeRepository;
  20. use Composer\Script;
  21. use Composer\Script\PackageEvent;
  22. use Composer\Util\ProcessExecutor;
  23. /**
  24. * The Event Dispatcher.
  25. *
  26. * Example in command:
  27. * $dispatcher = new EventDispatcher($this->getComposer(), $this->getApplication()->getIO());
  28. * // ...
  29. * $dispatcher->dispatch(ScriptEvents::POST_INSTALL_CMD);
  30. * // ...
  31. *
  32. * @author François Pluchino <francois.pluchino@opendisplay.com>
  33. * @author Jordi Boggiano <j.boggiano@seld.be>
  34. * @author Nils Adermann <naderman@naderman.de>
  35. */
  36. class EventDispatcher
  37. {
  38. protected $composer;
  39. protected $io;
  40. protected $loader;
  41. protected $process;
  42. protected $listeners;
  43. /**
  44. * Constructor.
  45. *
  46. * @param Composer $composer The composer instance
  47. * @param IOInterface $io The IOInterface instance
  48. * @param ProcessExecutor $process
  49. */
  50. public function __construct(Composer $composer, IOInterface $io, ProcessExecutor $process = null)
  51. {
  52. $this->composer = $composer;
  53. $this->io = $io;
  54. $this->process = $process ?: new ProcessExecutor($io);
  55. }
  56. /**
  57. * Dispatch an event
  58. *
  59. * @param string $eventName An event name
  60. * @param Event $event
  61. * @return int return code of the executed script if any, for php scripts a false return
  62. * value is changed to 1, anything else to 0
  63. */
  64. public function dispatch($eventName, Event $event = null)
  65. {
  66. if (null == $event) {
  67. $event = new Event($eventName);
  68. }
  69. return $this->doDispatch($event);
  70. }
  71. /**
  72. * Dispatch a script event.
  73. *
  74. * @param string $eventName The constant in ScriptEvents
  75. * @param bool $devMode
  76. * @param array $additionalArgs Arguments passed by the user
  77. * @param array $flags Optional flags to pass data not as argument
  78. * @return int return code of the executed script if any, for php scripts a false return
  79. * value is changed to 1, anything else to 0
  80. */
  81. public function dispatchScript($eventName, $devMode = false, $additionalArgs = array(), $flags = array())
  82. {
  83. return $this->doDispatch(new Script\Event($eventName, $this->composer, $this->io, $devMode, $additionalArgs, $flags));
  84. }
  85. /**
  86. * Dispatch a package event.
  87. *
  88. * @param string $eventName The constant in PackageEvents
  89. * @param bool $devMode Whether or not we are in dev mode
  90. * @param PolicyInterface $policy The policy
  91. * @param Pool $pool The pool
  92. * @param CompositeRepository $installedRepo The installed repository
  93. * @param Request $request The request
  94. * @param array $operations The list of operations
  95. * @param OperationInterface $operation The package being installed/updated/removed
  96. *
  97. * @return int return code of the executed script if any, for php scripts a false return
  98. * value is changed to 1, anything else to 0
  99. */
  100. public function dispatchPackageEvent($eventName, $devMode, PolicyInterface $policy, Pool $pool, CompositeRepository $installedRepo, Request $request, array $operations, OperationInterface $operation)
  101. {
  102. return $this->doDispatch(new PackageEvent($eventName, $this->composer, $this->io, $devMode, $policy, $pool, $installedRepo, $request, $operations, $operation));
  103. }
  104. /**
  105. * Dispatch a installer event.
  106. *
  107. * @param string $eventName The constant in InstallerEvents
  108. * @param bool $devMode Whether or not we are in dev mode
  109. * @param PolicyInterface $policy The policy
  110. * @param Pool $pool The pool
  111. * @param CompositeRepository $installedRepo The installed repository
  112. * @param Request $request The request
  113. * @param array $operations The list of operations
  114. *
  115. * @return int return code of the executed script if any, for php scripts a false return
  116. * value is changed to 1, anything else to 0
  117. */
  118. public function dispatchInstallerEvent($eventName, $devMode, PolicyInterface $policy, Pool $pool, CompositeRepository $installedRepo, Request $request, array $operations = array())
  119. {
  120. return $this->doDispatch(new InstallerEvent($eventName, $this->composer, $this->io, $devMode, $policy, $pool, $installedRepo, $request, $operations));
  121. }
  122. /**
  123. * Triggers the listeners of an event.
  124. *
  125. * @param Event $event The event object to pass to the event handlers/listeners.
  126. * @param string $additionalArgs
  127. * @return int return code of the executed script if any, for php scripts a false return
  128. * value is changed to 1, anything else to 0
  129. * @throws \RuntimeException
  130. * @throws \Exception
  131. */
  132. protected function doDispatch(Event $event)
  133. {
  134. $listeners = $this->getListeners($event);
  135. $return = 0;
  136. foreach ($listeners as $callable) {
  137. if (!is_string($callable) && is_callable($callable)) {
  138. $event = $this->checkListenerExpectedEvent($callable, $event);
  139. $return = false === call_user_func($callable, $event) ? 1 : 0;
  140. } elseif ($this->isPhpScript($callable)) {
  141. $className = substr($callable, 0, strpos($callable, '::'));
  142. $methodName = substr($callable, strpos($callable, '::') + 2);
  143. if (!class_exists($className)) {
  144. $this->io->writeError('<warning>Class '.$className.' is not autoloadable, can not call '.$event->getName().' script</warning>');
  145. continue;
  146. }
  147. if (!is_callable($callable)) {
  148. $this->io->writeError('<warning>Method '.$callable.' is not callable, can not call '.$event->getName().' script</warning>');
  149. continue;
  150. }
  151. try {
  152. $return = false === $this->executeEventPhpScript($className, $methodName, $event) ? 1 : 0;
  153. } catch (\Exception $e) {
  154. $message = "Script %s handling the %s event terminated with an exception";
  155. $this->io->writeError('<error>'.sprintf($message, $callable, $event->getName()).'</error>');
  156. throw $e;
  157. }
  158. } else {
  159. $args = implode(' ', array_map(array('Composer\Util\ProcessExecutor', 'escape'), $event->getArguments()));
  160. $exec = $callable . ($args === '' ? '' : ' '.$args);
  161. if ($this->io->isVerbose()) {
  162. $this->io->writeError(sprintf('> %s', $exec));
  163. }
  164. if (0 !== ($exitCode = $this->process->execute($exec))) {
  165. $this->io->writeError(sprintf('<error>Script %s handling the %s event returned with an error</error>', $callable, $event->getName()));
  166. throw new \RuntimeException('Error Output: '.$this->process->getErrorOutput(), $exitCode);
  167. }
  168. }
  169. if ($event->isPropagationStopped()) {
  170. break;
  171. }
  172. }
  173. return $return;
  174. }
  175. /**
  176. * @param string $className
  177. * @param string $methodName
  178. * @param Event $event Event invoking the PHP callable
  179. */
  180. protected function executeEventPhpScript($className, $methodName, Event $event)
  181. {
  182. $event = $this->checkListenerExpectedEvent(array($className, $methodName), $event);
  183. return $className::$methodName($event);
  184. }
  185. /**
  186. * @param mixed $target
  187. * @param Event $event
  188. * @return Event|CommandEvent
  189. */
  190. protected function checkListenerExpectedEvent($target, Event $event)
  191. {
  192. try {
  193. $reflected = new \ReflectionParameter($target, 0);
  194. } catch (\Exception $e) {
  195. return $event;
  196. }
  197. $typehint = $reflected->getClass();
  198. if (!$typehint instanceof \ReflectionClass) {
  199. return $event;
  200. }
  201. $expected = $typehint->getName();
  202. // BC support
  203. if (!$event instanceof $expected && $expected === 'Composer\Script\CommandEvent') {
  204. $event = new \Composer\Script\CommandEvent(
  205. $event->getName(), $event->getComposer(), $event->getIO(), $event->isDevMode(), $event->getArguments()
  206. );
  207. }
  208. if (!$event instanceof $expected && $expected === 'Composer\Script\PackageEvent') {
  209. $event = new \Composer\Script\PackageEvent(
  210. $event->getName(), $event->getComposer(), $event->getIO(), $event->isDevMode(),
  211. $event->getPolicy(), $event->getPool(), $event->getInstalledRepo(), $event->getRequest(),
  212. $event->getOperations(), $event->getOperation()
  213. );
  214. }
  215. if (!$event instanceof $expected && $expected === 'Composer\Script\Event') {
  216. $event = new \Composer\Script\Event(
  217. $event->getName(), $event->getComposer(), $event->getIO(), $event->isDevMode(),
  218. $event->getArguments(), $event->getFlags()
  219. );
  220. }
  221. return $event;
  222. }
  223. /**
  224. * Add a listener for a particular event
  225. *
  226. * @param string $eventName The event name - typically a constant
  227. * @param Callable $listener A callable expecting an event argument
  228. * @param integer $priority A higher value represents a higher priority
  229. */
  230. protected function addListener($eventName, $listener, $priority = 0)
  231. {
  232. $this->listeners[$eventName][$priority][] = $listener;
  233. }
  234. /**
  235. * Adds object methods as listeners for the events in getSubscribedEvents
  236. *
  237. * @see EventSubscriberInterface
  238. *
  239. * @param EventSubscriberInterface $subscriber
  240. */
  241. public function addSubscriber(EventSubscriberInterface $subscriber)
  242. {
  243. foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
  244. if (is_string($params)) {
  245. $this->addListener($eventName, array($subscriber, $params));
  246. } elseif (is_string($params[0])) {
  247. $this->addListener($eventName, array($subscriber, $params[0]), isset($params[1]) ? $params[1] : 0);
  248. } else {
  249. foreach ($params as $listener) {
  250. $this->addListener($eventName, array($subscriber, $listener[0]), isset($listener[1]) ? $listener[1] : 0);
  251. }
  252. }
  253. }
  254. }
  255. /**
  256. * Retrieves all listeners for a given event
  257. *
  258. * @param Event $event
  259. * @return array All listeners: callables and scripts
  260. */
  261. protected function getListeners(Event $event)
  262. {
  263. $scriptListeners = $this->getScriptListeners($event);
  264. if (!isset($this->listeners[$event->getName()][0])) {
  265. $this->listeners[$event->getName()][0] = array();
  266. }
  267. krsort($this->listeners[$event->getName()]);
  268. $listeners = $this->listeners;
  269. $listeners[$event->getName()][0] = array_merge($listeners[$event->getName()][0], $scriptListeners);
  270. return call_user_func_array('array_merge', $listeners[$event->getName()]);
  271. }
  272. /**
  273. * Checks if an event has listeners registered
  274. *
  275. * @param Event $event
  276. * @return boolean
  277. */
  278. public function hasEventListeners(Event $event)
  279. {
  280. $listeners = $this->getListeners($event);
  281. return count($listeners) > 0;
  282. }
  283. /**
  284. * Finds all listeners defined as scripts in the package
  285. *
  286. * @param Event $event Event object
  287. * @return array Listeners
  288. */
  289. protected function getScriptListeners(Event $event)
  290. {
  291. $package = $this->composer->getPackage();
  292. $scripts = $package->getScripts();
  293. if (empty($scripts[$event->getName()])) {
  294. return array();
  295. }
  296. if ($this->loader) {
  297. $this->loader->unregister();
  298. }
  299. $generator = $this->composer->getAutoloadGenerator();
  300. $packages = $this->composer->getRepositoryManager()->getLocalRepository()->getCanonicalPackages();
  301. $packageMap = $generator->buildPackageMap($this->composer->getInstallationManager(), $package, $packages);
  302. $map = $generator->parseAutoloads($packageMap, $package);
  303. $this->loader = $generator->createLoader($map);
  304. $this->loader->register();
  305. return $scripts[$event->getName()];
  306. }
  307. /**
  308. * Checks if string given references a class path and method
  309. *
  310. * @param string $callable
  311. * @return boolean
  312. */
  313. protected function isPhpScript($callable)
  314. {
  315. return false === strpos($callable, ' ') && false !== strpos($callable, '::');
  316. }
  317. }