PluginManager.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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\Plugin;
  12. use Composer\Composer;
  13. use Composer\EventDispatcher\EventSubscriberInterface;
  14. use Composer\IO\IOInterface;
  15. use Composer\Package\CompletePackage;
  16. use Composer\Package\Package;
  17. use Composer\Package\Version\VersionParser;
  18. use Composer\Repository\RepositoryInterface;
  19. use Composer\Package\PackageInterface;
  20. use Composer\Package\Link;
  21. use Composer\Semver\Constraint\Constraint;
  22. use Composer\Plugin\Capability\Capability;
  23. use Composer\Util\PackageSorter;
  24. /**
  25. * Plugin manager
  26. *
  27. * @author Nils Adermann <naderman@naderman.de>
  28. * @author Jordi Boggiano <j.boggiano@seld.be>
  29. */
  30. class PluginManager
  31. {
  32. protected $composer;
  33. protected $io;
  34. protected $globalComposer;
  35. protected $versionParser;
  36. protected $disablePlugins = false;
  37. protected $plugins = array();
  38. protected $registeredPlugins = array();
  39. private static $classCounter = 0;
  40. /**
  41. * Initializes plugin manager
  42. *
  43. * @param IOInterface $io
  44. * @param Composer $composer
  45. * @param Composer $globalComposer
  46. * @param bool $disablePlugins
  47. */
  48. public function __construct(IOInterface $io, Composer $composer, Composer $globalComposer = null, $disablePlugins = false)
  49. {
  50. $this->io = $io;
  51. $this->composer = $composer;
  52. $this->globalComposer = $globalComposer;
  53. $this->versionParser = new VersionParser();
  54. $this->disablePlugins = $disablePlugins;
  55. }
  56. /**
  57. * Loads all plugins from currently installed plugin packages
  58. */
  59. public function loadInstalledPlugins()
  60. {
  61. if ($this->disablePlugins) {
  62. return;
  63. }
  64. $repo = $this->composer->getRepositoryManager()->getLocalRepository();
  65. $globalRepo = $this->globalComposer ? $this->globalComposer->getRepositoryManager()->getLocalRepository() : null;
  66. if ($repo) {
  67. $this->loadRepository($repo);
  68. }
  69. if ($globalRepo) {
  70. $this->loadRepository($globalRepo);
  71. }
  72. }
  73. /**
  74. * Gets all currently active plugin instances
  75. *
  76. * @return array plugins
  77. */
  78. public function getPlugins()
  79. {
  80. return $this->plugins;
  81. }
  82. /**
  83. * Gets global composer or null when main composer is not fully loaded
  84. *
  85. * @return Composer|null
  86. */
  87. public function getGlobalComposer()
  88. {
  89. return $this->globalComposer;
  90. }
  91. /**
  92. * Register a plugin package, activate it etc.
  93. *
  94. * If it's of type composer-installer it is registered as an installer
  95. * instead for BC
  96. *
  97. * @param PackageInterface $package
  98. * @param bool $failOnMissingClasses By default this silently skips plugins that can not be found, but if set to true it fails with an exception
  99. *
  100. * @throws \UnexpectedValueException
  101. */
  102. public function registerPackage(PackageInterface $package, $failOnMissingClasses = false)
  103. {
  104. if ($this->disablePlugins) {
  105. return;
  106. }
  107. if ($package->getType() === 'composer-plugin') {
  108. $requiresComposer = null;
  109. foreach ($package->getRequires() as $link) { /** @var Link $link */
  110. if ('composer-plugin-api' === $link->getTarget()) {
  111. $requiresComposer = $link->getConstraint();
  112. break;
  113. }
  114. }
  115. if (!$requiresComposer) {
  116. throw new \RuntimeException("Plugin ".$package->getName()." is missing a require statement for a version of the composer-plugin-api package.");
  117. }
  118. $currentPluginApiVersion = $this->getPluginApiVersion();
  119. $currentPluginApiConstraint = new Constraint('==', $this->versionParser->normalize($currentPluginApiVersion));
  120. if ($requiresComposer->getPrettyString() === '1.0.0' && $this->getPluginApiVersion() === '1.0.0') {
  121. $this->io->writeError('<warning>The "' . $package->getName() . '" plugin requires composer-plugin-api 1.0.0, this *WILL* break in the future and it should be fixed ASAP (require ^1.0 for example).</warning>');
  122. } elseif (!$requiresComposer->matches($currentPluginApiConstraint)) {
  123. $this->io->writeError('<warning>The "' . $package->getName() . '" plugin was skipped because it requires a Plugin API version ("' . $requiresComposer->getPrettyString() . '") that does not match your Composer installation ("' . $currentPluginApiVersion . '"). You may need to run composer update with the "--no-plugins" option.</warning>');
  124. return;
  125. }
  126. }
  127. $oldInstallerPlugin = ($package->getType() === 'composer-installer');
  128. if (isset($this->registeredPlugins[$package->getName()])) {
  129. return;
  130. }
  131. $extra = $package->getExtra();
  132. if (empty($extra['class'])) {
  133. throw new \UnexpectedValueException('Error while installing '.$package->getPrettyName().', composer-plugin packages should have a class defined in their extra key to be usable.');
  134. }
  135. $classes = is_array($extra['class']) ? $extra['class'] : array($extra['class']);
  136. $localRepo = $this->composer->getRepositoryManager()->getLocalRepository();
  137. $globalRepo = $this->globalComposer ? $this->globalComposer->getRepositoryManager()->getLocalRepository() : null;
  138. $localRepos = $localRepo;
  139. if ($globalRepo) {
  140. $localRepos = new CompositeRepository(array($localRepos, $globalRepo));
  141. }
  142. $autoloadPackages = array($package->getName() => $package);
  143. $autoloadPackages = $this->collectDependencies($localRepos, $autoloadPackages, $package);
  144. $generator = $this->composer->getAutoloadGenerator();
  145. $autoloads = array();
  146. foreach ($autoloadPackages as $autoloadPackage) {
  147. $downloadPath = $this->getInstallPath($autoloadPackage, $globalRepo && $globalRepo->hasPackage($autoloadPackage));
  148. $autoloads[] = array($autoloadPackage, $downloadPath);
  149. }
  150. $map = $generator->parseAutoloads($autoloads, new Package('dummy', '1.0.0.0', '1.0.0'));
  151. $classLoader = $generator->createLoader($map);
  152. $classLoader->register();
  153. foreach ($classes as $class) {
  154. if (class_exists($class, false)) {
  155. $class = trim($class, '\\');
  156. $path = $classLoader->findFile($class);
  157. $code = file_get_contents($path);
  158. $separatorPos = strrpos($class, '\\');
  159. $className = $class;
  160. if ($separatorPos) {
  161. $className = substr($class, $separatorPos + 1);
  162. }
  163. $code = preg_replace('{^((?:final\s+)?(?:\s*))class\s+('.preg_quote($className).')}mi', '$1class $2_composer_tmp'.self::$classCounter, $code, 1);
  164. $code = str_replace('__FILE__', var_export($path, true), $code);
  165. $code = str_replace('__DIR__', var_export(dirname($path), true), $code);
  166. $code = str_replace('__CLASS__', var_export($class, true), $code);
  167. $code = preg_replace('/^\s*<\?(php)?/i', '', $code, 1);
  168. eval($code);
  169. $class .= '_composer_tmp'.self::$classCounter;
  170. self::$classCounter++;
  171. }
  172. if ($oldInstallerPlugin) {
  173. $installer = new $class($this->io, $this->composer);
  174. $this->composer->getInstallationManager()->addInstaller($installer);
  175. $this->registeredPlugins[$package->getName()] = $installer;
  176. } elseif (class_exists($class)) {
  177. $plugin = new $class();
  178. $this->addPlugin($plugin);
  179. $this->registeredPlugins[$package->getName()] = $plugin;
  180. } elseif ($failOnMissingClasses) {
  181. throw new \UnexpectedValueException('Plugin '.$package->getName().' could not be initialized, class not found: '.$class);
  182. }
  183. }
  184. }
  185. /**
  186. * Deactivates a plugin package
  187. *
  188. * If it's of type composer-installer it is unregistered from the installers
  189. * instead for BC
  190. *
  191. * @param PackageInterface $package
  192. *
  193. * @throws \UnexpectedValueException
  194. */
  195. public function deactivatePackage(PackageInterface $package)
  196. {
  197. if ($this->disablePlugins) {
  198. return;
  199. }
  200. $oldInstallerPlugin = ($package->getType() === 'composer-installer');
  201. if (!isset($this->registeredPlugins[$package->getName()])) {
  202. return;
  203. }
  204. if ($oldInstallerPlugin) {
  205. $installer = $this->registeredPlugins[$package->getName()];
  206. unset($this->registeredPlugins[$package->getName()]);
  207. $this->composer->getInstallationManager()->removeInstaller($installer);
  208. } else {
  209. $plugin = $this->registeredPlugins[$package->getName()];
  210. unset($this->registeredPlugins[$package->getName()]);
  211. $this->removePlugin($plugin);
  212. }
  213. }
  214. /**
  215. * Uninstall a plugin package
  216. *
  217. * If it's of type composer-installer it is unregistered from the installers
  218. * instead for BC
  219. *
  220. * @param PackageInterface $package
  221. *
  222. * @throws \UnexpectedValueException
  223. */
  224. public function uninstallPackage(PackageInterface $package)
  225. {
  226. if ($this->disablePlugins) {
  227. return;
  228. }
  229. $oldInstallerPlugin = ($package->getType() === 'composer-installer');
  230. if (!isset($this->registeredPlugins[$package->getName()])) {
  231. return;
  232. }
  233. if ($oldInstallerPlugin) {
  234. $this->deactivatePackage($package);
  235. } else {
  236. $plugin = $this->registeredPlugins[$package->getName()];
  237. unset($this->registeredPlugins[$package->getName()]);
  238. $this->removePlugin($plugin);
  239. $this->uninstallPlugin($plugin);
  240. }
  241. }
  242. /**
  243. * Returns the version of the internal composer-plugin-api package.
  244. *
  245. * @return string
  246. */
  247. protected function getPluginApiVersion()
  248. {
  249. return PluginInterface::PLUGIN_API_VERSION;
  250. }
  251. /**
  252. * Adds a plugin, activates it and registers it with the event dispatcher
  253. *
  254. * Ideally plugin packages should be registered via registerPackage, but if you use Composer
  255. * programmatically and want to register a plugin class directly this is a valid way
  256. * to do it.
  257. *
  258. * @param PluginInterface $plugin plugin instance
  259. */
  260. public function addPlugin(PluginInterface $plugin)
  261. {
  262. $this->io->writeError('Loading plugin '.get_class($plugin), true, IOInterface::DEBUG);
  263. $this->plugins[] = $plugin;
  264. $plugin->activate($this->composer, $this->io);
  265. if ($plugin instanceof EventSubscriberInterface) {
  266. $this->composer->getEventDispatcher()->addSubscriber($plugin);
  267. }
  268. }
  269. /**
  270. * Removes a plugin, deactivates it and removes any listener the plugin has set on the plugin instance
  271. *
  272. * Ideally plugin packages should be deactivated via deactivatePackage, but if you use Composer
  273. * programmatically and want to deregister a plugin class directly this is a valid way
  274. * to do it.
  275. *
  276. * @param PluginInterface $plugin plugin instance
  277. */
  278. public function removePlugin(PluginInterface $plugin)
  279. {
  280. $index = array_search($plugin, $this->plugins, true);
  281. if ($index === false) {
  282. return;
  283. }
  284. $this->io->writeError('Unloading plugin '.get_class($plugin), true, IOInterface::DEBUG);
  285. unset($this->plugins[$index]);
  286. $plugin->deactivate($this->composer, $this->io);
  287. $this->composer->getEventDispatcher()->removeListener($plugin);
  288. }
  289. /**
  290. * Notifies a plugin it is being uninstalled and should clean up
  291. *
  292. * Ideally plugin packages should be uninstalled via uninstallPackage, but if you use Composer
  293. * programmatically and want to deregister a plugin class directly this is a valid way
  294. * to do it.
  295. *
  296. * @param PluginInterface $plugin plugin instance
  297. */
  298. public function uninstallPlugin(PluginInterface $plugin)
  299. {
  300. $this->io->writeError('Uninstalling plugin '.get_class($plugin), true, IOInterface::DEBUG);
  301. $plugin->uninstall($this->composer, $this->io);
  302. }
  303. /**
  304. * Load all plugins and installers from a repository
  305. *
  306. * Note that plugins in the specified repository that rely on events that
  307. * have fired prior to loading will be missed. This means you likely want to
  308. * call this method as early as possible.
  309. *
  310. * @param RepositoryInterface $repo Repository to scan for plugins to install
  311. *
  312. * @throws \RuntimeException
  313. */
  314. private function loadRepository(RepositoryInterface $repo)
  315. {
  316. $packages = $repo->getPackages();
  317. $sortedPackages = array_reverse(PackageSorter::sortPackages($packages));
  318. foreach ($sortedPackages as $package) {
  319. if (!($package instanceof CompletePackage)) {
  320. continue;
  321. }
  322. if ('composer-plugin' === $package->getType()) {
  323. $this->registerPackage($package);
  324. // Backward compatibility
  325. } elseif ('composer-installer' === $package->getType()) {
  326. $this->registerPackage($package);
  327. }
  328. }
  329. }
  330. /**
  331. * Recursively generates a map of package names to packages for all deps
  332. *
  333. * @param RepositoryInterface $localRepos Set of local repos
  334. * @param array $collected Current state of the map for recursion
  335. * @param PackageInterface $package The package to analyze
  336. *
  337. * @return array Map of package names to packages
  338. */
  339. private function collectDependencies(RepositoryInterface $localRepos, array $collected, PackageInterface $package)
  340. {
  341. $requires = array_merge(
  342. $package->getRequires(),
  343. $package->getDevRequires()
  344. );
  345. foreach ($requires as $requireLink) {
  346. foreach ($this->lookupInstalledPackages($localRepos, $requireLink) as $requiredPackage) {
  347. if (!isset($collected[$requiredPackage->getName()])) {
  348. $collected[$requiredPackage->getName()] = $requiredPackage;
  349. $collected = $this->collectDependencies($localRepos, $collected, $requiredPackage);
  350. }
  351. }
  352. }
  353. return $collected;
  354. }
  355. /**
  356. * Resolves a package link to a package in the installed repo set
  357. *
  358. * Since dependencies are already installed this should always find one.
  359. *
  360. * @param RepositoryInterface $localRepos Set of local repos
  361. * @param Link $link Package link to look up
  362. *
  363. * @return PackageInterface[] The found packages
  364. */
  365. private function lookupInstalledPackages(RepositoryInterface $localRepos, Link $link)
  366. {
  367. $matches = array();
  368. foreach ($localRepos->getPackages() as $candidate) {
  369. if (in_array($link->getTarget(), $candidate->getNames(), true)) {
  370. if ($link->getConstraint() === null || $link->getConstraint()->matches(new Constraint('=', $candidate->getVersion()))) {
  371. $matches[] = $candidate;
  372. }
  373. }
  374. }
  375. return $matches;
  376. }
  377. /**
  378. * Retrieves the path a package is installed to.
  379. *
  380. * @param PackageInterface $package
  381. * @param bool $global Whether this is a global package
  382. *
  383. * @return string Install path
  384. */
  385. private function getInstallPath(PackageInterface $package, $global = false)
  386. {
  387. if (!$global) {
  388. return $this->composer->getInstallationManager()->getInstallPath($package);
  389. }
  390. return $this->globalComposer->getInstallationManager()->getInstallPath($package);
  391. }
  392. /**
  393. * @param PluginInterface $plugin
  394. * @param string $capability
  395. * @throws \RuntimeException On empty or non-string implementation class name value
  396. * @return null|string The fully qualified class of the implementation or null if Plugin is not of Capable type or does not provide it
  397. */
  398. protected function getCapabilityImplementationClassName(PluginInterface $plugin, $capability)
  399. {
  400. if (!($plugin instanceof Capable)) {
  401. return null;
  402. }
  403. $capabilities = (array) $plugin->getCapabilities();
  404. if (!empty($capabilities[$capability]) && is_string($capabilities[$capability]) && trim($capabilities[$capability])) {
  405. return trim($capabilities[$capability]);
  406. }
  407. if (
  408. array_key_exists($capability, $capabilities)
  409. && (empty($capabilities[$capability]) || !is_string($capabilities[$capability]) || !trim($capabilities[$capability]))
  410. ) {
  411. throw new \UnexpectedValueException('Plugin '.get_class($plugin).' provided invalid capability class name(s), got '.var_export($capabilities[$capability], 1));
  412. }
  413. }
  414. /**
  415. * @param PluginInterface $plugin
  416. * @param string $capabilityClassName The fully qualified name of the API interface which the plugin may provide
  417. * an implementation of.
  418. * @param array $ctorArgs Arguments passed to Capability's constructor.
  419. * Keeping it an array will allow future values to be passed w\o changing the signature.
  420. * @return null|Capability
  421. */
  422. public function getPluginCapability(PluginInterface $plugin, $capabilityClassName, array $ctorArgs = array())
  423. {
  424. if ($capabilityClass = $this->getCapabilityImplementationClassName($plugin, $capabilityClassName)) {
  425. if (!class_exists($capabilityClass)) {
  426. throw new \RuntimeException("Cannot instantiate Capability, as class $capabilityClass from plugin ".get_class($plugin)." does not exist.");
  427. }
  428. $ctorArgs['plugin'] = $plugin;
  429. $capabilityObj = new $capabilityClass($ctorArgs);
  430. // FIXME these could use is_a and do the check *before* instantiating once drop support for php<5.3.9
  431. if (!$capabilityObj instanceof Capability || !$capabilityObj instanceof $capabilityClassName) {
  432. throw new \RuntimeException(
  433. 'Class ' . $capabilityClass . ' must implement both Composer\Plugin\Capability\Capability and '. $capabilityClassName . '.'
  434. );
  435. }
  436. return $capabilityObj;
  437. }
  438. }
  439. /**
  440. * @param string $capabilityClassName The fully qualified name of the API interface which the plugin may provide
  441. * an implementation of.
  442. * @param array $ctorArgs Arguments passed to Capability's constructor.
  443. * Keeping it an array will allow future values to be passed w\o changing the signature.
  444. * @return Capability[]
  445. */
  446. public function getPluginCapabilities($capabilityClassName, array $ctorArgs = array())
  447. {
  448. $capabilities = array();
  449. foreach ($this->getPlugins() as $plugin) {
  450. if ($capability = $this->getPluginCapability($plugin, $capabilityClassName, $ctorArgs)) {
  451. $capabilities[] = $capability;
  452. }
  453. }
  454. return $capabilities;
  455. }
  456. }