AutoloadGenerator.php 11 KB

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