EventDispatcher.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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. // add the bin dir to the PATH to make local binaries of deps usable in scripts
  138. $binDir = $this->composer->getConfig()->get('bin-dir');
  139. if (is_dir($binDir)) {
  140. $binDir = realpath($binDir);
  141. if (isset($_SERVER['PATH']) && !preg_match('{(^|'.PATH_SEPARATOR.')'.preg_quote($binDir).'($|'.PATH_SEPARATOR.')}', $_SERVER['PATH'])) {
  142. $_SERVER['PATH'] = $binDir.PATH_SEPARATOR.getenv('PATH');
  143. putenv('PATH='.$_SERVER['PATH']);
  144. }
  145. }
  146. $listeners = $this->getListeners($event);
  147. $this->pushEvent($event);
  148. $return = 0;
  149. foreach ($listeners as $callable) {
  150. if (!is_string($callable) && is_callable($callable)) {
  151. $event = $this->checkListenerExpectedEvent($callable, $event);
  152. $return = false === call_user_func($callable, $event) ? 1 : 0;
  153. } elseif ($this->isComposerScript($callable)) {
  154. $this->io->writeError(sprintf('> %s: %s', $event->getName(), $callable), true, IOInterface::VERBOSE);
  155. $scriptName = substr($callable, 1);
  156. $args = $event->getArguments();
  157. $flags = $event->getFlags();
  158. $return = $this->dispatch($scriptName, new Script\Event($scriptName, $event->getComposer(), $event->getIO(), $event->isDevMode(), $args, $flags));
  159. } elseif ($this->isPhpScript($callable)) {
  160. $className = substr($callable, 0, strpos($callable, '::'));
  161. $methodName = substr($callable, strpos($callable, '::') + 2);
  162. if (!class_exists($className)) {
  163. $this->io->writeError('<warning>Class '.$className.' is not autoloadable, can not call '.$event->getName().' script</warning>');
  164. continue;
  165. }
  166. if (!is_callable($callable)) {
  167. $this->io->writeError('<warning>Method '.$callable.' is not callable, can not call '.$event->getName().' script</warning>');
  168. continue;
  169. }
  170. try {
  171. $return = false === $this->executeEventPhpScript($className, $methodName, $event) ? 1 : 0;
  172. } catch (\Exception $e) {
  173. $message = "Script %s handling the %s event terminated with an exception";
  174. $this->io->writeError('<error>'.sprintf($message, $callable, $event->getName()).'</error>');
  175. throw $e;
  176. }
  177. } else {
  178. $args = implode(' ', array_map(array('Composer\Util\ProcessExecutor', 'escape'), $event->getArguments()));
  179. $exec = $callable . ($args === '' ? '' : ' '.$args);
  180. if ($this->io->isVerbose()) {
  181. $this->io->writeError(sprintf('> %s: %s', $event->getName(), $exec));
  182. } else {
  183. $this->io->writeError(sprintf('> %s', $exec));
  184. }
  185. if (0 !== ($exitCode = $this->process->execute($exec))) {
  186. $this->io->writeError(sprintf('<error>Script %s handling the %s event returned with an error</error>', $callable, $event->getName()));
  187. throw new \RuntimeException('Error Output: '.$this->process->getErrorOutput(), $exitCode);
  188. }
  189. }
  190. if ($event->isPropagationStopped()) {
  191. break;
  192. }
  193. }
  194. $this->popEvent();
  195. return $return;
  196. }
  197. /**
  198. * @param string $className
  199. * @param string $methodName
  200. * @param Event $event Event invoking the PHP callable
  201. */
  202. protected function executeEventPhpScript($className, $methodName, Event $event)
  203. {
  204. $event = $this->checkListenerExpectedEvent(array($className, $methodName), $event);
  205. if ($this->io->isVerbose()) {
  206. $this->io->writeError(sprintf('> %s: %s::%s', $event->getName(), $className, $methodName));
  207. } else {
  208. $this->io->writeError(sprintf('> %s::%s', $className, $methodName));
  209. }
  210. return $className::$methodName($event);
  211. }
  212. /**
  213. * @param mixed $target
  214. * @param Event $event
  215. * @return Event|CommandEvent
  216. */
  217. protected function checkListenerExpectedEvent($target, Event $event)
  218. {
  219. try {
  220. $reflected = new \ReflectionParameter($target, 0);
  221. } catch (\Exception $e) {
  222. return $event;
  223. }
  224. $typehint = $reflected->getClass();
  225. if (!$typehint instanceof \ReflectionClass) {
  226. return $event;
  227. }
  228. $expected = $typehint->getName();
  229. // BC support
  230. if (!$event instanceof $expected && $expected === 'Composer\Script\CommandEvent') {
  231. $event = new \Composer\Script\CommandEvent(
  232. $event->getName(), $event->getComposer(), $event->getIO(), $event->isDevMode(), $event->getArguments()
  233. );
  234. }
  235. if (!$event instanceof $expected && $expected === 'Composer\Script\PackageEvent') {
  236. $event = new \Composer\Script\PackageEvent(
  237. $event->getName(), $event->getComposer(), $event->getIO(), $event->isDevMode(),
  238. $event->getPolicy(), $event->getPool(), $event->getInstalledRepo(), $event->getRequest(),
  239. $event->getOperations(), $event->getOperation()
  240. );
  241. }
  242. if (!$event instanceof $expected && $expected === 'Composer\Script\Event') {
  243. $event = new \Composer\Script\Event(
  244. $event->getName(), $event->getComposer(), $event->getIO(), $event->isDevMode(),
  245. $event->getArguments(), $event->getFlags()
  246. );
  247. }
  248. return $event;
  249. }
  250. /**
  251. * Add a listener for a particular event
  252. *
  253. * @param string $eventName The event name - typically a constant
  254. * @param Callable $listener A callable expecting an event argument
  255. * @param int $priority A higher value represents a higher priority
  256. */
  257. public function addListener($eventName, $listener, $priority = 0)
  258. {
  259. $this->listeners[$eventName][$priority][] = $listener;
  260. }
  261. /**
  262. * Adds object methods as listeners for the events in getSubscribedEvents
  263. *
  264. * @see EventSubscriberInterface
  265. *
  266. * @param EventSubscriberInterface $subscriber
  267. */
  268. public function addSubscriber(EventSubscriberInterface $subscriber)
  269. {
  270. foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
  271. if (is_string($params)) {
  272. $this->addListener($eventName, array($subscriber, $params));
  273. } elseif (is_string($params[0])) {
  274. $this->addListener($eventName, array($subscriber, $params[0]), isset($params[1]) ? $params[1] : 0);
  275. } else {
  276. foreach ($params as $listener) {
  277. $this->addListener($eventName, array($subscriber, $listener[0]), isset($listener[1]) ? $listener[1] : 0);
  278. }
  279. }
  280. }
  281. }
  282. /**
  283. * Retrieves all listeners for a given event
  284. *
  285. * @param Event $event
  286. * @return array All listeners: callables and scripts
  287. */
  288. protected function getListeners(Event $event)
  289. {
  290. $scriptListeners = $this->getScriptListeners($event);
  291. if (!isset($this->listeners[$event->getName()][0])) {
  292. $this->listeners[$event->getName()][0] = array();
  293. }
  294. krsort($this->listeners[$event->getName()]);
  295. $listeners = $this->listeners;
  296. $listeners[$event->getName()][0] = array_merge($listeners[$event->getName()][0], $scriptListeners);
  297. return call_user_func_array('array_merge', $listeners[$event->getName()]);
  298. }
  299. /**
  300. * Checks if an event has listeners registered
  301. *
  302. * @param Event $event
  303. * @return bool
  304. */
  305. public function hasEventListeners(Event $event)
  306. {
  307. $listeners = $this->getListeners($event);
  308. return count($listeners) > 0;
  309. }
  310. /**
  311. * Finds all listeners defined as scripts in the package
  312. *
  313. * @param Event $event Event object
  314. * @return array Listeners
  315. */
  316. protected function getScriptListeners(Event $event)
  317. {
  318. $package = $this->composer->getPackage();
  319. $scripts = $package->getScripts();
  320. if (empty($scripts[$event->getName()])) {
  321. return array();
  322. }
  323. if ($this->loader) {
  324. $this->loader->unregister();
  325. }
  326. $generator = $this->composer->getAutoloadGenerator();
  327. $packages = $this->composer->getRepositoryManager()->getLocalRepository()->getCanonicalPackages();
  328. $packageMap = $generator->buildPackageMap($this->composer->getInstallationManager(), $package, $packages);
  329. $map = $generator->parseAutoloads($packageMap, $package);
  330. $this->loader = $generator->createLoader($map);
  331. $this->loader->register();
  332. return $scripts[$event->getName()];
  333. }
  334. /**
  335. * Checks if string given references a class path and method
  336. *
  337. * @param string $callable
  338. * @return bool
  339. */
  340. protected function isPhpScript($callable)
  341. {
  342. return false === strpos($callable, ' ') && false !== strpos($callable, '::');
  343. }
  344. /**
  345. * Checks if string given references a composer run-script
  346. *
  347. * @param string $callable
  348. * @return bool
  349. */
  350. protected function isComposerScript($callable)
  351. {
  352. return '@' === substr($callable, 0, 1);
  353. }
  354. /**
  355. * Push an event to the stack of active event
  356. *
  357. * @param Event $event
  358. * @throws \RuntimeException
  359. * @return number
  360. */
  361. protected function pushEvent(Event $event)
  362. {
  363. $eventName = $event->getName();
  364. if (in_array($eventName, $this->eventStack)) {
  365. throw new \RuntimeException(sprintf("Circular call to script handler '%s' detected", $eventName));
  366. }
  367. return array_push($this->eventStack, $eventName);
  368. }
  369. /**
  370. * Pops the active event from the stack
  371. *
  372. * @return mixed
  373. */
  374. protected function popEvent()
  375. {
  376. return array_pop($this->eventStack);
  377. }
  378. }