EventDispatcher.php 22 KB

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