PageRenderTime 46ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/src/Composer/Autoload/AutoloadGenerator.php

https://github.com/theshadow/composer
PHP | 510 lines | 435 code | 46 blank | 29 comment | 17 complexity | 8a4975f7811c214fbfee97d858ab9023 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\Autoload;
  12. use Composer\Config;
  13. use Composer\Installer\InstallationManager;
  14. use Composer\Package\AliasPackage;
  15. use Composer\Package\PackageInterface;
  16. use Composer\Repository\RepositoryInterface;
  17. use Composer\Util\Filesystem;
  18. /**
  19. * @author Igor Wiedler <igor@wiedler.ch>
  20. * @author Jordi Boggiano <j.boggiano@seld.be>
  21. */
  22. class AutoloadGenerator
  23. {
  24. public function dump(Config $config, RepositoryInterface $localRepo, PackageInterface $mainPackage, InstallationManager $installationManager, $targetDir, $scanPsr0Packages = false, $suffix = '')
  25. {
  26. $filesystem = new Filesystem();
  27. $filesystem->ensureDirectoryExists($config->get('vendor-dir'));
  28. $vendorPath = strtr(realpath($config->get('vendor-dir')), '\\', '/');
  29. $targetDir = $vendorPath.'/'.$targetDir;
  30. $filesystem->ensureDirectoryExists($targetDir);
  31. $relVendorPath = $filesystem->findShortestPath(getcwd(), $vendorPath, true);
  32. $vendorPathCode = $filesystem->findShortestPathCode(realpath($targetDir), $vendorPath, true);
  33. $vendorPathToTargetDirCode = $filesystem->findShortestPathCode($vendorPath, realpath($targetDir), true);
  34. $appBaseDirCode = $filesystem->findShortestPathCode($vendorPath, getcwd(), true);
  35. $appBaseDirCode = str_replace('__DIR__', '$vendorDir', $appBaseDirCode);
  36. $namespacesFile = <<<EOF
  37. <?php
  38. // autoload_namespaces.php generated by Composer
  39. \$vendorDir = $vendorPathCode;
  40. \$baseDir = $appBaseDirCode;
  41. return array(
  42. EOF;
  43. $packageMap = $this->buildPackageMap($installationManager, $mainPackage, $localRepo->getPackages());
  44. $autoloads = $this->parseAutoloads($packageMap, $mainPackage);
  45. foreach ($autoloads['psr-0'] as $namespace => $paths) {
  46. $exportedPaths = array();
  47. foreach ($paths as $path) {
  48. $exportedPaths[] = $this->getPathCode($filesystem, $relVendorPath, $vendorPath, $path);
  49. }
  50. $exportedPrefix = var_export($namespace, true);
  51. $namespacesFile .= " $exportedPrefix => ";
  52. if (count($exportedPaths) > 1) {
  53. $namespacesFile .= "array(".implode(', ', $exportedPaths)."),\n";
  54. } else {
  55. $namespacesFile .= $exportedPaths[0].",\n";
  56. }
  57. }
  58. $namespacesFile .= ");\n";
  59. $classmapFile = <<<EOF
  60. <?php
  61. // autoload_classmap.php generated by Composer
  62. \$vendorDir = $vendorPathCode;
  63. \$baseDir = $appBaseDirCode;
  64. return array(
  65. EOF;
  66. // add custom psr-0 autoloading if the root package has a target dir
  67. $targetDirLoader = null;
  68. $mainAutoload = $mainPackage->getAutoload();
  69. if ($mainPackage->getTargetDir() && !empty($mainAutoload['psr-0'])) {
  70. $levels = count(explode('/', trim(strtr($mainPackage->getTargetDir(), '\\', '/'), '/')));
  71. $prefixes = implode(', ', array_map(function ($prefix) {
  72. return var_export($prefix, true);
  73. }, array_keys($mainAutoload['psr-0'])));
  74. $baseDirFromTargetDirCode = $filesystem->findShortestPathCode($targetDir, getcwd(), true);
  75. $targetDirLoader = <<<EOF
  76. public static function autoload(\$class)
  77. {
  78. \$dir = $baseDirFromTargetDirCode . '/';
  79. \$prefixes = array($prefixes);
  80. foreach (\$prefixes as \$prefix) {
  81. if (0 !== strpos(\$class, \$prefix)) {
  82. continue;
  83. }
  84. \$path = \$dir . implode('/', array_slice(explode('\\\\', \$class), $levels)).'.php';
  85. if (!\$path = stream_resolve_include_path(\$path)) {
  86. return false;
  87. }
  88. require \$path;
  89. return true;
  90. }
  91. }
  92. EOF;
  93. }
  94. // flatten array
  95. $classMap = array();
  96. if ($scanPsr0Packages) {
  97. foreach ($autoloads['psr-0'] as $namespace => $paths) {
  98. foreach ($paths as $dir) {
  99. $dir = $this->getPath($filesystem, $relVendorPath, $vendorPath, $dir);
  100. $whitelist = sprintf(
  101. '{%s/%s.+(?<!(?<!/)Test\.php)$}',
  102. preg_quote(rtrim($dir, '/')),
  103. strpos($namespace, '_') === false ? preg_quote(strtr($namespace, '\\', '/')) : ''
  104. );
  105. if (!is_dir($dir)) {
  106. continue;
  107. }
  108. foreach (ClassMapGenerator::createMap($dir, $whitelist) as $class => $path) {
  109. if ('' === $namespace || 0 === strpos($class, $namespace)) {
  110. $path = '/'.$filesystem->findShortestPath(getcwd(), $path, true);
  111. if (!isset($classMap[$class])) {
  112. $classMap[$class] = '$baseDir . '.var_export($path, true).",\n";
  113. }
  114. }
  115. }
  116. }
  117. }
  118. }
  119. $autoloads['classmap'] = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($autoloads['classmap']));
  120. foreach ($autoloads['classmap'] as $dir) {
  121. foreach (ClassMapGenerator::createMap($dir) as $class => $path) {
  122. $path = '/'.$filesystem->findShortestPath(getcwd(), $path, true);
  123. $classMap[$class] = '$baseDir . '.var_export($path, true).",\n";
  124. }
  125. }
  126. ksort($classMap);
  127. foreach ($classMap as $class => $code) {
  128. $classmapFile .= ' '.var_export($class, true).' => '.$code;
  129. }
  130. $classmapFile .= ");\n";
  131. $filesCode = "";
  132. $autoloads['files'] = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($autoloads['files']));
  133. foreach ($autoloads['files'] as $functionFile) {
  134. $filesCode .= ' require '.$this->getPathCode($filesystem, $relVendorPath, $vendorPath, $functionFile).";\n";
  135. }
  136. if (!$suffix) {
  137. $suffix = md5(uniqid('', true));
  138. }
  139. file_put_contents($targetDir.'/autoload_namespaces.php', $namespacesFile);
  140. file_put_contents($targetDir.'/autoload_classmap.php', $classmapFile);
  141. if ($includePathFile = $this->getIncludePathsFile($packageMap, $filesystem, $relVendorPath, $vendorPath, $vendorPathCode, $appBaseDirCode)) {
  142. file_put_contents($targetDir.'/include_paths.php', $includePathFile);
  143. }
  144. file_put_contents($vendorPath.'/autoload.php', $this->getAutoloadFile($vendorPathToTargetDirCode, $suffix));
  145. file_put_contents($targetDir.'/autoload_real.php', $this->getAutoloadRealFile(true, true, (bool) $includePathFile, $targetDirLoader, $filesCode, $vendorPathCode, $appBaseDirCode, $suffix));
  146. copy(__DIR__.'/ClassLoader.php', $targetDir.'/ClassLoader.php');
  147. }
  148. public function buildPackageMap(InstallationManager $installationManager, PackageInterface $mainPackage, array $packages)
  149. {
  150. // build package => install path map
  151. $packageMap = array(array($mainPackage, ''));
  152. foreach ($packages as $package) {
  153. if ($package instanceof AliasPackage) {
  154. continue;
  155. }
  156. $packageMap[] = array(
  157. $package,
  158. $installationManager->getInstallPath($package)
  159. );
  160. }
  161. return $packageMap;
  162. }
  163. /**
  164. * Compiles an ordered list of namespace => path mappings
  165. *
  166. * @param array $packageMap array of array(package, installDir-relative-to-composer.json)
  167. * @param PackageInterface $mainPackage root package instance
  168. * @return array array('psr-0' => array('Ns\\Foo' => array('installDir')))
  169. */
  170. public function parseAutoloads(array $packageMap, PackageInterface $mainPackage)
  171. {
  172. $mainPackageMap = array_shift($packageMap);
  173. $sortedPackageMap = $this->sortPackageMap($packageMap);
  174. $sortedPackageMap[] = $mainPackageMap;
  175. array_unshift($packageMap, $mainPackageMap);
  176. $psr0 = $this->parseAutoloadsType($packageMap, 'psr-0', $mainPackage);
  177. $classmap = $this->parseAutoloadsType($sortedPackageMap, 'classmap', $mainPackage);
  178. $files = $this->parseAutoloadsType($sortedPackageMap, 'files', $mainPackage);
  179. krsort($psr0);
  180. return array('psr-0' => $psr0, 'classmap' => $classmap, 'files' => $files);
  181. }
  182. /**
  183. * Registers an autoloader based on an autoload map returned by parseAutoloads
  184. *
  185. * @param array $autoloads see parseAutoloads return value
  186. * @return ClassLoader
  187. */
  188. public function createLoader(array $autoloads)
  189. {
  190. $loader = new ClassLoader();
  191. if (isset($autoloads['psr-0'])) {
  192. foreach ($autoloads['psr-0'] as $namespace => $path) {
  193. $loader->add($namespace, $path);
  194. }
  195. }
  196. return $loader;
  197. }
  198. protected function getIncludePathsFile(array $packageMap, Filesystem $filesystem, $relVendorPath, $vendorPath, $vendorPathCode, $appBaseDirCode)
  199. {
  200. $includePaths = array();
  201. foreach ($packageMap as $item) {
  202. list($package, $installPath) = $item;
  203. if (null !== $package->getTargetDir() && strlen($package->getTargetDir()) > 0) {
  204. $installPath = substr($installPath, 0, -strlen('/'.$package->getTargetDir()));
  205. }
  206. foreach ($package->getIncludePaths() as $includePath) {
  207. $includePath = trim($includePath, '/');
  208. $includePaths[] = empty($installPath) ? $includePath : $installPath.'/'.$includePath;
  209. }
  210. }
  211. if (!$includePaths) {
  212. return;
  213. }
  214. $includePathsFile = <<<EOF
  215. <?php
  216. // include_paths.php generated by Composer
  217. \$vendorDir = $vendorPathCode;
  218. \$baseDir = $appBaseDirCode;
  219. return array(
  220. EOF;
  221. foreach ($includePaths as $path) {
  222. $includePathsFile .= " " . $this->getPathCode($filesystem, $relVendorPath, $vendorPath, $path) . ",\n";
  223. }
  224. return $includePathsFile . ");\n";
  225. }
  226. protected function getPathCode(Filesystem $filesystem, $relVendorPath, $vendorPath, $path)
  227. {
  228. $path = strtr($path, '\\', '/');
  229. $baseDir = '';
  230. if (!$filesystem->isAbsolutePath($path)) {
  231. if (strpos($path, $relVendorPath) === 0) {
  232. // path starts with vendor dir
  233. $path = substr($path, strlen($relVendorPath));
  234. $baseDir = '$vendorDir . ';
  235. } else {
  236. $path = '/'.$path;
  237. $baseDir = '$baseDir . ';
  238. }
  239. } elseif (strpos($path, $vendorPath) === 0) {
  240. $path = substr($path, strlen($vendorPath));
  241. $baseDir = '$vendorDir . ';
  242. }
  243. return $baseDir.var_export($path, true);
  244. }
  245. protected function getPath(Filesystem $filesystem, $relVendorPath, $vendorPath, $path)
  246. {
  247. $path = strtr($path, '\\', '/');
  248. if (!$filesystem->isAbsolutePath($path)) {
  249. if (strpos($path, $relVendorPath) === 0) {
  250. // path starts with vendor dir
  251. return $vendorPath . substr($path, strlen($relVendorPath));
  252. }
  253. return strtr(getcwd(), '\\', '/').'/'.$path;
  254. }
  255. return $path;
  256. }
  257. protected function getAutoloadFile($vendorPathToTargetDirCode, $suffix)
  258. {
  259. return <<<AUTOLOAD
  260. <?php
  261. // autoload.php generated by Composer
  262. require_once $vendorPathToTargetDirCode . '/autoload_real.php';
  263. return ComposerAutoloaderInit$suffix::getLoader();
  264. AUTOLOAD;
  265. }
  266. protected function getAutoloadRealFile($usePSR0, $useClassMap, $useIncludePath, $targetDirLoader, $filesCode, $vendorPathCode, $appBaseDirCode, $suffix)
  267. {
  268. // TODO the class ComposerAutoloaderInit should be revert to a closure
  269. // when APC has been fixed:
  270. // - https://github.com/composer/composer/issues/959
  271. // - https://bugs.php.net/bug.php?id=52144
  272. // - https://bugs.php.net/bug.php?id=61576
  273. // - https://bugs.php.net/bug.php?id=59298
  274. if ($filesCode) {
  275. $filesCode = "\n\n".rtrim($filesCode);
  276. }
  277. $file = <<<HEADER
  278. <?php
  279. // autoload_real.php generated by Composer
  280. class ComposerAutoloaderInit$suffix
  281. {
  282. private static \$loader;
  283. public static function loadClassLoader(\$class)
  284. {
  285. if ('Composer\\Autoload\\ClassLoader' === \$class) {
  286. require __DIR__ . '/ClassLoader.php';
  287. }
  288. }
  289. public static function getLoader()
  290. {
  291. if (null !== self::\$loader) {
  292. return self::\$loader;
  293. }
  294. spl_autoload_register(array('ComposerAutoloaderInit$suffix', 'loadClassLoader'));
  295. self::\$loader = \$loader = new \\Composer\\Autoload\\ClassLoader();
  296. spl_autoload_unregister(array('ComposerAutoloaderInit$suffix', 'loadClassLoader'));
  297. \$vendorDir = $vendorPathCode;
  298. \$baseDir = $appBaseDirCode;
  299. HEADER;
  300. if ($useIncludePath) {
  301. $file .= <<<'INCLUDE_PATH'
  302. $includePaths = require __DIR__ . '/include_paths.php';
  303. array_push($includePaths, get_include_path());
  304. set_include_path(join(PATH_SEPARATOR, $includePaths));
  305. INCLUDE_PATH;
  306. }
  307. if ($usePSR0) {
  308. $file .= <<<'PSR0'
  309. $map = require __DIR__ . '/autoload_namespaces.php';
  310. foreach ($map as $namespace => $path) {
  311. $loader->add($namespace, $path);
  312. }
  313. PSR0;
  314. }
  315. if ($useClassMap) {
  316. $file .= <<<'CLASSMAP'
  317. $classMap = require __DIR__ . '/autoload_classmap.php';
  318. if ($classMap) {
  319. $loader->addClassMap($classMap);
  320. }
  321. CLASSMAP;
  322. }
  323. if ($targetDirLoader) {
  324. $file .= <<<REGISTER_AUTOLOAD
  325. spl_autoload_register(array('ComposerAutoloaderInit$suffix', 'autoload'), true, true);
  326. REGISTER_AUTOLOAD;
  327. }
  328. $file .= <<<METHOD_FOOTER
  329. \$loader->register(true);{$filesCode}
  330. return \$loader;
  331. }
  332. METHOD_FOOTER;
  333. $file .= $targetDirLoader;
  334. return $file . <<<FOOTER
  335. }
  336. FOOTER;
  337. }
  338. protected function parseAutoloadsType(array $packageMap, $type, PackageInterface $mainPackage)
  339. {
  340. $autoloads = array();
  341. foreach ($packageMap as $item) {
  342. list($package, $installPath) = $item;
  343. $autoload = $package->getAutoload();
  344. // skip misconfigured packages
  345. if (!isset($autoload[$type]) || !is_array($autoload[$type])) {
  346. continue;
  347. }
  348. if (null !== $package->getTargetDir() && $package !== $mainPackage) {
  349. $installPath = substr($installPath, 0, -strlen('/'.$package->getTargetDir()));
  350. }
  351. foreach ($autoload[$type] as $namespace => $paths) {
  352. foreach ((array) $paths as $path) {
  353. // remove target-dir from classmap entries of the root package
  354. if ($type === 'classmap' && $package === $mainPackage && $package->getTargetDir()) {
  355. $targetDir = str_replace('\\<dirsep\\>', '[\\\\/]', preg_quote(str_replace(array('/', '\\'), '<dirsep>', $package->getTargetDir())));
  356. $path = ltrim(preg_replace('{^'.$targetDir.'}', '', ltrim($path, '\\/')), '\\/');
  357. }
  358. $autoloads[$namespace][] = empty($installPath) ? $path : $installPath.'/'.$path;
  359. }
  360. }
  361. }
  362. return $autoloads;
  363. }
  364. protected function sortPackageMap(array $packageMap)
  365. {
  366. $positions = array();
  367. $names = array();
  368. $indexes = array();
  369. foreach ($packageMap as $position => $item) {
  370. $mainName = $item[0]->getName();
  371. $names = array_merge(array_fill_keys($item[0]->getNames(), $mainName), $names);
  372. $names[$mainName] = $mainName;
  373. $indexes[$mainName] = $positions[$mainName] = $position;
  374. }
  375. foreach ($packageMap as $item) {
  376. $position = $positions[$item[0]->getName()];
  377. foreach (array_merge($item[0]->getRequires(), $item[0]->getDevRequires()) as $link) {
  378. $target = $link->getTarget();
  379. if (!isset($names[$target])) {
  380. continue;
  381. }
  382. $target = $names[$target];
  383. if ($positions[$target] <= $position) {
  384. continue;
  385. }
  386. foreach ($positions as $key => $value) {
  387. if ($value >= $position) {
  388. break;
  389. }
  390. $positions[$key]--;
  391. }
  392. $positions[$target] = $position - 1;
  393. }
  394. asort($positions);
  395. }
  396. $sortedPackageMap = array();
  397. foreach (array_keys($positions) as $packageName) {
  398. $sortedPackageMap[] = $packageMap[$indexes[$packageName]];
  399. }
  400. return $sortedPackageMap;
  401. }
  402. }