AutoloadGenerator.php 12 KB

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