AutoloadGenerator.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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\Installer\InstallationManager;
  13. use Composer\Json\JsonFile;
  14. use Composer\Package\Loader\JsonLoader;
  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(RepositoryInterface $localRepo, PackageInterface $mainPackage, InstallationManager $installationManager, $targetDir, $bcLinks = false)
  25. {
  26. $filesystem = new Filesystem();
  27. $filesystem->ensureDirectoryExists($installationManager->getVendorPath());
  28. $filesystem->ensureDirectoryExists($targetDir);
  29. $vendorPath = strtr(realpath($installationManager->getVendorPath()), '\\', '/');
  30. $relVendorPath = $filesystem->findShortestPath(getcwd(), $vendorPath, true);
  31. $vendorDirCode = $filesystem->findShortestPathCode(realpath($targetDir), $vendorPath, true);
  32. $appBaseDirCode = $filesystem->findShortestPathCode($vendorPath, getcwd(), true);
  33. $appBaseDirCode = str_replace('__DIR__', '$vendorDir', $appBaseDirCode);
  34. $namespacesFile = <<<EOF
  35. <?php
  36. // autoload_namespace.php generated by Composer
  37. \$vendorDir = $vendorDirCode;
  38. \$baseDir = $appBaseDirCode;
  39. return array(
  40. EOF;
  41. $packageMap = $this->buildPackageMap($installationManager, $mainPackage, $localRepo->getPackages());
  42. $autoloads = $this->parseAutoloads($packageMap);
  43. foreach ($autoloads['psr-0'] as $namespace => $paths) {
  44. $exportedPaths = array();
  45. foreach ($paths as $path) {
  46. $exportedPaths[] = $this->getPathCode($filesystem, $relVendorPath, $vendorPath, $path);
  47. }
  48. $exportedPrefix = var_export($namespace, true);
  49. $namespacesFile .= " $exportedPrefix => ";
  50. if (count($exportedPaths) > 1) {
  51. $namespacesFile .= "array(".implode(', ', $exportedPaths)."),\n";
  52. } else {
  53. $namespacesFile .= $exportedPaths[0].",\n";
  54. }
  55. }
  56. $namespacesFile .= ");\n";
  57. $classmapFile = <<<EOF
  58. <?php
  59. // autoload_classmap.php generated by Composer
  60. \$vendorDir = $vendorDirCode;
  61. \$baseDir = $appBaseDirCode;
  62. return array(
  63. EOF;
  64. // add custom psr-0 autoloading if the root package has a target dir
  65. $targetDirLoader = null;
  66. $mainAutoload = $mainPackage->getAutoload();
  67. if ($mainPackage->getTargetDir() && $mainAutoload['psr-0']) {
  68. $levels = count(explode('/', trim(strtr($mainPackage->getTargetDir(), '\\', '/'), '/')));
  69. $prefixes = implode(', ', array_map(function ($prefix) {
  70. return var_export($prefix, true);
  71. }, array_keys($mainAutoload['psr-0'])));
  72. $baseDirFromTargetDirCode = $filesystem->findShortestPathCode(realpath($targetDir), getcwd(), true);
  73. $targetDirLoader = <<<EOF
  74. spl_autoload_register(function(\$class) {
  75. \$prefixes = array($prefixes);
  76. foreach (\$prefixes as \$prefix) {
  77. if (0 !== strpos(\$class, \$prefix)) {
  78. continue;
  79. }
  80. \$path = $baseDirFromTargetDirCode . '/' . implode('/', array_slice(explode('\\\\', \$class), $levels)).'.php';
  81. if (!stream_resolve_include_path(\$path)) {
  82. return false;
  83. }
  84. require_once \$path;
  85. return true;
  86. }
  87. });
  88. EOF;
  89. }
  90. // flatten array
  91. $autoloads['classmap'] = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($autoloads['classmap']));
  92. foreach ($autoloads['classmap'] as $dir) {
  93. foreach (ClassMapGenerator::createMap($dir) as $class => $path) {
  94. $path = '/'.$filesystem->findShortestPath(getcwd(), $path, true);
  95. $classmapFile .= ' '.var_export($class, true).' => $baseDir . '.var_export($path, true).",\n";
  96. }
  97. }
  98. $classmapFile .= ");\n";
  99. file_put_contents($targetDir.'/autoload_namespaces.php', $namespacesFile);
  100. file_put_contents($targetDir.'/autoload_classmap.php', $classmapFile);
  101. if ($includePathFile = $this->getIncludePathsFile($packageMap, $filesystem, $relVendorPath, $vendorPath, $vendorDirCode, $appBaseDirCode)) {
  102. file_put_contents($targetDir.'/include_paths.php', $includePathFile);
  103. }
  104. file_put_contents($targetDir.'/autoload.php', $this->getAutoloadFile(true, true, (Boolean) $includePathFile, $targetDirLoader));
  105. copy(__DIR__.'/ClassLoader.php', $targetDir.'/ClassLoader.php');
  106. // TODO BC feature, add E_DEPRECATED in autoload.php on April 30th, remove after May 30th
  107. if ($bcLinks) {
  108. file_put_contents($targetDir.'/.composer/autoload_namespaces.php', "<?php\n// Deprecated file, use the one in root of vendor dir\nreturn include dirname(__DIR__).'/autoload_namespaces.php';\n");
  109. file_put_contents($targetDir.'/.composer/autoload_classmap.php', "<?php\n// Deprecated file, use the one in root of vendor dir\nreturn include dirname(__DIR__).'/autoload_classmap.php';\n");
  110. file_put_contents($targetDir.'/.composer/autoload.php', "<?php\n// Deprecated file, use the one in root of vendor dir\nreturn include dirname(__DIR__).'/autoload.php';\n");
  111. file_put_contents($targetDir.'/.composer/ClassLoader.php', "<?php\n// Deprecated file, use the one in root of vendor dir\nreturn include dirname(__DIR__).'/ClassLoader.php';\n");
  112. if ($includePathFile) {
  113. file_put_contents($targetDir.'/.composer/include_paths.php', "<?php\n// Deprecated file, use the one in root of vendor dir\nreturn include dirname(__DIR__).'/include_paths.php';\n");
  114. }
  115. }
  116. }
  117. public function buildPackageMap(InstallationManager $installationManager, PackageInterface $mainPackage, array $packages)
  118. {
  119. // build package => install path map
  120. $packageMap = array();
  121. // add main package
  122. $packageMap[] = array($mainPackage, '');
  123. foreach ($packages as $package) {
  124. $packageMap[] = array(
  125. $package,
  126. $installationManager->getInstallPath($package)
  127. );
  128. }
  129. return $packageMap;
  130. }
  131. /**
  132. * Compiles an ordered list of namespace => path mappings
  133. *
  134. * @param array $packageMap array of array(package, installDir-relative-to-composer.json)
  135. * @return array array('psr-0' => array('Ns\\Foo' => array('installDir')))
  136. */
  137. public function parseAutoloads(array $packageMap)
  138. {
  139. $autoloads = array('classmap' => array(), 'psr-0' => array());
  140. foreach ($packageMap as $item) {
  141. list($package, $installPath) = $item;
  142. if (null !== $package->getTargetDir()) {
  143. $installPath = substr($installPath, 0, -strlen('/'.$package->getTargetDir()));
  144. }
  145. foreach ($package->getAutoload() as $type => $mapping) {
  146. // skip misconfigured packages
  147. if (!is_array($mapping)) {
  148. continue;
  149. }
  150. foreach ($mapping as $namespace => $paths) {
  151. foreach ((array) $paths as $path) {
  152. $autoloads[$type][$namespace][] = empty($installPath) ? $path : $installPath.'/'.$path;
  153. }
  154. }
  155. }
  156. }
  157. foreach ($autoloads as $type => $maps) {
  158. krsort($autoloads[$type]);
  159. }
  160. return $autoloads;
  161. }
  162. /**
  163. * Registers an autoloader based on an autoload map returned by parseAutoloads
  164. *
  165. * @param array $autoloads see parseAutoloads return value
  166. * @return ClassLoader
  167. */
  168. public function createLoader(array $autoloads)
  169. {
  170. $loader = new ClassLoader();
  171. if (isset($autoloads['psr-0'])) {
  172. foreach ($autoloads['psr-0'] as $namespace => $path) {
  173. $loader->add($namespace, $path);
  174. }
  175. }
  176. return $loader;
  177. }
  178. protected function getIncludePathsFile(array $packageMap, Filesystem $filesystem, $relVendorPath, $vendorPath, $vendorDirCode, $appBaseDirCode)
  179. {
  180. $includePaths = array();
  181. foreach ($packageMap as $item) {
  182. list($package, $installPath) = $item;
  183. if (null !== $package->getTargetDir()) {
  184. $installPath = substr($installPath, 0, -strlen('/'.$package->getTargetDir()));
  185. }
  186. foreach ($package->getIncludePaths() as $includePath) {
  187. $includePath = trim($includePath, '/');
  188. $includePaths[] = empty($installPath) ? $includePath : $installPath.'/'.$includePath;
  189. }
  190. }
  191. if (!$includePaths) {
  192. return;
  193. }
  194. $includePathsFile = <<<EOF
  195. <?php
  196. // include_paths.php generated by Composer
  197. \$vendorDir = $vendorDirCode;
  198. \$baseDir = $appBaseDirCode;
  199. return array(
  200. EOF;
  201. foreach ($includePaths as $path) {
  202. $includePathsFile .= " " . $this->getPathCode($filesystem, $relVendorPath, $vendorPath, $path) . ",\n";
  203. }
  204. return $includePathsFile . ");\n";
  205. }
  206. protected function getPathCode(Filesystem $filesystem, $relVendorPath, $vendorPath, $path)
  207. {
  208. $path = strtr($path, '\\', '/');
  209. $baseDir = '';
  210. if (!$filesystem->isAbsolutePath($path)) {
  211. if (strpos($path, $relVendorPath) === 0) {
  212. // path starts with vendor dir
  213. $path = substr($path, strlen($relVendorPath));
  214. $baseDir = '$vendorDir . ';
  215. } else {
  216. $path = '/'.$path;
  217. $baseDir = '$baseDir . ';
  218. }
  219. } elseif (strpos($path, $vendorPath) === 0) {
  220. $path = substr($path, strlen($vendorPath));
  221. $baseDir = '$vendorDir . ';
  222. }
  223. return $baseDir.var_export($path, true);
  224. }
  225. protected function getAutoloadFile($usePSR0, $useClassMap, $useIncludePath, $targetDirLoader)
  226. {
  227. $file = <<<'HEADER'
  228. <?php
  229. // autoload.php generated by Composer
  230. if (!class_exists('Composer\\Autoload\\ClassLoader', false)) {
  231. require __DIR__.'/ClassLoader.php';
  232. }
  233. return call_user_func(function() {
  234. $loader = new \Composer\Autoload\ClassLoader();
  235. HEADER;
  236. if ($useIncludePath) {
  237. $file .= <<<'INCLUDE_PATH'
  238. $includePaths = require __DIR__.'/include_paths.php';
  239. array_unshift($includePaths, get_include_path());
  240. set_include_path(join(PATH_SEPARATOR, $includePaths));
  241. INCLUDE_PATH;
  242. }
  243. if ($usePSR0) {
  244. $file .= <<<'PSR0'
  245. $map = require __DIR__.'/autoload_namespaces.php';
  246. foreach ($map as $namespace => $path) {
  247. $loader->add($namespace, $path);
  248. }
  249. PSR0;
  250. }
  251. if ($useClassMap) {
  252. $file .= <<<'CLASSMAP'
  253. $classMap = require __DIR__.'/autoload_classmap.php';
  254. if ($classMap) {
  255. $loader->addClassMap($classMap);
  256. }
  257. CLASSMAP;
  258. }
  259. $file .= $targetDirLoader;
  260. return $file . <<<'FOOTER'
  261. $loader->register();
  262. return $loader;
  263. });
  264. FOOTER;
  265. }
  266. }