Factory.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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;
  12. use Composer\Config\JsonConfigSource;
  13. use Composer\Json\JsonFile;
  14. use Composer\IO\IOInterface;
  15. use Composer\Package\Archiver;
  16. use Composer\Package\Version\VersionGuesser;
  17. use Composer\Repository\RepositoryManager;
  18. use Composer\Repository\WritableRepositoryInterface;
  19. use Composer\Util\ProcessExecutor;
  20. use Composer\Util\RemoteFilesystem;
  21. use Symfony\Component\Console\Formatter\OutputFormatterStyle;
  22. use Composer\EventDispatcher\EventDispatcher;
  23. use Composer\Autoload\AutoloadGenerator;
  24. use Composer\Semver\VersionParser;
  25. /**
  26. * Creates a configured instance of composer.
  27. *
  28. * @author Ryan Weaver <ryan@knplabs.com>
  29. * @author Jordi Boggiano <j.boggiano@seld.be>
  30. * @author Igor Wiedler <igor@wiedler.ch>
  31. * @author Nils Adermann <naderman@naderman.de>
  32. */
  33. class Factory
  34. {
  35. /**
  36. * @throws \RuntimeException
  37. * @return string
  38. */
  39. protected static function getHomeDir()
  40. {
  41. $home = getenv('COMPOSER_HOME');
  42. if (!$home) {
  43. if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
  44. if (!getenv('APPDATA')) {
  45. throw new \RuntimeException('The APPDATA or COMPOSER_HOME environment variable must be set for composer to run correctly');
  46. }
  47. $home = strtr(getenv('APPDATA'), '\\', '/') . '/Composer';
  48. } else {
  49. if (!getenv('HOME')) {
  50. throw new \RuntimeException('The HOME or COMPOSER_HOME environment variable must be set for composer to run correctly');
  51. }
  52. $home = rtrim(getenv('HOME'), '/') . '/.composer';
  53. }
  54. }
  55. return $home;
  56. }
  57. /**
  58. * @param string $home
  59. * @return string
  60. */
  61. protected static function getCacheDir($home)
  62. {
  63. $cacheDir = getenv('COMPOSER_CACHE_DIR');
  64. if (!$cacheDir) {
  65. if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
  66. if ($cacheDir = getenv('LOCALAPPDATA')) {
  67. $cacheDir .= '/Composer';
  68. } else {
  69. $cacheDir = $home . '/cache';
  70. }
  71. $cacheDir = strtr($cacheDir, '\\', '/');
  72. } else {
  73. $cacheDir = $home.'/cache';
  74. }
  75. }
  76. return $cacheDir;
  77. }
  78. /**
  79. * @param IOInterface|null $io
  80. * @return Config
  81. */
  82. public static function createConfig(IOInterface $io = null, $cwd = null)
  83. {
  84. $cwd = $cwd ?: getcwd();
  85. // determine home and cache dirs
  86. $home = self::getHomeDir();
  87. $cacheDir = self::getCacheDir($home);
  88. // Protect directory against web access. Since HOME could be
  89. // the www-data's user home and be web-accessible it is a
  90. // potential security risk
  91. foreach (array($home, $cacheDir) as $dir) {
  92. if (!file_exists($dir . '/.htaccess')) {
  93. if (!is_dir($dir)) {
  94. @mkdir($dir, 0777, true);
  95. }
  96. @file_put_contents($dir . '/.htaccess', 'Deny from all');
  97. }
  98. }
  99. $config = new Config(true, $cwd);
  100. // add dirs to the config
  101. $config->merge(array('config' => array('home' => $home, 'cache-dir' => $cacheDir)));
  102. // load global config
  103. $file = new JsonFile($config->get('home').'/config.json');
  104. if ($file->exists()) {
  105. if ($io && $io->isDebug()) {
  106. $io->writeError('Loading config file ' . $file->getPath());
  107. }
  108. $config->merge($file->read());
  109. }
  110. $config->setConfigSource(new JsonConfigSource($file));
  111. // load global auth file
  112. $file = new JsonFile($config->get('home').'/auth.json');
  113. if ($file->exists()) {
  114. if ($io && $io->isDebug()) {
  115. $io->writeError('Loading config file ' . $file->getPath());
  116. }
  117. $config->merge(array('config' => $file->read()));
  118. }
  119. $config->setAuthConfigSource(new JsonConfigSource($file, true));
  120. return $config;
  121. }
  122. public static function getComposerFile()
  123. {
  124. return trim(getenv('COMPOSER')) ?: './composer.json';
  125. }
  126. public static function createAdditionalStyles()
  127. {
  128. return array(
  129. 'highlight' => new OutputFormatterStyle('red'),
  130. 'warning' => new OutputFormatterStyle('black', 'yellow'),
  131. );
  132. }
  133. public static function createDefaultRepositories(IOInterface $io = null, Config $config = null, RepositoryManager $rm = null)
  134. {
  135. $repos = array();
  136. if (!$config) {
  137. $config = static::createConfig($io);
  138. }
  139. if (!$rm) {
  140. if (!$io) {
  141. throw new \InvalidArgumentException('This function requires either an IOInterface or a RepositoryManager');
  142. }
  143. $factory = new static;
  144. $rm = $factory->createRepositoryManager($io, $config);
  145. }
  146. foreach ($config->getRepositories() as $index => $repo) {
  147. if (is_string($repo)) {
  148. throw new \UnexpectedValueException('"repositories" should be an array of repository definitions, only a single repository was given');
  149. }
  150. if (!is_array($repo)) {
  151. throw new \UnexpectedValueException('Repository "'.$index.'" ('.json_encode($repo).') should be an array, '.gettype($repo).' given');
  152. }
  153. if (!isset($repo['type'])) {
  154. throw new \UnexpectedValueException('Repository "'.$index.'" ('.json_encode($repo).') must have a type defined');
  155. }
  156. $name = is_int($index) && isset($repo['url']) ? preg_replace('{^https?://}i', '', $repo['url']) : $index;
  157. while (isset($repos[$name])) {
  158. $name .= '2';
  159. }
  160. $repos[$name] = $rm->createRepository($repo['type'], $repo);
  161. }
  162. return $repos;
  163. }
  164. /**
  165. * Creates a Composer instance
  166. *
  167. * @param IOInterface $io IO instance
  168. * @param array|string|null $localConfig either a configuration array or a filename to read from, if null it will
  169. * read from the default filename
  170. * @param bool $disablePlugins Whether plugins should not be loaded
  171. * @param bool $fullLoad Whether to initialize everything or only main project stuff (used when loading the global composer)
  172. * @throws \InvalidArgumentException
  173. * @throws \UnexpectedValueException
  174. * @return Composer
  175. */
  176. public function createComposer(IOInterface $io, $localConfig = null, $disablePlugins = false, $cwd = null, $fullLoad = true)
  177. {
  178. $cwd = $cwd ?: getcwd();
  179. // load Composer configuration
  180. if (null === $localConfig) {
  181. $localConfig = static::getComposerFile();
  182. }
  183. if (is_string($localConfig)) {
  184. $composerFile = $localConfig;
  185. $file = new JsonFile($localConfig, new RemoteFilesystem($io));
  186. if (!$file->exists()) {
  187. if ($localConfig === './composer.json' || $localConfig === 'composer.json') {
  188. $message = 'Composer could not find a composer.json file in '.$cwd;
  189. } else {
  190. $message = 'Composer could not find the config file: '.$localConfig;
  191. }
  192. $instructions = 'To initialize a project, please create a composer.json file as described in the https://getcomposer.org/ "Getting Started" section';
  193. throw new \InvalidArgumentException($message.PHP_EOL.$instructions);
  194. }
  195. $file->validateSchema(JsonFile::LAX_SCHEMA);
  196. $localConfig = $file->read();
  197. }
  198. // Load config and override with local config/auth config
  199. $config = static::createConfig($io, $cwd);
  200. $config->merge($localConfig);
  201. if (isset($composerFile)) {
  202. if ($io && $io->isDebug()) {
  203. $io->writeError('Loading config file ' . $composerFile);
  204. }
  205. $localAuthFile = new JsonFile(dirname(realpath($composerFile)) . '/auth.json');
  206. if ($localAuthFile->exists()) {
  207. if ($io && $io->isDebug()) {
  208. $io->writeError('Loading config file ' . $localAuthFile->getPath());
  209. }
  210. $config->merge(array('config' => $localAuthFile->read()));
  211. $config->setAuthConfigSource(new JsonConfigSource($localAuthFile, true));
  212. }
  213. }
  214. $vendorDir = $config->get('vendor-dir');
  215. $binDir = $config->get('bin-dir');
  216. // initialize composer
  217. $composer = new Composer();
  218. $composer->setConfig($config);
  219. if ($fullLoad) {
  220. // load auth configs into the IO instance
  221. $io->loadConfiguration($config);
  222. }
  223. // initialize event dispatcher
  224. $dispatcher = new EventDispatcher($composer, $io);
  225. $composer->setEventDispatcher($dispatcher);
  226. // initialize repository manager
  227. $rm = $this->createRepositoryManager($io, $config, $dispatcher);
  228. $composer->setRepositoryManager($rm);
  229. // load local repository
  230. $this->addLocalRepository($rm, $vendorDir);
  231. // load package
  232. $parser = new VersionParser;
  233. $guesser = new VersionGuesser($config, new ProcessExecutor($io), $parser);
  234. $loader = new Package\Loader\RootPackageLoader($rm, $config, $parser, $guesser);
  235. $package = $loader->load($localConfig);
  236. $composer->setPackage($package);
  237. // initialize installation manager
  238. $im = $this->createInstallationManager();
  239. $composer->setInstallationManager($im);
  240. if ($fullLoad) {
  241. // initialize download manager
  242. $dm = $this->createDownloadManager($io, $config, $dispatcher);
  243. $composer->setDownloadManager($dm);
  244. // initialize autoload generator
  245. $generator = new AutoloadGenerator($dispatcher, $io);
  246. $composer->setAutoloadGenerator($generator);
  247. }
  248. // add installers to the manager (must happen after download manager is created since they read it out of $composer)
  249. $this->createDefaultInstallers($im, $composer, $io);
  250. if ($fullLoad) {
  251. $globalComposer = $this->createGlobalComposer($io, $config, $disablePlugins);
  252. $pm = $this->createPluginManager($io, $composer, $globalComposer, $disablePlugins);
  253. $composer->setPluginManager($pm);
  254. $pm->loadInstalledPlugins();
  255. // once we have plugins and custom installers we can
  256. // purge packages from local repos if they have been deleted on the filesystem
  257. if ($rm->getLocalRepository()) {
  258. $this->purgePackages($rm->getLocalRepository(), $im);
  259. }
  260. }
  261. // init locker if possible
  262. if ($fullLoad && isset($composerFile)) {
  263. $lockFile = "json" === pathinfo($composerFile, PATHINFO_EXTENSION)
  264. ? substr($composerFile, 0, -4).'lock'
  265. : $composerFile . '.lock';
  266. $locker = new Package\Locker($io, new JsonFile($lockFile, new RemoteFilesystem($io, $config)), $rm, $im, file_get_contents($composerFile));
  267. $composer->setLocker($locker);
  268. }
  269. return $composer;
  270. }
  271. /**
  272. * @param IOInterface $io
  273. * @param Config $config
  274. * @param EventDispatcher $eventDispatcher
  275. * @return Repository\RepositoryManager
  276. */
  277. protected function createRepositoryManager(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null)
  278. {
  279. $rm = new RepositoryManager($io, $config, $eventDispatcher);
  280. $rm->setRepositoryClass('composer', 'Composer\Repository\ComposerRepository');
  281. $rm->setRepositoryClass('vcs', 'Composer\Repository\VcsRepository');
  282. $rm->setRepositoryClass('package', 'Composer\Repository\PackageRepository');
  283. $rm->setRepositoryClass('pear', 'Composer\Repository\PearRepository');
  284. $rm->setRepositoryClass('git', 'Composer\Repository\VcsRepository');
  285. $rm->setRepositoryClass('svn', 'Composer\Repository\VcsRepository');
  286. $rm->setRepositoryClass('perforce', 'Composer\Repository\VcsRepository');
  287. $rm->setRepositoryClass('hg', 'Composer\Repository\VcsRepository');
  288. $rm->setRepositoryClass('artifact', 'Composer\Repository\ArtifactRepository');
  289. $rm->setRepositoryClass('path', 'Composer\Repository\PathRepository');
  290. return $rm;
  291. }
  292. /**
  293. * @param Repository\RepositoryManager $rm
  294. * @param string $vendorDir
  295. */
  296. protected function addLocalRepository(RepositoryManager $rm, $vendorDir)
  297. {
  298. $rm->setLocalRepository(new Repository\InstalledFilesystemRepository(new JsonFile($vendorDir.'/composer/installed.json')));
  299. }
  300. /**
  301. * @param Config $config
  302. * @return Composer|null
  303. */
  304. protected function createGlobalComposer(IOInterface $io, Config $config, $disablePlugins)
  305. {
  306. if (realpath($config->get('home')) === getcwd()) {
  307. return;
  308. }
  309. $composer = null;
  310. try {
  311. $composer = self::createComposer($io, $config->get('home') . '/composer.json', $disablePlugins, $config->get('home'), false);
  312. } catch (\Exception $e) {
  313. if ($io->isDebug()) {
  314. $io->writeError('Failed to initialize global composer: '.$e->getMessage());
  315. }
  316. }
  317. return $composer;
  318. }
  319. /**
  320. * @param IO\IOInterface $io
  321. * @param Config $config
  322. * @param EventDispatcher $eventDispatcher
  323. * @return Downloader\DownloadManager
  324. */
  325. public function createDownloadManager(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null)
  326. {
  327. $cache = null;
  328. if ($config->get('cache-files-ttl') > 0) {
  329. $cache = new Cache($io, $config->get('cache-files-dir'), 'a-z0-9_./');
  330. }
  331. $dm = new Downloader\DownloadManager($io);
  332. switch ($config->get('preferred-install')) {
  333. case 'dist':
  334. $dm->setPreferDist(true);
  335. break;
  336. case 'source':
  337. $dm->setPreferSource(true);
  338. break;
  339. case 'auto':
  340. default:
  341. // noop
  342. break;
  343. }
  344. $dm->setDownloader('git', new Downloader\GitDownloader($io, $config));
  345. $dm->setDownloader('svn', new Downloader\SvnDownloader($io, $config));
  346. $dm->setDownloader('hg', new Downloader\HgDownloader($io, $config));
  347. $dm->setDownloader('perforce', new Downloader\PerforceDownloader($io, $config));
  348. $dm->setDownloader('zip', new Downloader\ZipDownloader($io, $config, $eventDispatcher, $cache));
  349. $dm->setDownloader('rar', new Downloader\RarDownloader($io, $config, $eventDispatcher, $cache));
  350. $dm->setDownloader('tar', new Downloader\TarDownloader($io, $config, $eventDispatcher, $cache));
  351. $dm->setDownloader('gzip', new Downloader\GzipDownloader($io, $config, $eventDispatcher, $cache));
  352. $dm->setDownloader('phar', new Downloader\PharDownloader($io, $config, $eventDispatcher, $cache));
  353. $dm->setDownloader('file', new Downloader\FileDownloader($io, $config, $eventDispatcher, $cache));
  354. $dm->setDownloader('path', new Downloader\PathDownloader($io, $config, $eventDispatcher, $cache));
  355. return $dm;
  356. }
  357. /**
  358. * @param Config $config The configuration
  359. * @param Downloader\DownloadManager $dm Manager use to download sources
  360. * @return Archiver\ArchiveManager
  361. */
  362. public function createArchiveManager(Config $config, Downloader\DownloadManager $dm = null)
  363. {
  364. if (null === $dm) {
  365. $io = new IO\NullIO();
  366. $io->loadConfiguration($config);
  367. $dm = $this->createDownloadManager($io, $config);
  368. }
  369. $am = new Archiver\ArchiveManager($dm);
  370. $am->addArchiver(new Archiver\PharArchiver);
  371. return $am;
  372. }
  373. /**
  374. * @param IOInterface $io
  375. * @param Composer $composer
  376. * @param Composer $globalComposer
  377. * @param bool $disablePlugins
  378. * @return Plugin\PluginManager
  379. */
  380. protected function createPluginManager(IOInterface $io, Composer $composer, Composer $globalComposer = null, $disablePlugins = false)
  381. {
  382. return new Plugin\PluginManager($io, $composer, $globalComposer, $disablePlugins);
  383. }
  384. /**
  385. * @return Installer\InstallationManager
  386. */
  387. protected function createInstallationManager()
  388. {
  389. return new Installer\InstallationManager();
  390. }
  391. /**
  392. * @param Installer\InstallationManager $im
  393. * @param Composer $composer
  394. * @param IO\IOInterface $io
  395. */
  396. protected function createDefaultInstallers(Installer\InstallationManager $im, Composer $composer, IOInterface $io)
  397. {
  398. $im->addInstaller(new Installer\LibraryInstaller($io, $composer, null));
  399. $im->addInstaller(new Installer\PearInstaller($io, $composer, 'pear-library'));
  400. $im->addInstaller(new Installer\PluginInstaller($io, $composer));
  401. $im->addInstaller(new Installer\MetapackageInstaller($io));
  402. }
  403. /**
  404. * @param WritableRepositoryInterface $repo repository to purge packages from
  405. * @param Installer\InstallationManager $im manager to check whether packages are still installed
  406. */
  407. protected function purgePackages(WritableRepositoryInterface $repo, Installer\InstallationManager $im)
  408. {
  409. foreach ($repo->getPackages() as $package) {
  410. if (!$im->isPackageInstalled($repo, $package)) {
  411. $repo->removePackage($package);
  412. }
  413. }
  414. }
  415. /**
  416. * @param IOInterface $io IO instance
  417. * @param mixed $config either a configuration array or a filename to read from, if null it will read from
  418. * the default filename
  419. * @param bool $disablePlugins Whether plugins should not be loaded
  420. * @return Composer
  421. */
  422. public static function create(IOInterface $io, $config = null, $disablePlugins = false)
  423. {
  424. $factory = new static();
  425. return $factory->createComposer($io, $config, $disablePlugins);
  426. }
  427. }