EventDispatcher.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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\Request;
  14. use Composer\Installer\InstallerEvent;
  15. use Composer\IO\IOInterface;
  16. use Composer\Composer;
  17. use Composer\DependencyResolver\Operation\OperationInterface;
  18. use Composer\Repository\CompositeRepository;
  19. use Composer\Repository\RepositoryInterface;
  20. use Composer\Repository\RepositorySet;
  21. use Composer\Script;
  22. use Composer\Installer\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 = array();
  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 RepositoryInterface $localRepo The installed repository
  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, RepositoryInterface $localRepo, array $operations, OperationInterface $operation)
  104. {
  105. return $this->doDispatch(new PackageEvent($eventName, $this->composer, $this->io, $devMode, $localRepo, $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 RepositorySet $repositorySet The repository set
  114. * @param RepositoryInterface $localRepo 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, RepositorySet $repositorySet, RepositoryInterface $localRepo, Request $request, array $operations = array())
  122. {
  123. return $this->doDispatch(new InstallerEvent($eventName, $this->composer, $this->io, $devMode, $policy, $repositorySet, $localRepo, $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. * @throws \RuntimeException|\Exception
  130. * @return int return code of the executed script if any, for php scripts a false return
  131. * value is changed to 1, anything else to 0
  132. */
  133. protected function doDispatch(Event $event)
  134. {
  135. $listeners = $this->getListeners($event);
  136. $this->pushEvent($event);
  137. $return = 0;
  138. foreach ($listeners as $callable) {
  139. $this->ensureBinDirIsInPath();
  140. if (!is_string($callable)) {
  141. if (!is_callable($callable)) {
  142. $className = is_object($callable[0]) ? get_class($callable[0]) : $callable[0];
  143. throw new \RuntimeException('Subscriber '.$className.'::'.$callable[1].' for event '.$event->getName().' is not callable, make sure the function is defined and public');
  144. }
  145. if (is_array($callable) && (is_string($callable[0]) || is_object($callable[0])) && is_string($callable[1])) {
  146. $this->io->writeError(sprintf('> %s: %s', $event->getName(), (is_object($callable[0]) ? get_class($callable[0]) : $callable[0]).'->'.$callable[1] ), true, IOInterface::VERBOSE);
  147. }
  148. $event = $this->checkListenerExpectedEvent($callable, $event);
  149. $return = false === call_user_func($callable, $event) ? 1 : 0;
  150. } elseif ($this->isComposerScript($callable)) {
  151. $this->io->writeError(sprintf('> %s: %s', $event->getName(), $callable), true, IOInterface::VERBOSE);
  152. $script = explode(' ', substr($callable, 1));
  153. $scriptName = $script[0];
  154. unset($script[0]);
  155. $args = array_merge($script, $event->getArguments());
  156. $flags = $event->getFlags();
  157. if (substr($callable, 0, 10) === '@composer ') {
  158. $exec = $this->getPhpExecCommand() . ' ' . ProcessExecutor::escape(getenv('COMPOSER_BINARY')) . ' ' . implode(' ', $args);
  159. if (0 !== ($exitCode = $this->executeTty($exec))) {
  160. $this->io->writeError(sprintf('<error>Script %s handling the %s event returned with error code '.$exitCode.'</error>', $callable, $event->getName()), true, IOInterface::QUIET);
  161. throw new ScriptExecutionException('Error Output: '.$this->process->getErrorOutput(), $exitCode);
  162. }
  163. } else {
  164. if (!$this->getListeners(new Event($scriptName))) {
  165. $this->io->writeError(sprintf('<warning>You made a reference to a non-existent script %s</warning>', $callable), true, IOInterface::QUIET);
  166. }
  167. try {
  168. /** @var InstallerEvent $event */
  169. $scriptEvent = new Script\Event($scriptName, $event->getComposer(), $event->getIO(), $event->isDevMode(), $args, $flags);
  170. $scriptEvent->setOriginatingEvent($event);
  171. $return = $this->dispatch($scriptName, $scriptEvent);
  172. } catch (ScriptExecutionException $e) {
  173. $this->io->writeError(sprintf('<error>Script %s was called via %s</error>', $callable, $event->getName()), true, IOInterface::QUIET);
  174. throw $e;
  175. }
  176. }
  177. } elseif ($this->isPhpScript($callable)) {
  178. $className = substr($callable, 0, strpos($callable, '::'));
  179. $methodName = substr($callable, strpos($callable, '::') + 2);
  180. if (!class_exists($className)) {
  181. $this->io->writeError('<warning>Class '.$className.' is not autoloadable, can not call '.$event->getName().' script</warning>', true, IOInterface::QUIET);
  182. continue;
  183. }
  184. if (!is_callable($callable)) {
  185. $this->io->writeError('<warning>Method '.$callable.' is not callable, can not call '.$event->getName().' script</warning>', true, IOInterface::QUIET);
  186. continue;
  187. }
  188. try {
  189. $return = false === $this->executeEventPhpScript($className, $methodName, $event) ? 1 : 0;
  190. } catch (\Exception $e) {
  191. $message = "Script %s handling the %s event terminated with an exception";
  192. $this->io->writeError('<error>'.sprintf($message, $callable, $event->getName()).'</error>', true, IOInterface::QUIET);
  193. throw $e;
  194. }
  195. } else {
  196. $args = implode(' ', array_map(array('Composer\Util\ProcessExecutor', 'escape'), $event->getArguments()));
  197. $exec = $callable . ($args === '' ? '' : ' '.$args);
  198. if ($this->io->isVerbose()) {
  199. $this->io->writeError(sprintf('> %s: %s', $event->getName(), $exec));
  200. } else {
  201. $this->io->writeError(sprintf('> %s', $exec));
  202. }
  203. $possibleLocalBinaries = $this->composer->getPackage()->getBinaries();
  204. if ($possibleLocalBinaries) {
  205. foreach ($possibleLocalBinaries as $localExec) {
  206. if (preg_match('{\b'.preg_quote($callable).'$}', $localExec)) {
  207. $caller = BinaryInstaller::determineBinaryCaller($localExec);
  208. $exec = preg_replace('{^'.preg_quote($callable).'}', $caller . ' ' . $localExec, $exec);
  209. break;
  210. }
  211. }
  212. }
  213. if (substr($exec, 0, 8) === '@putenv ') {
  214. putenv(substr($exec, 8));
  215. continue;
  216. } elseif (substr($exec, 0, 5) === '@php ') {
  217. $exec = $this->getPhpExecCommand() . ' ' . substr($exec, 5);
  218. } else {
  219. $finder = new PhpExecutableFinder();
  220. $phpPath = $finder->find(false);
  221. if ($phpPath) {
  222. putenv('PHP_BINARY=' . $phpPath);
  223. }
  224. }
  225. if (0 !== ($exitCode = $this->executeTty($exec))) {
  226. $this->io->writeError(sprintf('<error>Script %s handling the %s event returned with error code '.$exitCode.'</error>', $callable, $event->getName()), true, IOInterface::QUIET);
  227. throw new ScriptExecutionException('Error Output: '.$this->process->getErrorOutput(), $exitCode);
  228. }
  229. }
  230. if ($event->isPropagationStopped()) {
  231. break;
  232. }
  233. }
  234. $this->popEvent();
  235. return $return;
  236. }
  237. protected function executeTty($exec)
  238. {
  239. if ($this->io->isInteractive()) {
  240. return $this->process->executeTty($exec);
  241. }
  242. return $this->process->execute($exec);
  243. }
  244. protected function getPhpExecCommand()
  245. {
  246. $finder = new PhpExecutableFinder();
  247. $phpPath = $finder->find(false);
  248. if (!$phpPath) {
  249. throw new \RuntimeException('Failed to locate PHP binary to execute '.$phpPath);
  250. }
  251. $phpArgs = $finder->findArguments();
  252. $phpArgs = $phpArgs ? ' ' . implode(' ', $phpArgs) : '';
  253. $allowUrlFOpenFlag = ' -d allow_url_fopen=' . ProcessExecutor::escape(ini_get('allow_url_fopen'));
  254. $disableFunctionsFlag = ' -d disable_functions=' . ProcessExecutor::escape(ini_get('disable_functions'));
  255. $memoryLimitFlag = ' -d memory_limit=' . ProcessExecutor::escape(ini_get('memory_limit'));
  256. return ProcessExecutor::escape($phpPath) . $phpArgs . $allowUrlFOpenFlag . $disableFunctionsFlag . $memoryLimitFlag;
  257. }
  258. /**
  259. * @param string $className
  260. * @param string $methodName
  261. * @param Event $event Event invoking the PHP callable
  262. */
  263. protected function executeEventPhpScript($className, $methodName, Event $event)
  264. {
  265. $event = $this->checkListenerExpectedEvent(array($className, $methodName), $event);
  266. if ($this->io->isVerbose()) {
  267. $this->io->writeError(sprintf('> %s: %s::%s', $event->getName(), $className, $methodName));
  268. } else {
  269. $this->io->writeError(sprintf('> %s::%s', $className, $methodName));
  270. }
  271. return $className::$methodName($event);
  272. }
  273. /**
  274. * @param mixed $target
  275. * @param Event $event
  276. * @return Event
  277. */
  278. protected function checkListenerExpectedEvent($target, Event $event)
  279. {
  280. if (in_array($event->getName(), array(
  281. 'init',
  282. 'command',
  283. 'pre-file-download',
  284. ), true)) {
  285. return $event;
  286. }
  287. try {
  288. $reflected = new \ReflectionParameter($target, 0);
  289. } catch (\Exception $e) {
  290. return $event;
  291. }
  292. $typehint = $reflected->getClass();
  293. if (!$typehint instanceof \ReflectionClass) {
  294. return $event;
  295. }
  296. $expected = $typehint->getName();
  297. return $event;
  298. }
  299. private function serializeCallback($cb)
  300. {
  301. if (is_array($cb) && count($cb) === 2) {
  302. if (is_object($cb[0])) {
  303. $cb[0] = get_class($cb[0]);
  304. }
  305. if (is_string($cb[0]) && is_string($cb[1])) {
  306. $cb = implode('::', $cb);
  307. }
  308. }
  309. if (is_string($cb)) {
  310. return $cb;
  311. }
  312. return var_export($cb, true);
  313. }
  314. /**
  315. * Add a listener for a particular event
  316. *
  317. * @param string $eventName The event name - typically a constant
  318. * @param callable $listener A callable expecting an event argument
  319. * @param int $priority A higher value represents a higher priority
  320. */
  321. public function addListener($eventName, $listener, $priority = 0)
  322. {
  323. $this->listeners[$eventName][$priority][] = $listener;
  324. }
  325. /**
  326. * @param callable|object $listener A callable or an object instance for which all listeners should be removed
  327. */
  328. public function removeListener($listener)
  329. {
  330. foreach ($this->listeners as $eventName => $priorities) {
  331. foreach ($priorities as $priority => $listeners) {
  332. foreach ($listeners as $index => $candidate) {
  333. if ($listener === $candidate || (is_array($candidate) && is_object($listener) && $candidate[0] === $listener)) {
  334. unset($this->listeners[$eventName][$priority][$index]);
  335. }
  336. }
  337. }
  338. }
  339. }
  340. /**
  341. * Adds object methods as listeners for the events in getSubscribedEvents
  342. *
  343. * @see EventSubscriberInterface
  344. *
  345. * @param EventSubscriberInterface $subscriber
  346. */
  347. public function addSubscriber(EventSubscriberInterface $subscriber)
  348. {
  349. foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
  350. if (is_string($params)) {
  351. $this->addListener($eventName, array($subscriber, $params));
  352. } elseif (is_string($params[0])) {
  353. $this->addListener($eventName, array($subscriber, $params[0]), isset($params[1]) ? $params[1] : 0);
  354. } else {
  355. foreach ($params as $listener) {
  356. $this->addListener($eventName, array($subscriber, $listener[0]), isset($listener[1]) ? $listener[1] : 0);
  357. }
  358. }
  359. }
  360. }
  361. /**
  362. * Retrieves all listeners for a given event
  363. *
  364. * @param Event $event
  365. * @return array All listeners: callables and scripts
  366. */
  367. protected function getListeners(Event $event)
  368. {
  369. $scriptListeners = $this->getScriptListeners($event);
  370. if (!isset($this->listeners[$event->getName()][0])) {
  371. $this->listeners[$event->getName()][0] = array();
  372. }
  373. krsort($this->listeners[$event->getName()]);
  374. $listeners = $this->listeners;
  375. $listeners[$event->getName()][0] = array_merge($listeners[$event->getName()][0], $scriptListeners);
  376. return call_user_func_array('array_merge', $listeners[$event->getName()]);
  377. }
  378. /**
  379. * Checks if an event has listeners registered
  380. *
  381. * @param Event $event
  382. * @return bool
  383. */
  384. public function hasEventListeners(Event $event)
  385. {
  386. $listeners = $this->getListeners($event);
  387. return count($listeners) > 0;
  388. }
  389. /**
  390. * Finds all listeners defined as scripts in the package
  391. *
  392. * @param Event $event Event object
  393. * @return array Listeners
  394. */
  395. protected function getScriptListeners(Event $event)
  396. {
  397. $package = $this->composer->getPackage();
  398. $scripts = $package->getScripts();
  399. if (empty($scripts[$event->getName()])) {
  400. return array();
  401. }
  402. if ($this->loader) {
  403. $this->loader->unregister();
  404. }
  405. $generator = $this->composer->getAutoloadGenerator();
  406. if ($event instanceof ScriptEvent) {
  407. $generator->setDevMode($event->isDevMode());
  408. }
  409. $packages = $this->composer->getRepositoryManager()->getLocalRepository()->getCanonicalPackages();
  410. $packageMap = $generator->buildPackageMap($this->composer->getInstallationManager(), $package, $packages);
  411. $map = $generator->parseAutoloads($packageMap, $package);
  412. $this->loader = $generator->createLoader($map);
  413. $this->loader->register();
  414. return $scripts[$event->getName()];
  415. }
  416. /**
  417. * Checks if string given references a class path and method
  418. *
  419. * @param string $callable
  420. * @return bool
  421. */
  422. protected function isPhpScript($callable)
  423. {
  424. return false === strpos($callable, ' ') && false !== strpos($callable, '::');
  425. }
  426. /**
  427. * Checks if string given references a composer run-script
  428. *
  429. * @param string $callable
  430. * @return bool
  431. */
  432. protected function isComposerScript($callable)
  433. {
  434. return '@' === substr($callable, 0, 1) && '@php ' !== substr($callable, 0, 5) && '@putenv ' !== substr($callable, 0, 8);
  435. }
  436. /**
  437. * Push an event to the stack of active event
  438. *
  439. * @param Event $event
  440. * @throws \RuntimeException
  441. * @return int
  442. */
  443. protected function pushEvent(Event $event)
  444. {
  445. $eventName = $event->getName();
  446. if (in_array($eventName, $this->eventStack)) {
  447. throw new \RuntimeException(sprintf("Circular call to script handler '%s' detected", $eventName));
  448. }
  449. return array_push($this->eventStack, $eventName);
  450. }
  451. /**
  452. * Pops the active event from the stack
  453. *
  454. * @return mixed
  455. */
  456. protected function popEvent()
  457. {
  458. return array_pop($this->eventStack);
  459. }
  460. private function ensureBinDirIsInPath()
  461. {
  462. $pathStr = 'PATH';
  463. if (!isset($_SERVER[$pathStr]) && isset($_SERVER['Path'])) {
  464. $pathStr = 'Path';
  465. }
  466. // add the bin dir to the PATH to make local binaries of deps usable in scripts
  467. $binDir = $this->composer->getConfig()->get('bin-dir');
  468. if (is_dir($binDir)) {
  469. $binDir = realpath($binDir);
  470. if (isset($_SERVER[$pathStr]) && !preg_match('{(^|'.PATH_SEPARATOR.')'.preg_quote($binDir).'($|'.PATH_SEPARATOR.')}', $_SERVER[$pathStr])) {
  471. $_SERVER[$pathStr] = $binDir.PATH_SEPARATOR.getenv($pathStr);
  472. putenv($pathStr.'='.$_SERVER[$pathStr]);
  473. }
  474. }
  475. }
  476. }