EventDispatcher.php 15 KB

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