EventDispatcher.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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. if (in_array($event->getName(), array(
  239. 'init',
  240. 'command',
  241. 'pre-file-download',
  242. ), true)) {
  243. return $event;
  244. }
  245. try {
  246. $reflected = new \ReflectionParameter($target, 0);
  247. } catch (\Exception $e) {
  248. return $event;
  249. }
  250. $typehint = $reflected->getClass();
  251. if (!$typehint instanceof \ReflectionClass) {
  252. return $event;
  253. }
  254. $expected = $typehint->getName();
  255. // BC support
  256. if (!$event instanceof $expected && $expected === 'Composer\Script\CommandEvent') {
  257. trigger_error('The callback '.$this->serializeCallback($target).' declared at '.$reflected->getDeclaringFunction()->getFileName().' accepts a '.$expected.' but '.$event->getName().' events use a '.get_class($event).' instance. Please adjust your type hint accordingly, see https://getcomposer.org/doc/articles/scripts.md#event-classes', E_USER_DEPRECATED);
  258. $event = new \Composer\Script\CommandEvent(
  259. $event->getName(), $event->getComposer(), $event->getIO(), $event->isDevMode(), $event->getArguments()
  260. );
  261. }
  262. if (!$event instanceof $expected && $expected === 'Composer\Script\PackageEvent') {
  263. trigger_error('The callback '.$this->serializeCallback($target).' declared at '.$reflected->getDeclaringFunction()->getFileName().' accepts a '.$expected.' but '.$event->getName().' events use a '.get_class($event).' instance. Please adjust your type hint accordingly, see https://getcomposer.org/doc/articles/scripts.md#event-classes', E_USER_DEPRECATED);
  264. $event = new \Composer\Script\PackageEvent(
  265. $event->getName(), $event->getComposer(), $event->getIO(), $event->isDevMode(),
  266. $event->getPolicy(), $event->getPool(), $event->getInstalledRepo(), $event->getRequest(),
  267. $event->getOperations(), $event->getOperation()
  268. );
  269. }
  270. if (!$event instanceof $expected && $expected === 'Composer\Script\Event') {
  271. trigger_error('The callback '.$this->serializeCallback($target).' declared at '.$reflected->getDeclaringFunction()->getFileName().' accepts a '.$expected.' but '.$event->getName().' events use a '.get_class($event).' instance. Please adjust your type hint accordingly, see https://getcomposer.org/doc/articles/scripts.md#event-classes', E_USER_DEPRECATED);
  272. $event = new \Composer\Script\Event(
  273. $event->getName(), $event->getComposer(), $event->getIO(), $event->isDevMode(),
  274. $event->getArguments(), $event->getFlags()
  275. );
  276. }
  277. return $event;
  278. }
  279. private function serializeCallback($cb)
  280. {
  281. if (is_array($cb) && count($cb) === 2) {
  282. if (is_object($cb[0])) {
  283. $cb[0] = get_class($cb[0]);
  284. }
  285. if (is_string($cb[0]) && is_string($cb[1])) {
  286. $cb = implode('::', $cb);
  287. }
  288. }
  289. if (is_string($cb)) {
  290. return $cb;
  291. }
  292. return var_export($cb, true);
  293. }
  294. /**
  295. * Add a listener for a particular event
  296. *
  297. * @param string $eventName The event name - typically a constant
  298. * @param Callable $listener A callable expecting an event argument
  299. * @param int $priority A higher value represents a higher priority
  300. */
  301. public function addListener($eventName, $listener, $priority = 0)
  302. {
  303. $this->listeners[$eventName][$priority][] = $listener;
  304. }
  305. /**
  306. * Adds object methods as listeners for the events in getSubscribedEvents
  307. *
  308. * @see EventSubscriberInterface
  309. *
  310. * @param EventSubscriberInterface $subscriber
  311. */
  312. public function addSubscriber(EventSubscriberInterface $subscriber)
  313. {
  314. foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
  315. if (is_string($params)) {
  316. $this->addListener($eventName, array($subscriber, $params));
  317. } elseif (is_string($params[0])) {
  318. $this->addListener($eventName, array($subscriber, $params[0]), isset($params[1]) ? $params[1] : 0);
  319. } else {
  320. foreach ($params as $listener) {
  321. $this->addListener($eventName, array($subscriber, $listener[0]), isset($listener[1]) ? $listener[1] : 0);
  322. }
  323. }
  324. }
  325. }
  326. /**
  327. * Retrieves all listeners for a given event
  328. *
  329. * @param Event $event
  330. * @return array All listeners: callables and scripts
  331. */
  332. protected function getListeners(Event $event)
  333. {
  334. $scriptListeners = $this->getScriptListeners($event);
  335. if (!isset($this->listeners[$event->getName()][0])) {
  336. $this->listeners[$event->getName()][0] = array();
  337. }
  338. krsort($this->listeners[$event->getName()]);
  339. $listeners = $this->listeners;
  340. $listeners[$event->getName()][0] = array_merge($listeners[$event->getName()][0], $scriptListeners);
  341. return call_user_func_array('array_merge', $listeners[$event->getName()]);
  342. }
  343. /**
  344. * Checks if an event has listeners registered
  345. *
  346. * @param Event $event
  347. * @return bool
  348. */
  349. public function hasEventListeners(Event $event)
  350. {
  351. $listeners = $this->getListeners($event);
  352. return count($listeners) > 0;
  353. }
  354. /**
  355. * Finds all listeners defined as scripts in the package
  356. *
  357. * @param Event $event Event object
  358. * @return array Listeners
  359. */
  360. protected function getScriptListeners(Event $event)
  361. {
  362. $package = $this->composer->getPackage();
  363. $scripts = $package->getScripts();
  364. if (empty($scripts[$event->getName()])) {
  365. return array();
  366. }
  367. if ($this->loader) {
  368. $this->loader->unregister();
  369. }
  370. $generator = $this->composer->getAutoloadGenerator();
  371. $packages = $this->composer->getRepositoryManager()->getLocalRepository()->getCanonicalPackages();
  372. $packageMap = $generator->buildPackageMap($this->composer->getInstallationManager(), $package, $packages);
  373. $map = $generator->parseAutoloads($packageMap, $package);
  374. $this->loader = $generator->createLoader($map);
  375. $this->loader->register();
  376. return $scripts[$event->getName()];
  377. }
  378. /**
  379. * Checks if string given references a class path and method
  380. *
  381. * @param string $callable
  382. * @return bool
  383. */
  384. protected function isPhpScript($callable)
  385. {
  386. return false === strpos($callable, ' ') && false !== strpos($callable, '::');
  387. }
  388. /**
  389. * Checks if string given references a composer run-script
  390. *
  391. * @param string $callable
  392. * @return bool
  393. */
  394. protected function isComposerScript($callable)
  395. {
  396. return '@' === substr($callable, 0, 1);
  397. }
  398. /**
  399. * Push an event to the stack of active event
  400. *
  401. * @param Event $event
  402. * @throws \RuntimeException
  403. * @return number
  404. */
  405. protected function pushEvent(Event $event)
  406. {
  407. $eventName = $event->getName();
  408. if (in_array($eventName, $this->eventStack)) {
  409. throw new \RuntimeException(sprintf("Circular call to script handler '%s' detected", $eventName));
  410. }
  411. return array_push($this->eventStack, $eventName);
  412. }
  413. /**
  414. * Pops the active event from the stack
  415. *
  416. * @return mixed
  417. */
  418. protected function popEvent()
  419. {
  420. return array_pop($this->eventStack);
  421. }
  422. }