Factory.php 18 KB

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