AutoloadGenerator.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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. use Composer\Script\EventDispatcher;
  19. use Composer\Script\ScriptEvents;
  20. /**
  21. * @author Igor Wiedler <igor@wiedler.ch>
  22. * @author Jordi Boggiano <j.boggiano@seld.be>
  23. */
  24. class AutoloadGenerator
  25. {
  26. /**
  27. * @var EventDispatcher
  28. */
  29. private $eventDispatcher;
  30. public function __construct(EventDispatcher $eventDispatcher)
  31. {
  32. $this->eventDispatcher = $eventDispatcher;
  33. }
  34. public function dump(Config $config, RepositoryInterface $localRepo, PackageInterface $mainPackage, InstallationManager $installationManager, $targetDir, $scanPsr0Packages = false, $suffix = '')
  35. {
  36. $filesystem = new Filesystem();
  37. $filesystem->ensureDirectoryExists($config->get('vendor-dir'));
  38. $basePath = $filesystem->normalizePath(getcwd());
  39. $vendorPath = $filesystem->normalizePath(realpath($config->get('vendor-dir')));
  40. $useGlobalIncludePath = (bool) $config->get('use-include-path');
  41. $targetDir = $vendorPath.'/'.$targetDir;
  42. $filesystem->ensureDirectoryExists($targetDir);
  43. $relVendorPath = $filesystem->findShortestPath($basePath, $vendorPath, true);
  44. $vendorPathCode = $filesystem->findShortestPathCode(realpath($targetDir), $vendorPath, true);
  45. $vendorPathCode52 = str_replace('__DIR__', 'dirname(__FILE__)', $vendorPathCode);
  46. $vendorPathToTargetDirCode = $filesystem->findShortestPathCode($vendorPath, realpath($targetDir), true);
  47. $appBaseDirCode = $filesystem->findShortestPathCode($vendorPath, $basePath, true);
  48. $appBaseDirCode = str_replace('__DIR__', '$vendorDir', $appBaseDirCode);
  49. $namespacesFile = <<<EOF
  50. <?php
  51. // autoload_namespaces.php generated by Composer
  52. \$vendorDir = $vendorPathCode52;
  53. \$baseDir = $appBaseDirCode;
  54. return array(
  55. EOF;
  56. $packageMap = $this->buildPackageMap($installationManager, $mainPackage, $localRepo->getPackages());
  57. $autoloads = $this->parseAutoloads($packageMap, $mainPackage);
  58. foreach ($autoloads['psr-0'] as $namespace => $paths) {
  59. $exportedPaths = array();
  60. foreach ($paths as $path) {
  61. $exportedPaths[] = $this->getPathCode($filesystem, $basePath, $relVendorPath, $vendorPath, $path);
  62. }
  63. $exportedPrefix = var_export($namespace, true);
  64. $namespacesFile .= " $exportedPrefix => ";
  65. if (count($exportedPaths) > 1) {
  66. $namespacesFile .= "array(".implode(', ', $exportedPaths)."),\n";
  67. } else {
  68. $namespacesFile .= $exportedPaths[0].",\n";
  69. }
  70. }
  71. $namespacesFile .= ");\n";
  72. $classmapFile = <<<EOF
  73. <?php
  74. // autoload_classmap.php generated by Composer
  75. \$vendorDir = $vendorPathCode52;
  76. \$baseDir = $appBaseDirCode;
  77. return array(
  78. EOF;
  79. // add custom psr-0 autoloading if the root package has a target dir
  80. $targetDirLoader = null;
  81. $mainAutoload = $mainPackage->getAutoload();
  82. if ($mainPackage->getTargetDir() && !empty($mainAutoload['psr-0'])) {
  83. $levels = count(explode('/', $filesystem->normalizePath($mainPackage->getTargetDir())));
  84. $prefixes = implode(', ', array_map(function ($prefix) {
  85. return var_export($prefix, true);
  86. }, array_keys($mainAutoload['psr-0'])));
  87. $baseDirFromTargetDirCode = $filesystem->findShortestPathCode($targetDir, $basePath, true);
  88. $targetDirLoader = <<<EOF
  89. public static function autoload(\$class)
  90. {
  91. \$dir = $baseDirFromTargetDirCode . '/';
  92. \$prefixes = array($prefixes);
  93. foreach (\$prefixes as \$prefix) {
  94. if (0 !== strpos(\$class, \$prefix)) {
  95. continue;
  96. }
  97. \$path = \$dir . implode('/', array_slice(explode('\\\\', \$class), $levels)).'.php';
  98. if (!\$path = stream_resolve_include_path(\$path)) {
  99. return false;
  100. }
  101. require \$path;
  102. return true;
  103. }
  104. }
  105. EOF;
  106. }
  107. // flatten array
  108. $classMap = array();
  109. if ($scanPsr0Packages) {
  110. foreach ($autoloads['psr-0'] as $namespace => $paths) {
  111. foreach ($paths as $dir) {
  112. $dir = $this->getPath($filesystem, $basePath, $relVendorPath, $vendorPath, $dir);
  113. $whitelist = sprintf(
  114. '{%s/%s.+(?<!(?<!/)Test\.php)$}',
  115. preg_quote(rtrim($dir, '/')),
  116. strpos($namespace, '_') === false ? preg_quote(strtr($namespace, '\\', '/')) : ''
  117. );
  118. if (!is_dir($dir)) {
  119. continue;
  120. }
  121. foreach (ClassMapGenerator::createMap($dir, $whitelist) as $class => $path) {
  122. if ('' === $namespace || 0 === strpos($class, $namespace)) {
  123. if (!isset($classMap[$class])) {
  124. $path = $this->getPathCode($filesystem, $basePath, $relVendorPath, $vendorPath, $path);
  125. $classMap[$class] = $path.",\n";
  126. }
  127. }
  128. }
  129. }
  130. }
  131. }
  132. $autoloads['classmap'] = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($autoloads['classmap']));
  133. foreach ($autoloads['classmap'] as $dir) {
  134. foreach (ClassMapGenerator::createMap($dir) as $class => $path) {
  135. $path = $this->getPathCode($filesystem, $basePath, $relVendorPath, $vendorPath, $path);
  136. $classMap[$class] = $path.",\n";
  137. }
  138. }
  139. ksort($classMap);
  140. foreach ($classMap as $class => $code) {
  141. $classmapFile .= ' '.var_export($class, true).' => '.$code;
  142. }
  143. $classmapFile .= ");\n";
  144. $filesCode = "";
  145. $autoloads['files'] = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($autoloads['files']));
  146. foreach ($autoloads['files'] as $functionFile) {
  147. $filesCode .= ' require '.$this->getPathCode($filesystem, $basePath, $relVendorPath, $vendorPath, $functionFile).";\n";
  148. }
  149. if (!$suffix) {
  150. $suffix = md5(uniqid('', true));
  151. }
  152. file_put_contents($targetDir.'/autoload_namespaces.php', $namespacesFile);
  153. file_put_contents($targetDir.'/autoload_classmap.php', $classmapFile);
  154. if ($includePathFile = $this->getIncludePathsFile($packageMap, $filesystem, $basePath, $relVendorPath, $vendorPath, $vendorPathCode52, $appBaseDirCode)) {
  155. file_put_contents($targetDir.'/include_paths.php', $includePathFile);
  156. }
  157. file_put_contents($vendorPath.'/autoload.php', $this->getAutoloadFile($vendorPathToTargetDirCode, $suffix));
  158. file_put_contents($targetDir.'/autoload_real.php', $this->getAutoloadRealFile(true, true, (bool) $includePathFile, $targetDirLoader, $filesCode, $vendorPathCode, $appBaseDirCode, $suffix, $useGlobalIncludePath));
  159. copy(__DIR__.'/ClassLoader.php', $targetDir.'/ClassLoader.php');
  160. $this->eventDispatcher->dispatch(ScriptEvents::POST_AUTOLOAD_DUMP);
  161. }
  162. public function buildPackageMap(InstallationManager $installationManager, PackageInterface $mainPackage, array $packages)
  163. {
  164. // build package => install path map
  165. $packageMap = array(array($mainPackage, ''));
  166. foreach ($packages as $package) {
  167. if ($package instanceof AliasPackage) {
  168. continue;
  169. }
  170. $packageMap[] = array(
  171. $package,
  172. $installationManager->getInstallPath($package)
  173. );
  174. }
  175. return $packageMap;
  176. }
  177. /**
  178. * Compiles an ordered list of namespace => path mappings
  179. *
  180. * @param array $packageMap array of array(package, installDir-relative-to-composer.json)
  181. * @param PackageInterface $mainPackage root package instance
  182. * @return array array('psr-0' => array('Ns\\Foo' => array('installDir')))
  183. */
  184. public function parseAutoloads(array $packageMap, PackageInterface $mainPackage)
  185. {
  186. $mainPackageMap = array_shift($packageMap);
  187. $sortedPackageMap = $this->sortPackageMap($packageMap);
  188. $sortedPackageMap[] = $mainPackageMap;
  189. array_unshift($packageMap, $mainPackageMap);
  190. $psr0 = $this->parseAutoloadsType($packageMap, 'psr-0', $mainPackage);
  191. $classmap = $this->parseAutoloadsType($sortedPackageMap, 'classmap', $mainPackage);
  192. $files = $this->parseAutoloadsType($sortedPackageMap, 'files', $mainPackage);
  193. krsort($psr0);
  194. return array('psr-0' => $psr0, 'classmap' => $classmap, 'files' => $files);
  195. }
  196. /**
  197. * Registers an autoloader based on an autoload map returned by parseAutoloads
  198. *
  199. * @param array $autoloads see parseAutoloads return value
  200. * @return ClassLoader
  201. */
  202. public function createLoader(array $autoloads)
  203. {
  204. $loader = new ClassLoader();
  205. if (isset($autoloads['psr-0'])) {
  206. foreach ($autoloads['psr-0'] as $namespace => $path) {
  207. $loader->add($namespace, $path);
  208. }
  209. }
  210. return $loader;
  211. }
  212. protected function getIncludePathsFile(array $packageMap, Filesystem $filesystem, $basePath, $relVendorPath, $vendorPath, $vendorPathCode, $appBaseDirCode)
  213. {
  214. $includePaths = array();
  215. foreach ($packageMap as $item) {
  216. list($package, $installPath) = $item;
  217. if (null !== $package->getTargetDir() && strlen($package->getTargetDir()) > 0) {
  218. $installPath = substr($installPath, 0, -strlen('/'.$package->getTargetDir()));
  219. }
  220. foreach ($package->getIncludePaths() as $includePath) {
  221. $includePath = trim($includePath, '/');
  222. $includePaths[] = empty($installPath) ? $includePath : $installPath.'/'.$includePath;
  223. }
  224. }
  225. if (!$includePaths) {
  226. return;
  227. }
  228. $includePathsFile = <<<EOF
  229. <?php
  230. // include_paths.php generated by Composer
  231. \$vendorDir = $vendorPathCode;
  232. \$baseDir = $appBaseDirCode;
  233. return array(
  234. EOF;
  235. foreach ($includePaths as $path) {
  236. $includePathsFile .= " " . $this->getPathCode($filesystem, $basePath, $relVendorPath, $vendorPath, $path) . ",\n";
  237. }
  238. return $includePathsFile . ");\n";
  239. }
  240. protected function getPathCode(Filesystem $filesystem, $basePath, $relVendorPath, $vendorPath, $path)
  241. {
  242. $path = $filesystem->normalizePath($path);
  243. $baseDir = '';
  244. if (!$filesystem->isAbsolutePath($path)) {
  245. if (strpos($path, $relVendorPath) === 0) {
  246. // path starts with vendor dir
  247. $path = substr($path, strlen($relVendorPath));
  248. $baseDir = '$vendorDir . ';
  249. } else {
  250. $path = '/'.$path;
  251. $baseDir = '$baseDir . ';
  252. }
  253. } elseif (strpos($path, $vendorPath) === 0) {
  254. $path = substr($path, strlen($vendorPath));
  255. $baseDir = '$vendorDir . ';
  256. } elseif (strpos($path, $basePath) === 0) {
  257. $path = substr($path, strlen($basePath));
  258. $baseDir = '$baseDir . ';
  259. }
  260. if (preg_match('/\.phar$/', $path)){
  261. $baseDir = "'phar://' . '" . $baseDir;
  262. }
  263. return $baseDir.var_export($path, true);
  264. }
  265. protected function getPath(Filesystem $filesystem, $basePath, $relVendorPath, $vendorPath, $path)
  266. {
  267. $path = $filesystem->normalizePath($path);
  268. if (!$filesystem->isAbsolutePath($path)) {
  269. if (strpos($path, $relVendorPath) === 0) {
  270. // path starts with vendor dir
  271. return $vendorPath . substr($path, strlen($relVendorPath));
  272. }
  273. return $basePath.'/'.$path;
  274. }
  275. return $path;
  276. }
  277. protected function getAutoloadFile($vendorPathToTargetDirCode, $suffix)
  278. {
  279. return <<<AUTOLOAD
  280. <?php
  281. // autoload.php generated by Composer
  282. require_once $vendorPathToTargetDirCode . '/autoload_real.php';
  283. return ComposerAutoloaderInit$suffix::getLoader();
  284. AUTOLOAD;
  285. }
  286. protected function getAutoloadRealFile($usePSR0, $useClassMap, $useIncludePath, $targetDirLoader, $filesCode, $vendorPathCode, $appBaseDirCode, $suffix, $useGlobalIncludePath)
  287. {
  288. // TODO the class ComposerAutoloaderInit should be revert to a closure
  289. // when APC has been fixed:
  290. // - https://github.com/composer/composer/issues/959
  291. // - https://bugs.php.net/bug.php?id=52144
  292. // - https://bugs.php.net/bug.php?id=61576
  293. // - https://bugs.php.net/bug.php?id=59298
  294. if ($filesCode) {
  295. $filesCode = "\n\n".rtrim($filesCode);
  296. }
  297. $file = <<<HEADER
  298. <?php
  299. // autoload_real.php generated by Composer
  300. class ComposerAutoloaderInit$suffix
  301. {
  302. private static \$loader;
  303. public static function loadClassLoader(\$class)
  304. {
  305. if ('Composer\\Autoload\\ClassLoader' === \$class) {
  306. require __DIR__ . '/ClassLoader.php';
  307. }
  308. }
  309. public static function getLoader()
  310. {
  311. if (null !== self::\$loader) {
  312. return self::\$loader;
  313. }
  314. spl_autoload_register(array('ComposerAutoloaderInit$suffix', 'loadClassLoader'), true, true);
  315. self::\$loader = \$loader = new \\Composer\\Autoload\\ClassLoader();
  316. spl_autoload_unregister(array('ComposerAutoloaderInit$suffix', 'loadClassLoader'));
  317. \$vendorDir = $vendorPathCode;
  318. \$baseDir = $appBaseDirCode;
  319. HEADER;
  320. if ($useIncludePath) {
  321. $file .= <<<'INCLUDE_PATH'
  322. $includePaths = require __DIR__ . '/include_paths.php';
  323. array_push($includePaths, get_include_path());
  324. set_include_path(join(PATH_SEPARATOR, $includePaths));
  325. INCLUDE_PATH;
  326. }
  327. if ($usePSR0) {
  328. $file .= <<<'PSR0'
  329. $map = require __DIR__ . '/autoload_namespaces.php';
  330. foreach ($map as $namespace => $path) {
  331. $loader->add($namespace, $path);
  332. }
  333. PSR0;
  334. }
  335. if ($useClassMap) {
  336. $file .= <<<'CLASSMAP'
  337. $classMap = require __DIR__ . '/autoload_classmap.php';
  338. if ($classMap) {
  339. $loader->addClassMap($classMap);
  340. }
  341. CLASSMAP;
  342. }
  343. if ($useGlobalIncludePath) {
  344. $file .= <<<'INCLUDEPATH'
  345. $loader->setUseIncludePath(true);
  346. INCLUDEPATH;
  347. }
  348. if ($targetDirLoader) {
  349. $file .= <<<REGISTER_AUTOLOAD
  350. spl_autoload_register(array('ComposerAutoloaderInit$suffix', 'autoload'), true, true);
  351. REGISTER_AUTOLOAD;
  352. }
  353. $file .= <<<METHOD_FOOTER
  354. \$loader->register(true);{$filesCode}
  355. return \$loader;
  356. }
  357. METHOD_FOOTER;
  358. $file .= $targetDirLoader;
  359. return $file . <<<FOOTER
  360. }
  361. FOOTER;
  362. }
  363. protected function parseAutoloadsType(array $packageMap, $type, PackageInterface $mainPackage)
  364. {
  365. $autoloads = array();
  366. foreach ($packageMap as $item) {
  367. list($package, $installPath) = $item;
  368. $autoload = $package->getAutoload();
  369. // skip misconfigured packages
  370. if (!isset($autoload[$type]) || !is_array($autoload[$type])) {
  371. continue;
  372. }
  373. if (null !== $package->getTargetDir() && $package !== $mainPackage) {
  374. $installPath = substr($installPath, 0, -strlen('/'.$package->getTargetDir()));
  375. }
  376. foreach ($autoload[$type] as $namespace => $paths) {
  377. foreach ((array) $paths as $path) {
  378. // remove target-dir from file paths of the root package
  379. if ($type === 'files' && $package === $mainPackage && $package->getTargetDir() && !is_readable($installPath.'/'.$path)) {
  380. $targetDir = str_replace('\\<dirsep\\>', '[\\\\/]', preg_quote(str_replace(array('/', '\\'), '<dirsep>', $package->getTargetDir())));
  381. $path = ltrim(preg_replace('{^'.$targetDir.'}', '', ltrim($path, '\\/')), '\\/');
  382. }
  383. // add target-dir from file paths that don't have it
  384. if ($type === 'files' && $package !== $mainPackage && $package->getTargetDir() && !is_readable($installPath.'/'.$path)) {
  385. $path = $package->getTargetDir() . '/' . $path;
  386. }
  387. // remove target-dir from classmap entries of the root package
  388. if ($type === 'classmap' && $package === $mainPackage && $package->getTargetDir() && !is_readable($installPath.'/'.$path)) {
  389. $targetDir = str_replace('\\<dirsep\\>', '[\\\\/]', preg_quote(str_replace(array('/', '\\'), '<dirsep>', $package->getTargetDir())));
  390. $path = ltrim(preg_replace('{^'.$targetDir.'}', '', ltrim($path, '\\/')), '\\/');
  391. }
  392. // add target-dir to classmap entries that don't have it
  393. if ($type === 'classmap' && $package !== $mainPackage && $package->getTargetDir() && !is_readable($installPath.'/'.$path)) {
  394. $path = $package->getTargetDir() . '/' . $path;
  395. }
  396. $autoloads[$namespace][] = empty($installPath) ? $path : $installPath.'/'.$path;
  397. }
  398. }
  399. }
  400. return $autoloads;
  401. }
  402. protected function sortPackageMap(array $packageMap)
  403. {
  404. $positions = array();
  405. $names = array();
  406. $indexes = array();
  407. foreach ($packageMap as $position => $item) {
  408. $mainName = $item[0]->getName();
  409. $names = array_merge(array_fill_keys($item[0]->getNames(), $mainName), $names);
  410. $names[$mainName] = $mainName;
  411. $indexes[$mainName] = $positions[$mainName] = $position;
  412. }
  413. foreach ($packageMap as $item) {
  414. $position = $positions[$item[0]->getName()];
  415. foreach (array_merge($item[0]->getRequires(), $item[0]->getDevRequires()) as $link) {
  416. $target = $link->getTarget();
  417. if (!isset($names[$target])) {
  418. continue;
  419. }
  420. $target = $names[$target];
  421. if ($positions[$target] <= $position) {
  422. continue;
  423. }
  424. foreach ($positions as $key => $value) {
  425. if ($value >= $position) {
  426. break;
  427. }
  428. $positions[$key]--;
  429. }
  430. $positions[$target] = $position - 1;
  431. }
  432. asort($positions);
  433. }
  434. $sortedPackageMap = array();
  435. foreach (array_keys($positions) as $packageName) {
  436. $sortedPackageMap[] = $packageMap[$indexes[$packageName]];
  437. }
  438. return $sortedPackageMap;
  439. }
  440. }