PluginManager.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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\Package;
  16. use Composer\Package\Version\VersionParser;
  17. use Composer\Repository\RepositoryInterface;
  18. use Composer\Package\AliasPackage;
  19. use Composer\Package\PackageInterface;
  20. use Composer\Package\Link;
  21. use Composer\Semver\Constraint\Constraint;
  22. use Composer\DependencyResolver\Pool;
  23. use Composer\Plugin\Capability\Capability;
  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 (in_array($package->getName(), $this->registeredPlugins)) {
  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. $pool = new Pool('dev');
  139. $pool->addRepository($localRepo);
  140. if ($globalRepo) {
  141. $pool->addRepository($globalRepo);
  142. }
  143. $autoloadPackages = array($package->getName() => $package);
  144. $autoloadPackages = $this->collectDependencies($pool, $autoloadPackages, $package);
  145. $generator = $this->composer->getAutoloadGenerator();
  146. $autoloads = array();
  147. foreach ($autoloadPackages as $autoloadPackage) {
  148. $downloadPath = $this->getInstallPath($autoloadPackage, ($globalRepo && $globalRepo->hasPackage($autoloadPackage)));
  149. $autoloads[] = array($autoloadPackage, $downloadPath);
  150. }
  151. $map = $generator->parseAutoloads($autoloads, new Package('dummy', '1.0.0.0', '1.0.0'));
  152. $classLoader = $generator->createLoader($map);
  153. $classLoader->register();
  154. foreach ($classes as $class) {
  155. if (class_exists($class, false)) {
  156. $class = trim($class, '\\');
  157. $path = $classLoader->findFile($class);
  158. $code = file_get_contents($path);
  159. $separatorPos = strrpos($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. eval('?>'.$code);
  168. $class .= '_composer_tmp'.self::$classCounter;
  169. self::$classCounter++;
  170. }
  171. if ($oldInstallerPlugin) {
  172. $installer = new $class($this->io, $this->composer);
  173. $this->composer->getInstallationManager()->addInstaller($installer);
  174. } elseif (class_exists($class)) {
  175. $plugin = new $class();
  176. $this->addPlugin($plugin);
  177. $this->registeredPlugins[] = $package->getName();
  178. } elseif ($failOnMissingClasses) {
  179. throw new \UnexpectedValueException('Plugin '.$package->getName().' could not be initialized, class not found: '.$class);
  180. }
  181. }
  182. }
  183. /**
  184. * Returns the version of the internal composer-plugin-api package.
  185. *
  186. * @return string
  187. */
  188. protected function getPluginApiVersion()
  189. {
  190. return PluginInterface::PLUGIN_API_VERSION;
  191. }
  192. /**
  193. * Adds a plugin, activates it and registers it with the event dispatcher
  194. *
  195. * @param PluginInterface $plugin plugin instance
  196. */
  197. private function addPlugin(PluginInterface $plugin)
  198. {
  199. $this->io->writeError('Loading plugin '.get_class($plugin), true, IOInterface::DEBUG);
  200. $this->plugins[] = $plugin;
  201. $plugin->activate($this->composer, $this->io);
  202. if ($plugin instanceof EventSubscriberInterface) {
  203. $this->composer->getEventDispatcher()->addSubscriber($plugin);
  204. }
  205. }
  206. /**
  207. * Load all plugins and installers from a repository
  208. *
  209. * Note that plugins in the specified repository that rely on events that
  210. * have fired prior to loading will be missed. This means you likely want to
  211. * call this method as early as possible.
  212. *
  213. * @param RepositoryInterface $repo Repository to scan for plugins to install
  214. *
  215. * @throws \RuntimeException
  216. */
  217. private function loadRepository(RepositoryInterface $repo)
  218. {
  219. foreach ($repo->getPackages() as $package) { /** @var PackageInterface $package */
  220. if ($package instanceof AliasPackage) {
  221. continue;
  222. }
  223. if ('composer-plugin' === $package->getType()) {
  224. $this->registerPackage($package);
  225. // Backward compatibility
  226. } elseif ('composer-installer' === $package->getType()) {
  227. $this->registerPackage($package);
  228. }
  229. }
  230. }
  231. /**
  232. * Recursively generates a map of package names to packages for all deps
  233. *
  234. * @param Pool $pool Package pool of installed packages
  235. * @param array $collected Current state of the map for recursion
  236. * @param PackageInterface $package The package to analyze
  237. *
  238. * @return array Map of package names to packages
  239. */
  240. private function collectDependencies(Pool $pool, array $collected, PackageInterface $package)
  241. {
  242. $requires = array_merge(
  243. $package->getRequires(),
  244. $package->getDevRequires()
  245. );
  246. foreach ($requires as $requireLink) {
  247. $requiredPackage = $this->lookupInstalledPackage($pool, $requireLink);
  248. if ($requiredPackage && !isset($collected[$requiredPackage->getName()])) {
  249. $collected[$requiredPackage->getName()] = $requiredPackage;
  250. $collected = $this->collectDependencies($pool, $collected, $requiredPackage);
  251. }
  252. }
  253. return $collected;
  254. }
  255. /**
  256. * Resolves a package link to a package in the installed pool
  257. *
  258. * Since dependencies are already installed this should always find one.
  259. *
  260. * @param Pool $pool Pool of installed packages only
  261. * @param Link $link Package link to look up
  262. *
  263. * @return PackageInterface|null The found package
  264. */
  265. private function lookupInstalledPackage(Pool $pool, Link $link)
  266. {
  267. $packages = $pool->whatProvides($link->getTarget(), $link->getConstraint());
  268. return (!empty($packages)) ? $packages[0] : null;
  269. }
  270. /**
  271. * Retrieves the path a package is installed to.
  272. *
  273. * @param PackageInterface $package
  274. * @param bool $global Whether this is a global package
  275. *
  276. * @return string Install path
  277. */
  278. private function getInstallPath(PackageInterface $package, $global = false)
  279. {
  280. if (!$global) {
  281. return $this->composer->getInstallationManager()->getInstallPath($package);
  282. }
  283. return $this->globalComposer->getInstallationManager()->getInstallPath($package);
  284. }
  285. /**
  286. * @param PluginInterface $plugin
  287. * @param string $capability
  288. * @throws \RuntimeException On empty or non-string implementation class name value
  289. * @return null|string The fully qualified class of the implementation or null if Plugin is not of Capable type or does not provide it
  290. */
  291. protected function getCapabilityImplementationClassName(PluginInterface $plugin, $capability)
  292. {
  293. if (!($plugin instanceof Capable)) {
  294. return null;
  295. }
  296. $capabilities = (array) $plugin->getCapabilities();
  297. if (!empty($capabilities[$capability]) && is_string($capabilities[$capability]) && trim($capabilities[$capability])) {
  298. return trim($capabilities[$capability]);
  299. }
  300. if (
  301. array_key_exists($capability, $capabilities)
  302. && (empty($capabilities[$capability]) || !is_string($capabilities[$capability]) || !trim($capabilities[$capability]))
  303. ) {
  304. throw new \UnexpectedValueException('Plugin '.get_class($plugin).' provided invalid capability class name(s), got '.var_export($capabilities[$capability], 1));
  305. }
  306. }
  307. /**
  308. * @param PluginInterface $plugin
  309. * @param string $capabilityClassName The fully qualified name of the API interface which the plugin may provide
  310. * an implementation of.
  311. * @param array $ctorArgs Arguments passed to Capability's constructor.
  312. * Keeping it an array will allow future values to be passed w\o changing the signature.
  313. * @return null|Capability
  314. */
  315. public function getPluginCapability(PluginInterface $plugin, $capabilityClassName, array $ctorArgs = array())
  316. {
  317. if ($capabilityClass = $this->getCapabilityImplementationClassName($plugin, $capabilityClassName)) {
  318. if (!class_exists($capabilityClass)) {
  319. throw new \RuntimeException("Cannot instantiate Capability, as class $capabilityClass from plugin ".get_class($plugin)." does not exist.");
  320. }
  321. $capabilityObj = new $capabilityClass($ctorArgs);
  322. // FIXME these could use is_a and do the check *before* instantiating once drop support for php<5.3.9
  323. if (!$capabilityObj instanceof Capability || !$capabilityObj instanceof $capabilityClassName) {
  324. throw new \RuntimeException(
  325. 'Class ' . $capabilityClass . ' must implement both Composer\Plugin\Capability\Capability and '. $capabilityClassName . '.'
  326. );
  327. }
  328. return $capabilityObj;
  329. }
  330. }
  331. }