AutoloadGenerator.php 14 KB

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