Factory.php 14 KB

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