Factory.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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\Repository\RepositoryManager;
  17. use Composer\Repository\RepositoryInterface;
  18. use Composer\Util\ProcessExecutor;
  19. use Composer\Util\RemoteFilesystem;
  20. use Composer\Util\Filesystem;
  21. use Symfony\Component\Console\Formatter\OutputFormatterStyle;
  22. use Composer\EventDispatcher\EventDispatcher;
  23. use Composer\Autoload\AutoloadGenerator;
  24. use Composer\Package\Version\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. * @return string
  37. * @throws \RuntimeException
  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)
  84. {
  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();
  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($home.'/config.json');
  104. if ($file->exists()) {
  105. if ($io && $io->isDebug()) {
  106. $io->write('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->write('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_array($repo)) {
  148. throw new \UnexpectedValueException('Repository '.$index.' ('.json_encode($repo).') should be an array, '.gettype($repo).' given');
  149. }
  150. if (!isset($repo['type'])) {
  151. throw new \UnexpectedValueException('Repository '.$index.' ('.json_encode($repo).') must have a type defined');
  152. }
  153. $name = is_int($index) && isset($repo['url']) ? preg_replace('{^https?://}i', '', $repo['url']) : $index;
  154. while (isset($repos[$name])) {
  155. $name .= '2';
  156. }
  157. $repos[$name] = $rm->createRepository($repo['type'], $repo);
  158. }
  159. return $repos;
  160. }
  161. /**
  162. * Creates a Composer instance
  163. *
  164. * @param IOInterface $io IO instance
  165. * @param array|string|null $localConfig either a configuration array or a filename to read from, if null it will
  166. * read from the default filename
  167. * @param bool $disablePlugins Whether plugins should not be loaded
  168. * @throws \InvalidArgumentException
  169. * @throws \UnexpectedValueException
  170. * @return Composer
  171. */
  172. public function createComposer(IOInterface $io, $localConfig = null, $disablePlugins = false)
  173. {
  174. // load Composer configuration
  175. if (null === $localConfig) {
  176. $localConfig = static::getComposerFile();
  177. }
  178. if (is_string($localConfig)) {
  179. $composerFile = $localConfig;
  180. $file = new JsonFile($localConfig, new RemoteFilesystem($io));
  181. if (!$file->exists()) {
  182. if ($localConfig === './composer.json' || $localConfig === 'composer.json') {
  183. $message = 'Composer could not find a composer.json file in '.getcwd();
  184. } else {
  185. $message = 'Composer could not find the config file: '.$localConfig;
  186. }
  187. $instructions = 'To initialize a project, please create a composer.json file as described in the http://getcomposer.org/ "Getting Started" section';
  188. throw new \InvalidArgumentException($message.PHP_EOL.$instructions);
  189. }
  190. $file->validateSchema(JsonFile::LAX_SCHEMA);
  191. $localConfig = $file->read();
  192. }
  193. // Load config and override with local config/auth config
  194. $config = static::createConfig($io);
  195. $config->merge($localConfig);
  196. if (isset($composerFile)) {
  197. if ($io && $io->isDebug()) {
  198. $io->write('Loading config file ' . $composerFile);
  199. }
  200. $localAuthFile = new JsonFile(dirname(realpath($composerFile)) . '/auth.json');
  201. if ($localAuthFile->exists()) {
  202. if ($io && $io->isDebug()) {
  203. $io->write('Loading config file ' . $localAuthFile->getPath());
  204. }
  205. $config->merge(array('config' => $localAuthFile->read()));
  206. $config->setAuthConfigSource(new JsonConfigSource($localAuthFile, true));
  207. }
  208. }
  209. // load auth configs into the IO instance
  210. $io->loadConfiguration($config);
  211. $vendorDir = $config->get('vendor-dir');
  212. $binDir = $config->get('bin-dir');
  213. // setup process timeout
  214. ProcessExecutor::setTimeout((int) $config->get('process-timeout'));
  215. // initialize composer
  216. $composer = new Composer();
  217. $composer->setConfig($config);
  218. // initialize event dispatcher
  219. $dispatcher = new EventDispatcher($composer, $io);
  220. // initialize repository manager
  221. $rm = $this->createRepositoryManager($io, $config, $dispatcher);
  222. // load local repository
  223. $this->addLocalRepository($rm, $vendorDir);
  224. // load package
  225. $parser = new VersionParser;
  226. $loader = new Package\Loader\RootPackageLoader($rm, $config, $parser, new ProcessExecutor($io));
  227. $package = $loader->load($localConfig);
  228. // initialize installation manager
  229. $im = $this->createInstallationManager();
  230. // Composer composition
  231. $composer->setPackage($package);
  232. $composer->setRepositoryManager($rm);
  233. $composer->setInstallationManager($im);
  234. // initialize download manager
  235. $dm = $this->createDownloadManager($io, $config, $dispatcher);
  236. $composer->setDownloadManager($dm);
  237. $composer->setEventDispatcher($dispatcher);
  238. // initialize autoload generator
  239. $generator = new AutoloadGenerator($dispatcher, $io);
  240. $composer->setAutoloadGenerator($generator);
  241. // add installers to the manager
  242. $this->createDefaultInstallers($im, $composer, $io);
  243. $globalRepository = $this->createGlobalRepository($config, $vendorDir);
  244. $pm = $this->createPluginManager($composer, $io, $globalRepository);
  245. $composer->setPluginManager($pm);
  246. if (!$disablePlugins) {
  247. $pm->loadInstalledPlugins();
  248. }
  249. // purge packages if they have been deleted on the filesystem
  250. $this->purgePackages($rm, $im);
  251. // init locker if possible
  252. if (isset($composerFile)) {
  253. $lockFile = "json" === pathinfo($composerFile, PATHINFO_EXTENSION)
  254. ? substr($composerFile, 0, -4).'lock'
  255. : $composerFile . '.lock';
  256. $locker = new Package\Locker($io, new JsonFile($lockFile, new RemoteFilesystem($io, $config)), $rm, $im, md5_file($composerFile));
  257. $composer->setLocker($locker);
  258. }
  259. return $composer;
  260. }
  261. /**
  262. * @param IOInterface $io
  263. * @param Config $config
  264. * @param EventDispatcher $eventDispatcher
  265. * @return Repository\RepositoryManager
  266. */
  267. protected function createRepositoryManager(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null)
  268. {
  269. $rm = new RepositoryManager($io, $config, $eventDispatcher);
  270. $rm->setRepositoryClass('composer', 'Composer\Repository\ComposerRepository');
  271. $rm->setRepositoryClass('vcs', 'Composer\Repository\VcsRepository');
  272. $rm->setRepositoryClass('package', 'Composer\Repository\PackageRepository');
  273. $rm->setRepositoryClass('pear', 'Composer\Repository\PearRepository');
  274. $rm->setRepositoryClass('git', 'Composer\Repository\VcsRepository');
  275. $rm->setRepositoryClass('svn', 'Composer\Repository\VcsRepository');
  276. $rm->setRepositoryClass('perforce', 'Composer\Repository\VcsRepository');
  277. $rm->setRepositoryClass('hg', 'Composer\Repository\VcsRepository');
  278. $rm->setRepositoryClass('artifact', 'Composer\Repository\ArtifactRepository');
  279. return $rm;
  280. }
  281. /**
  282. * @param Repository\RepositoryManager $rm
  283. * @param string $vendorDir
  284. */
  285. protected function addLocalRepository(RepositoryManager $rm, $vendorDir)
  286. {
  287. $rm->setLocalRepository(new Repository\InstalledFilesystemRepository(new JsonFile($vendorDir.'/composer/installed.json')));
  288. }
  289. /**
  290. * @param Config $config
  291. * @param string $vendorDir
  292. * @return Repository\InstalledFilesystemRepository|null
  293. */
  294. protected function createGlobalRepository(Config $config, $vendorDir)
  295. {
  296. if ($config->get('home') == $vendorDir) {
  297. return null;
  298. }
  299. $path = $config->get('home').'/vendor/composer/installed.json';
  300. if (!file_exists($path)) {
  301. return null;
  302. }
  303. return new Repository\InstalledFilesystemRepository(new JsonFile($path));
  304. }
  305. /**
  306. * @param IO\IOInterface $io
  307. * @param Config $config
  308. * @param EventDispatcher $eventDispatcher
  309. * @return Downloader\DownloadManager
  310. */
  311. public function createDownloadManager(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null)
  312. {
  313. $cache = null;
  314. if ($config->get('cache-files-ttl') > 0) {
  315. $cache = new Cache($io, $config->get('cache-files-dir'), 'a-z0-9_./');
  316. }
  317. $dm = new Downloader\DownloadManager($io);
  318. switch ($config->get('preferred-install')) {
  319. case 'dist':
  320. $dm->setPreferDist(true);
  321. break;
  322. case 'source':
  323. $dm->setPreferSource(true);
  324. break;
  325. case 'auto':
  326. default:
  327. // noop
  328. break;
  329. }
  330. $dm->setDownloader('git', new Downloader\GitDownloader($io, $config));
  331. $dm->setDownloader('svn', new Downloader\SvnDownloader($io, $config));
  332. $dm->setDownloader('hg', new Downloader\HgDownloader($io, $config));
  333. $dm->setDownloader('perforce', new Downloader\PerforceDownloader($io, $config));
  334. $dm->setDownloader('zip', new Downloader\ZipDownloader($io, $config, $eventDispatcher, $cache));
  335. $dm->setDownloader('rar', new Downloader\RarDownloader($io, $config, $eventDispatcher, $cache));
  336. $dm->setDownloader('tar', new Downloader\TarDownloader($io, $config, $eventDispatcher, $cache));
  337. $dm->setDownloader('gzip', new Downloader\GzipDownloader($io, $config, $eventDispatcher, $cache));
  338. $dm->setDownloader('phar', new Downloader\PharDownloader($io, $config, $eventDispatcher, $cache));
  339. $dm->setDownloader('file', new Downloader\FileDownloader($io, $config, $eventDispatcher, $cache));
  340. return $dm;
  341. }
  342. /**
  343. * @param Config $config The configuration
  344. * @param Downloader\DownloadManager $dm Manager use to download sources
  345. *
  346. * @return Archiver\ArchiveManager
  347. */
  348. public function createArchiveManager(Config $config, Downloader\DownloadManager $dm = null)
  349. {
  350. if (null === $dm) {
  351. $io = new IO\NullIO();
  352. $io->loadConfiguration($config);
  353. $dm = $this->createDownloadManager($io, $config);
  354. }
  355. $am = new Archiver\ArchiveManager($dm);
  356. $am->addArchiver(new Archiver\PharArchiver);
  357. return $am;
  358. }
  359. /**
  360. * @param Composer $composer
  361. * @param IOInterface $io
  362. * @param RepositoryInterface $globalRepository
  363. * @return Plugin\PluginManager
  364. */
  365. protected function createPluginManager(Composer $composer, IOInterface $io, RepositoryInterface $globalRepository = null)
  366. {
  367. return new Plugin\PluginManager($composer, $io, $globalRepository);
  368. }
  369. /**
  370. * @return Installer\InstallationManager
  371. */
  372. protected function createInstallationManager()
  373. {
  374. return new Installer\InstallationManager();
  375. }
  376. /**
  377. * @param Installer\InstallationManager $im
  378. * @param Composer $composer
  379. * @param IO\IOInterface $io
  380. */
  381. protected function createDefaultInstallers(Installer\InstallationManager $im, Composer $composer, IOInterface $io)
  382. {
  383. $im->addInstaller(new Installer\LibraryInstaller($io, $composer, null));
  384. $im->addInstaller(new Installer\PearInstaller($io, $composer, 'pear-library'));
  385. $im->addInstaller(new Installer\PluginInstaller($io, $composer));
  386. $im->addInstaller(new Installer\MetapackageInstaller($io));
  387. }
  388. /**
  389. * @param Repository\RepositoryManager $rm
  390. * @param Installer\InstallationManager $im
  391. */
  392. protected function purgePackages(Repository\RepositoryManager $rm, Installer\InstallationManager $im)
  393. {
  394. $repo = $rm->getLocalRepository();
  395. foreach ($repo->getPackages() as $package) {
  396. if (!$im->isPackageInstalled($repo, $package)) {
  397. $repo->removePackage($package);
  398. }
  399. }
  400. }
  401. /**
  402. * @param IOInterface $io IO instance
  403. * @param mixed $config either a configuration array or a filename to read from, if null it will read from
  404. * the default filename
  405. * @param bool $disablePlugins Whether plugins should not be loaded
  406. * @return Composer
  407. */
  408. public static function create(IOInterface $io, $config = null, $disablePlugins = false)
  409. {
  410. $factory = new static();
  411. return $factory->createComposer($io, $config, $disablePlugins);
  412. }
  413. }