AutoloadGenerator.php 20 KB

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