EventDispatcher.php 17 KB

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