Factory.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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\Repository\ComposerRepository;
  16. use Composer\Repository\RepositoryManager;
  17. use Composer\Util\ProcessExecutor;
  18. use Composer\Util\RemoteFilesystem;
  19. use Symfony\Component\Console\Formatter\OutputFormatterStyle;
  20. /**
  21. * Creates a configured instance of composer.
  22. *
  23. * @author Ryan Weaver <ryan@knplabs.com>
  24. * @author Jordi Boggiano <j.boggiano@seld.be>
  25. * @author Igor Wiedler <igor@wiedler.ch>
  26. */
  27. class Factory
  28. {
  29. /**
  30. * @return Config
  31. */
  32. public static function createConfig()
  33. {
  34. // determine home and cache dirs
  35. $home = getenv('COMPOSER_HOME');
  36. $cacheDir = getenv('COMPOSER_CACHE_DIR');
  37. if (!$home) {
  38. if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
  39. $home = getenv('APPDATA') . '/Composer';
  40. } else {
  41. $home = rtrim(getenv('HOME'), '/') . '/.composer';
  42. }
  43. }
  44. if (!$cacheDir) {
  45. if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
  46. if ($cacheDir = getenv('LOCALAPPDATA')) {
  47. $cacheDir .= '/Composer';
  48. } else {
  49. $cacheDir = getenv('APPDATA') . '/Composer/cache';
  50. }
  51. } else {
  52. $cacheDir = $home.'/cache';
  53. }
  54. }
  55. // Protect directory against web access. Since HOME could be
  56. // the www-data's user home and be web-accessible it is a
  57. // potential security risk
  58. foreach (array($home, $cacheDir) as $dir) {
  59. if (!file_exists($dir . '/.htaccess')) {
  60. if (!is_dir($dir)) {
  61. @mkdir($dir, 0777, true);
  62. }
  63. @file_put_contents($dir . '/.htaccess', 'Deny from all');
  64. }
  65. }
  66. $config = new Config();
  67. // add dirs to the config
  68. $config->merge(array('config' => array('home' => $home, 'cache-dir' => $cacheDir)));
  69. $file = new JsonFile($home.'/config.json');
  70. if ($file->exists()) {
  71. $config->merge($file->read());
  72. }
  73. $config->setConfigSource(new JsonConfigSource($file));
  74. // move old cache dirs to the new locations
  75. $legacyPaths = array(
  76. 'cache-repo-dir' => array('/cache' => '/http*', '/cache.svn' => '/*', '/cache.github' => '/*'),
  77. 'cache-vcs-dir' => array('/cache.git' => '/*', '/cache.hg' => '/*'),
  78. 'cache-files-dir' => array('/cache.files' => '/*'),
  79. );
  80. foreach ($legacyPaths as $key => $oldPaths) {
  81. foreach ($oldPaths as $oldPath => $match) {
  82. $dir = $config->get($key);
  83. if ('/cache.github' === $oldPath) {
  84. $dir .= '/github.com';
  85. }
  86. $oldPath = $config->get('home').$oldPath;
  87. $oldPathMatch = $oldPath . $match;
  88. if (is_dir($oldPath) && $dir !== $oldPath) {
  89. if (!is_dir($dir)) {
  90. if (!@mkdir($dir, 0777, true)) {
  91. continue;
  92. }
  93. }
  94. if (is_array($children = glob($oldPathMatch))) {
  95. foreach ($children as $child) {
  96. @rename($child, $dir.'/'.basename($child));
  97. }
  98. }
  99. @unlink($oldPath);
  100. }
  101. }
  102. }
  103. return $config;
  104. }
  105. public function getComposerFile()
  106. {
  107. return getenv('COMPOSER') ?: 'composer.json';
  108. }
  109. public static function createAdditionalStyles()
  110. {
  111. return array(
  112. 'highlight' => new OutputFormatterStyle('red'),
  113. 'warning' => new OutputFormatterStyle('black', 'yellow'),
  114. );
  115. }
  116. public static function createDefaultRepositories(IOInterface $io = null, Config $config = null, RepositoryManager $rm = null)
  117. {
  118. $repos = array();
  119. if (!$config) {
  120. $config = static::createConfig();
  121. }
  122. if (!$rm) {
  123. if (!$io) {
  124. throw new \InvalidArgumentException('This function requires either an IOInterface or a RepositoryManager');
  125. }
  126. $factory = new static;
  127. $rm = $factory->createRepositoryManager($io, $config);
  128. }
  129. foreach ($config->getRepositories() as $index => $repo) {
  130. if (!is_array($repo)) {
  131. throw new \UnexpectedValueException('Repository '.$index.' ('.json_encode($repo).') should be an array, '.gettype($repo).' given');
  132. }
  133. if (!isset($repo['type'])) {
  134. throw new \UnexpectedValueException('Repository '.$index.' ('.json_encode($repo).') must have a type defined');
  135. }
  136. $name = is_int($index) && isset($repo['url']) ? preg_replace('{^https?://}i', '', $repo['url']) : $index;
  137. while (isset($repos[$name])) {
  138. $name .= '2';
  139. }
  140. $repos[$name] = $rm->createRepository($repo['type'], $repo);
  141. }
  142. return $repos;
  143. }
  144. /**
  145. * Creates a Composer instance
  146. *
  147. * @param IOInterface $io IO instance
  148. * @param array|string|null $localConfig either a configuration array or a filename to read from, if null it will
  149. * read from the default filename
  150. * @throws \InvalidArgumentException
  151. * @return Composer
  152. */
  153. public function createComposer(IOInterface $io, $localConfig = null)
  154. {
  155. // load Composer configuration
  156. if (null === $localConfig) {
  157. $localConfig = $this->getComposerFile();
  158. }
  159. if (is_string($localConfig)) {
  160. $composerFile = $localConfig;
  161. $file = new JsonFile($localConfig, new RemoteFilesystem($io));
  162. if (!$file->exists()) {
  163. if ($localConfig === 'composer.json') {
  164. $message = 'Composer could not find a composer.json file in '.getcwd();
  165. } else {
  166. $message = 'Composer could not find the config file: '.$localConfig;
  167. }
  168. $instructions = 'To initialize a project, please create a composer.json file as described in the http://getcomposer.org/ "Getting Started" section';
  169. throw new \InvalidArgumentException($message.PHP_EOL.$instructions);
  170. }
  171. $file->validateSchema(JsonFile::LAX_SCHEMA);
  172. $localConfig = $file->read();
  173. }
  174. // Configuration defaults
  175. $config = static::createConfig();
  176. $config->merge($localConfig);
  177. // reload oauth token from config if available
  178. if ($tokens = $config->get('github-oauth')) {
  179. foreach ($tokens as $domain => $token) {
  180. $io->setAuthentication($domain, $token, 'x-oauth-basic');
  181. }
  182. }
  183. $vendorDir = $config->get('vendor-dir');
  184. $binDir = $config->get('bin-dir');
  185. // setup process timeout
  186. ProcessExecutor::setTimeout((int) $config->get('process-timeout'));
  187. // initialize repository manager
  188. $rm = $this->createRepositoryManager($io, $config);
  189. // load local repository
  190. $this->addLocalRepository($rm, $vendorDir);
  191. // load package
  192. $loader = new Package\Loader\RootPackageLoader($rm, $config);
  193. $package = $loader->load($localConfig);
  194. // initialize download manager
  195. $dm = $this->createDownloadManager($io, $config);
  196. // initialize installation manager
  197. $im = $this->createInstallationManager();
  198. // initialize composer
  199. $composer = new Composer();
  200. $composer->setConfig($config);
  201. $composer->setPackage($package);
  202. $composer->setRepositoryManager($rm);
  203. $composer->setDownloadManager($dm);
  204. $composer->setInstallationManager($im);
  205. // add installers to the manager
  206. $this->createDefaultInstallers($im, $composer, $io);
  207. // purge packages if they have been deleted on the filesystem
  208. $this->purgePackages($rm, $im);
  209. // init locker if possible
  210. if (isset($composerFile)) {
  211. $lockFile = "json" === pathinfo($composerFile, PATHINFO_EXTENSION)
  212. ? substr($composerFile, 0, -4).'lock'
  213. : $composerFile . '.lock';
  214. $locker = new Package\Locker(new JsonFile($lockFile, new RemoteFilesystem($io)), $rm, $im, md5_file($composerFile));
  215. $composer->setLocker($locker);
  216. }
  217. return $composer;
  218. }
  219. /**
  220. * @param IOInterface $io
  221. * @param Config $config
  222. * @return Repository\RepositoryManager
  223. */
  224. protected function createRepositoryManager(IOInterface $io, Config $config)
  225. {
  226. $rm = new RepositoryManager($io, $config);
  227. $rm->setRepositoryClass('composer', 'Composer\Repository\ComposerRepository');
  228. $rm->setRepositoryClass('vcs', 'Composer\Repository\VcsRepository');
  229. $rm->setRepositoryClass('package', 'Composer\Repository\PackageRepository');
  230. $rm->setRepositoryClass('pear', 'Composer\Repository\PearRepository');
  231. $rm->setRepositoryClass('git', 'Composer\Repository\VcsRepository');
  232. $rm->setRepositoryClass('svn', 'Composer\Repository\VcsRepository');
  233. $rm->setRepositoryClass('hg', 'Composer\Repository\VcsRepository');
  234. return $rm;
  235. }
  236. /**
  237. * @param Repository\RepositoryManager $rm
  238. * @param string $vendorDir
  239. */
  240. protected function addLocalRepository(RepositoryManager $rm, $vendorDir)
  241. {
  242. $rm->setLocalRepository(new Repository\InstalledFilesystemRepository(new JsonFile($vendorDir.'/composer/installed.json')));
  243. $rm->setLocalDevRepository(new Repository\InstalledFilesystemRepository(new JsonFile($vendorDir.'/composer/installed_dev.json')));
  244. }
  245. /**
  246. * @param IO\IOInterface $io
  247. * @param Config $config
  248. * @return Downloader\DownloadManager
  249. */
  250. public function createDownloadManager(IOInterface $io, Config $config)
  251. {
  252. $cache = null;
  253. if ($config->get('cache-files-ttl') > 0) {
  254. $cache = new Cache($io, $config->get('cache-files-dir'), 'a-z0-9_./');
  255. }
  256. $dm = new Downloader\DownloadManager();
  257. $dm->setDownloader('git', new Downloader\GitDownloader($io, $config));
  258. $dm->setDownloader('svn', new Downloader\SvnDownloader($io, $config));
  259. $dm->setDownloader('hg', new Downloader\HgDownloader($io, $config));
  260. $dm->setDownloader('zip', new Downloader\ZipDownloader($io, $config, $cache));
  261. $dm->setDownloader('tar', new Downloader\TarDownloader($io, $config, $cache));
  262. $dm->setDownloader('phar', new Downloader\PharDownloader($io, $config, $cache));
  263. $dm->setDownloader('file', new Downloader\FileDownloader($io, $config, $cache));
  264. return $dm;
  265. }
  266. /**
  267. * @return Installer\InstallationManager
  268. */
  269. protected function createInstallationManager()
  270. {
  271. return new Installer\InstallationManager();
  272. }
  273. /**
  274. * @param Installer\InstallationManager $im
  275. * @param Composer $composer
  276. * @param IO\IOInterface $io
  277. */
  278. protected function createDefaultInstallers(Installer\InstallationManager $im, Composer $composer, IOInterface $io)
  279. {
  280. $im->addInstaller(new Installer\LibraryInstaller($io, $composer, null));
  281. $im->addInstaller(new Installer\PearInstaller($io, $composer, 'pear-library'));
  282. $im->addInstaller(new Installer\InstallerInstaller($io, $composer));
  283. $im->addInstaller(new Installer\MetapackageInstaller($io));
  284. }
  285. /**
  286. * @param Repository\RepositoryManager $rm
  287. * @param Installer\InstallationManager $im
  288. */
  289. protected function purgePackages(Repository\RepositoryManager $rm, Installer\InstallationManager $im)
  290. {
  291. foreach ($rm->getLocalRepositories() as $repo) {
  292. /* @var $repo Repository\WritableRepositoryInterface */
  293. foreach ($repo->getPackages() as $package) {
  294. if (!$im->isPackageInstalled($repo, $package)) {
  295. $repo->removePackage($package);
  296. }
  297. }
  298. }
  299. }
  300. /**
  301. * @param IOInterface $io IO instance
  302. * @param mixed $config either a configuration array or a filename to read from, if null it will read from
  303. * the default filename
  304. * @return Composer
  305. */
  306. public static function create(IOInterface $io, $config = null)
  307. {
  308. $factory = new static();
  309. return $factory->createComposer($io, $config);
  310. }
  311. }