EventDispatcher.php 19 KB

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