PageRenderTime 51ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Composer/Factory.php

https://github.com/theshadow/composer
PHP | 359 lines | 234 code | 45 blank | 80 comment | 34 complexity | 145dd6a465a1b0aa48ab87c2c9b61ac3 MD5 | raw file
  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 static 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 = static::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. if (!preg_match('{^[a-z0-9]+$}', $token)) {
  181. throw new \UnexpectedValueException('Your github oauth token for '.$domain.' contains invalid characters: "'.$token.'"');
  182. }
  183. $io->setAuthentication($domain, $token, 'x-oauth-basic');
  184. }
  185. }
  186. $vendorDir = $config->get('vendor-dir');
  187. $binDir = $config->get('bin-dir');
  188. // setup process timeout
  189. ProcessExecutor::setTimeout((int) $config->get('process-timeout'));
  190. // initialize repository manager
  191. $rm = $this->createRepositoryManager($io, $config);
  192. // load local repository
  193. $this->addLocalRepository($rm, $vendorDir);
  194. // load package
  195. $loader = new Package\Loader\RootPackageLoader($rm, $config);
  196. $package = $loader->load($localConfig);
  197. // initialize download manager
  198. $dm = $this->createDownloadManager($io, $config);
  199. // initialize installation manager
  200. $im = $this->createInstallationManager();
  201. // initialize composer
  202. $composer = new Composer();
  203. $composer->setConfig($config);
  204. $composer->setPackage($package);
  205. $composer->setRepositoryManager($rm);
  206. $composer->setDownloadManager($dm);
  207. $composer->setInstallationManager($im);
  208. // add installers to the manager
  209. $this->createDefaultInstallers($im, $composer, $io);
  210. // purge packages if they have been deleted on the filesystem
  211. $this->purgePackages($rm, $im);
  212. // init locker if possible
  213. if (isset($composerFile)) {
  214. $lockFile = "json" === pathinfo($composerFile, PATHINFO_EXTENSION)
  215. ? substr($composerFile, 0, -4).'lock'
  216. : $composerFile . '.lock';
  217. $locker = new Package\Locker(new JsonFile($lockFile, new RemoteFilesystem($io)), $rm, $im, md5_file($composerFile));
  218. $composer->setLocker($locker);
  219. }
  220. return $composer;
  221. }
  222. /**
  223. * @param IOInterface $io
  224. * @param Config $config
  225. * @return Repository\RepositoryManager
  226. */
  227. protected function createRepositoryManager(IOInterface $io, Config $config)
  228. {
  229. $rm = new RepositoryManager($io, $config);
  230. $rm->setRepositoryClass('composer', 'Composer\Repository\ComposerRepository');
  231. $rm->setRepositoryClass('vcs', 'Composer\Repository\VcsRepository');
  232. $rm->setRepositoryClass('package', 'Composer\Repository\PackageRepository');
  233. $rm->setRepositoryClass('pear', 'Composer\Repository\PearRepository');
  234. $rm->setRepositoryClass('git', 'Composer\Repository\VcsRepository');
  235. $rm->setRepositoryClass('svn', 'Composer\Repository\VcsRepository');
  236. $rm->setRepositoryClass('hg', 'Composer\Repository\VcsRepository');
  237. return $rm;
  238. }
  239. /**
  240. * @param Repository\RepositoryManager $rm
  241. * @param string $vendorDir
  242. */
  243. protected function addLocalRepository(RepositoryManager $rm, $vendorDir)
  244. {
  245. $rm->setLocalRepository(new Repository\InstalledFilesystemRepository(new JsonFile($vendorDir.'/composer/installed.json')));
  246. $rm->setLocalDevRepository(new Repository\InstalledFilesystemRepository(new JsonFile($vendorDir.'/composer/installed_dev.json')));
  247. }
  248. /**
  249. * @param IO\IOInterface $io
  250. * @param Config $config
  251. * @return Downloader\DownloadManager
  252. */
  253. public function createDownloadManager(IOInterface $io, Config $config)
  254. {
  255. $cache = null;
  256. if ($config->get('cache-files-ttl') > 0) {
  257. $cache = new Cache($io, $config->get('cache-files-dir'), 'a-z0-9_./');
  258. }
  259. $dm = new Downloader\DownloadManager();
  260. $dm->setDownloader('git', new Downloader\GitDownloader($io, $config));
  261. $dm->setDownloader('svn', new Downloader\SvnDownloader($io, $config));
  262. $dm->setDownloader('hg', new Downloader\HgDownloader($io, $config));
  263. $dm->setDownloader('zip', new Downloader\ZipDownloader($io, $config, $cache));
  264. $dm->setDownloader('tar', new Downloader\TarDownloader($io, $config, $cache));
  265. $dm->setDownloader('phar', new Downloader\PharDownloader($io, $config, $cache));
  266. $dm->setDownloader('file', new Downloader\FileDownloader($io, $config, $cache));
  267. return $dm;
  268. }
  269. /**
  270. * @return Installer\InstallationManager
  271. */
  272. protected function createInstallationManager()
  273. {
  274. return new Installer\InstallationManager();
  275. }
  276. /**
  277. * @param Installer\InstallationManager $im
  278. * @param Composer $composer
  279. * @param IO\IOInterface $io
  280. */
  281. protected function createDefaultInstallers(Installer\InstallationManager $im, Composer $composer, IOInterface $io)
  282. {
  283. $im->addInstaller(new Installer\LibraryInstaller($io, $composer, null));
  284. $im->addInstaller(new Installer\PearInstaller($io, $composer, 'pear-library'));
  285. $im->addInstaller(new Installer\InstallerInstaller($io, $composer));
  286. $im->addInstaller(new Installer\MetapackageInstaller($io));
  287. }
  288. /**
  289. * @param Repository\RepositoryManager $rm
  290. * @param Installer\InstallationManager $im
  291. */
  292. protected function purgePackages(Repository\RepositoryManager $rm, Installer\InstallationManager $im)
  293. {
  294. foreach ($rm->getLocalRepositories() as $repo) {
  295. /* @var $repo Repository\WritableRepositoryInterface */
  296. foreach ($repo->getPackages() as $package) {
  297. if (!$im->isPackageInstalled($repo, $package)) {
  298. $repo->removePackage($package);
  299. }
  300. }
  301. }
  302. }
  303. /**
  304. * @param IOInterface $io IO instance
  305. * @param mixed $config either a configuration array or a filename to read from, if null it will read from
  306. * the default filename
  307. * @return Composer
  308. */
  309. public static function create(IOInterface $io, $config = null)
  310. {
  311. $factory = new static();
  312. return $factory->createComposer($io, $config);
  313. }
  314. }