/src/Composer/Autoload/AutoloadGenerator.php

https://github.com/skug/composer · PHP · 343 lines · 237 code · 71 blank · 35 comment · 23 complexity · 439c166c40ed09ee4a3b4bdffccbdb35 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)
  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_namespace.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);
  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() && $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. $baseDirFromVendorDirCode = $filesystem->findShortestPathCode($vendorPath, getcwd(), true);
  75. $targetDirLoader = <<<EOF
  76. spl_autoload_register(function(\$class) {
  77. \$dir = $baseDirFromVendorDirCode . '/';
  78. \$prefixes = array($prefixes);
  79. foreach (\$prefixes as \$prefix) {
  80. if (0 !== strpos(\$class, \$prefix)) {
  81. continue;
  82. }
  83. \$path = \$dir . implode('/', array_slice(explode('\\\\', \$class), $levels)).'.php';
  84. if (!\$path = stream_resolve_include_path(\$path)) {
  85. return false;
  86. }
  87. require \$path;
  88. return true;
  89. }
  90. });
  91. EOF;
  92. }
  93. // flatten array
  94. $autoloads['classmap'] = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($autoloads['classmap']));
  95. foreach ($autoloads['classmap'] as $dir) {
  96. foreach (ClassMapGenerator::createMap($dir) as $class => $path) {
  97. $path = '/'.$filesystem->findShortestPath(getcwd(), $path, true);
  98. $classmapFile .= ' '.var_export($class, true).' => $baseDir . '.var_export($path, true).",\n";
  99. }
  100. }
  101. $classmapFile .= ");\n";
  102. $filesCode = "";
  103. $autoloads['files'] = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($autoloads['files']));
  104. foreach ($autoloads['files'] as $functionFile) {
  105. $filesCode .= ' require '.$this->getPathCode($filesystem, $relVendorPath, $vendorPath, $functionFile).";\n";
  106. }
  107. file_put_contents($targetDir.'/autoload_namespaces.php', $namespacesFile);
  108. file_put_contents($targetDir.'/autoload_classmap.php', $classmapFile);
  109. if ($includePathFile = $this->getIncludePathsFile($packageMap, $filesystem, $relVendorPath, $vendorPath, $vendorPathCode, $appBaseDirCode)) {
  110. file_put_contents($targetDir.'/include_paths.php', $includePathFile);
  111. }
  112. file_put_contents($vendorPath.'/autoload.php', $this->getAutoloadFile($vendorPathToTargetDirCode, true, true, (bool) $includePathFile, $targetDirLoader, $filesCode));
  113. copy(__DIR__.'/ClassLoader.php', $targetDir.'/ClassLoader.php');
  114. }
  115. public function buildPackageMap(InstallationManager $installationManager, PackageInterface $mainPackage, array $packages)
  116. {
  117. // build package => install path map
  118. $packageMap = array();
  119. // add main package
  120. $packageMap[] = array($mainPackage, '');
  121. foreach ($packages as $package) {
  122. if ($package instanceof AliasPackage) {
  123. continue;
  124. }
  125. $packageMap[] = array(
  126. $package,
  127. $installationManager->getInstallPath($package)
  128. );
  129. }
  130. return $packageMap;
  131. }
  132. /**
  133. * Compiles an ordered list of namespace => path mappings
  134. *
  135. * @param array $packageMap array of array(package, installDir-relative-to-composer.json)
  136. * @return array array('psr-0' => array('Ns\\Foo' => array('installDir')))
  137. */
  138. public function parseAutoloads(array $packageMap)
  139. {
  140. $autoloads = array('classmap' => array(), 'psr-0' => array(), 'files' => array());
  141. foreach ($packageMap as $item) {
  142. list($package, $installPath) = $item;
  143. if (null !== $package->getTargetDir()) {
  144. $installPath = substr($installPath, 0, -strlen('/'.$package->getTargetDir()));
  145. }
  146. foreach ($package->getAutoload() as $type => $mapping) {
  147. // skip misconfigured packages
  148. if (!is_array($mapping)) {
  149. continue;
  150. }
  151. foreach ($mapping as $namespace => $paths) {
  152. foreach ((array) $paths as $path) {
  153. $autoloads[$type][$namespace][] = empty($installPath) ? $path : $installPath.'/'.$path;
  154. }
  155. }
  156. }
  157. }
  158. foreach ($autoloads as $type => $maps) {
  159. krsort($autoloads[$type]);
  160. }
  161. return $autoloads;
  162. }
  163. /**
  164. * Registers an autoloader based on an autoload map returned by parseAutoloads
  165. *
  166. * @param array $autoloads see parseAutoloads return value
  167. * @return ClassLoader
  168. */
  169. public function createLoader(array $autoloads)
  170. {
  171. $loader = new ClassLoader();
  172. if (isset($autoloads['psr-0'])) {
  173. foreach ($autoloads['psr-0'] as $namespace => $path) {
  174. $loader->add($namespace, $path);
  175. }
  176. }
  177. return $loader;
  178. }
  179. protected function getIncludePathsFile(array $packageMap, Filesystem $filesystem, $relVendorPath, $vendorPath, $vendorPathCode, $appBaseDirCode)
  180. {
  181. $includePaths = array();
  182. foreach ($packageMap as $item) {
  183. list($package, $installPath) = $item;
  184. if (null !== $package->getTargetDir() && strlen($package->getTargetDir()) > 0) {
  185. $installPath = substr($installPath, 0, -strlen('/'.$package->getTargetDir()));
  186. }
  187. foreach ($package->getIncludePaths() as $includePath) {
  188. $includePath = trim($includePath, '/');
  189. $includePaths[] = empty($installPath) ? $includePath : $installPath.'/'.$includePath;
  190. }
  191. }
  192. if (!$includePaths) {
  193. return;
  194. }
  195. $includePathsFile = <<<EOF
  196. <?php
  197. // include_paths.php generated by Composer
  198. \$vendorDir = $vendorPathCode;
  199. \$baseDir = $appBaseDirCode;
  200. return array(
  201. EOF;
  202. foreach ($includePaths as $path) {
  203. $includePathsFile .= " " . $this->getPathCode($filesystem, $relVendorPath, $vendorPath, $path) . ",\n";
  204. }
  205. return $includePathsFile . ");\n";
  206. }
  207. protected function getPathCode(Filesystem $filesystem, $relVendorPath, $vendorPath, $path)
  208. {
  209. $path = strtr($path, '\\', '/');
  210. $baseDir = '';
  211. if (!$filesystem->isAbsolutePath($path)) {
  212. if (strpos($path, $relVendorPath) === 0) {
  213. // path starts with vendor dir
  214. $path = substr($path, strlen($relVendorPath));
  215. $baseDir = '$vendorDir . ';
  216. } else {
  217. $path = '/'.$path;
  218. $baseDir = '$baseDir . ';
  219. }
  220. } elseif (strpos($path, $vendorPath) === 0) {
  221. $path = substr($path, strlen($vendorPath));
  222. $baseDir = '$vendorDir . ';
  223. }
  224. return $baseDir.var_export($path, true);
  225. }
  226. protected function getAutoloadFile($vendorPathToTargetDirCode, $usePSR0, $useClassMap, $useIncludePath, $targetDirLoader, $filesCode)
  227. {
  228. if ($filesCode) {
  229. $filesCode = "\n".$filesCode;
  230. }
  231. $file = <<<HEADER
  232. <?php
  233. // autoload.php generated by Composer
  234. if (!class_exists('Composer\\\\Autoload\\\\ClassLoader', false)) {
  235. require $vendorPathToTargetDirCode . '/ClassLoader.php';
  236. }
  237. return call_user_func(function() {
  238. \$loader = new \\Composer\\Autoload\\ClassLoader();
  239. \$composerDir = $vendorPathToTargetDirCode;
  240. HEADER;
  241. if ($useIncludePath) {
  242. $file .= <<<'INCLUDE_PATH'
  243. $includePaths = require $composerDir . '/include_paths.php';
  244. array_push($includePaths, get_include_path());
  245. set_include_path(join(PATH_SEPARATOR, $includePaths));
  246. INCLUDE_PATH;
  247. }
  248. if ($usePSR0) {
  249. $file .= <<<'PSR0'
  250. $map = require $composerDir . '/autoload_namespaces.php';
  251. foreach ($map as $namespace => $path) {
  252. $loader->add($namespace, $path);
  253. }
  254. PSR0;
  255. }
  256. if ($useClassMap) {
  257. $file .= <<<'CLASSMAP'
  258. $classMap = require $composerDir . '/autoload_classmap.php';
  259. if ($classMap) {
  260. $loader->addClassMap($classMap);
  261. }
  262. CLASSMAP;
  263. }
  264. $file .= $targetDirLoader;
  265. return $file . <<<FOOTER
  266. \$loader->register();
  267. $filesCode
  268. return \$loader;
  269. });
  270. FOOTER;
  271. }
  272. }