EventDispatcher.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. if (0 !== ($exitCode = $this->process->execute($callable . ($args === '' ? '' : ' '.$args)))) {
  161. $this->io->writeError(sprintf('<error>Script %s handling the %s event returned with an error</error>', $callable, $event->getName()));
  162. throw new \RuntimeException('Error Output: '.$this->process->getErrorOutput(), $exitCode);
  163. }
  164. }
  165. if ($event->isPropagationStopped()) {
  166. break;
  167. }
  168. }
  169. return $return;
  170. }
  171. /**
  172. * @param string $className
  173. * @param string $methodName
  174. * @param Event $event Event invoking the PHP callable
  175. */
  176. protected function executeEventPhpScript($className, $methodName, Event $event)
  177. {
  178. $event = $this->checkListenerExpectedEvent(array($className, $methodName), $event);
  179. return $className::$methodName($event);
  180. }
  181. /**
  182. * @param mixed $target
  183. * @param Event $event
  184. * @return Event|CommandEvent
  185. */
  186. protected function checkListenerExpectedEvent($target, Event $event)
  187. {
  188. try {
  189. $reflected = new \ReflectionParameter($target, 0);
  190. } catch (\Exception $e) {
  191. return $event;
  192. }
  193. $typehint = $reflected->getClass();
  194. if (!$typehint instanceof \ReflectionClass) {
  195. return $event;
  196. }
  197. $expected = $typehint->getName();
  198. // BC support
  199. if (!$event instanceof $expected && $expected === 'Composer\Script\CommandEvent') {
  200. $event = new \Composer\Script\CommandEvent(
  201. $event->getName(), $event->getComposer(), $event->getIO(), $event->isDevMode(), $event->getArguments()
  202. );
  203. }
  204. if (!$event instanceof $expected && $expected === 'Composer\Script\PackageEvent') {
  205. $event = new \Composer\Script\PackageEvent(
  206. $event->getName(), $event->getComposer(), $event->getIO(), $event->isDevMode(),
  207. $event->getPolicy(), $event->getPool(), $event->getInstalledRepo(), $event->getRequest(),
  208. $event->getOperations(), $event->getOperation()
  209. );
  210. }
  211. if (!$event instanceof $expected && $expected === 'Composer\Script\Event') {
  212. $event = new \Composer\Script\Event(
  213. $event->getName(), $event->getComposer(), $event->getIO(), $event->isDevMode(),
  214. $event->getArguments(), $event->getFlags()
  215. );
  216. }
  217. return $event;
  218. }
  219. /**
  220. * Add a listener for a particular event
  221. *
  222. * @param string $eventName The event name - typically a constant
  223. * @param Callable $listener A callable expecting an event argument
  224. * @param integer $priority A higher value represents a higher priority
  225. */
  226. protected function addListener($eventName, $listener, $priority = 0)
  227. {
  228. $this->listeners[$eventName][$priority][] = $listener;
  229. }
  230. /**
  231. * Adds object methods as listeners for the events in getSubscribedEvents
  232. *
  233. * @see EventSubscriberInterface
  234. *
  235. * @param EventSubscriberInterface $subscriber
  236. */
  237. public function addSubscriber(EventSubscriberInterface $subscriber)
  238. {
  239. foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
  240. if (is_string($params)) {
  241. $this->addListener($eventName, array($subscriber, $params));
  242. } elseif (is_string($params[0])) {
  243. $this->addListener($eventName, array($subscriber, $params[0]), isset($params[1]) ? $params[1] : 0);
  244. } else {
  245. foreach ($params as $listener) {
  246. $this->addListener($eventName, array($subscriber, $listener[0]), isset($listener[1]) ? $listener[1] : 0);
  247. }
  248. }
  249. }
  250. }
  251. /**
  252. * Retrieves all listeners for a given event
  253. *
  254. * @param Event $event
  255. * @return array All listeners: callables and scripts
  256. */
  257. protected function getListeners(Event $event)
  258. {
  259. $scriptListeners = $this->getScriptListeners($event);
  260. if (!isset($this->listeners[$event->getName()][0])) {
  261. $this->listeners[$event->getName()][0] = array();
  262. }
  263. krsort($this->listeners[$event->getName()]);
  264. $listeners = $this->listeners;
  265. $listeners[$event->getName()][0] = array_merge($listeners[$event->getName()][0], $scriptListeners);
  266. return call_user_func_array('array_merge', $listeners[$event->getName()]);
  267. }
  268. /**
  269. * Checks if an event has listeners registered
  270. *
  271. * @param Event $event
  272. * @return boolean
  273. */
  274. public function hasEventListeners(Event $event)
  275. {
  276. $listeners = $this->getListeners($event);
  277. return count($listeners) > 0;
  278. }
  279. /**
  280. * Finds all listeners defined as scripts in the package
  281. *
  282. * @param Event $event Event object
  283. * @return array Listeners
  284. */
  285. protected function getScriptListeners(Event $event)
  286. {
  287. $package = $this->composer->getPackage();
  288. $scripts = $package->getScripts();
  289. if (empty($scripts[$event->getName()])) {
  290. return array();
  291. }
  292. if ($this->loader) {
  293. $this->loader->unregister();
  294. }
  295. $generator = $this->composer->getAutoloadGenerator();
  296. $packages = $this->composer->getRepositoryManager()->getLocalRepository()->getCanonicalPackages();
  297. $packageMap = $generator->buildPackageMap($this->composer->getInstallationManager(), $package, $packages);
  298. $map = $generator->parseAutoloads($packageMap, $package);
  299. $this->loader = $generator->createLoader($map);
  300. $this->loader->register();
  301. return $scripts[$event->getName()];
  302. }
  303. /**
  304. * Checks if string given references a class path and method
  305. *
  306. * @param string $callable
  307. * @return boolean
  308. */
  309. protected function isPhpScript($callable)
  310. {
  311. return false === strpos($callable, ' ') && false !== strpos($callable, '::');
  312. }
  313. }