PageRenderTime 52ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Composer/Factory.php

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