AutoloadGenerator.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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\EventDispatcher\EventDispatcher;
  14. use Composer\Installer\InstallationManager;
  15. use Composer\Package\AliasPackage;
  16. use Composer\Package\PackageInterface;
  17. use Composer\Repository\InstalledRepositoryInterface;
  18. use Composer\Util\Filesystem;
  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->dispatchScript(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->dispatchScript(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. $includePathsCode = '';
  230. foreach ($includePaths as $path) {
  231. $includePathsCode .= " " . $this->getPathCode($filesystem, $basePath, $vendorPath, $path) . ",\n";
  232. }
  233. return <<<EOF
  234. <?php
  235. // include_paths.php @generated by Composer
  236. \$vendorDir = $vendorPathCode;
  237. \$baseDir = $appBaseDirCode;
  238. return array(
  239. $includePathsCode);
  240. EOF;
  241. }
  242. protected function getIncludeFilesFile(array $files, Filesystem $filesystem, $basePath, $vendorPath, $vendorPathCode, $appBaseDirCode)
  243. {
  244. $filesCode = '';
  245. $files = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($files));
  246. foreach ($files as $functionFile) {
  247. $filesCode .= ' '.$this->getPathCode($filesystem, $basePath, $vendorPath, $functionFile).",\n";
  248. }
  249. if (!$filesCode) {
  250. return FALSE;
  251. }
  252. return <<<EOF
  253. <?php
  254. // autoload_files.php @generated by Composer
  255. \$vendorDir = $vendorPathCode;
  256. \$baseDir = $appBaseDirCode;
  257. return array(
  258. $filesCode);
  259. EOF;
  260. }
  261. protected function getPathCode(Filesystem $filesystem, $basePath, $vendorPath, $path)
  262. {
  263. if (!$filesystem->isAbsolutePath($path)) {
  264. $path = $basePath . '/' . $path;
  265. }
  266. $path = $filesystem->normalizePath($path);
  267. $baseDir = '';
  268. if (strpos($path, $vendorPath) === 0) {
  269. $path = substr($path, strlen($vendorPath));
  270. $baseDir = '$vendorDir';
  271. if ($path !== false) {
  272. $baseDir .= " . ";
  273. }
  274. } else {
  275. $path = $filesystem->normalizePath($filesystem->findShortestPath($basePath, $path, true));
  276. if (!$filesystem->isAbsolutePath($path)) {
  277. $baseDir = '$baseDir . ';
  278. $path = '/' . $path;
  279. }
  280. }
  281. if (preg_match('/\.phar$/', $path)) {
  282. $baseDir = "'phar://' . " . $baseDir;
  283. }
  284. return $baseDir . (($path !== false) ? var_export($path, true) : "");
  285. }
  286. protected function getAutoloadFile($vendorPathToTargetDirCode, $suffix)
  287. {
  288. return <<<AUTOLOAD
  289. <?php
  290. // autoload.php @generated by Composer
  291. require_once $vendorPathToTargetDirCode . '/autoload_real.php';
  292. return ComposerAutoloaderInit$suffix::getLoader();
  293. AUTOLOAD;
  294. }
  295. protected function getAutoloadRealFile($usePSR0, $useClassMap, $useIncludePath, $targetDirLoader, $useIncludeFiles, $vendorPathCode, $appBaseDirCode, $suffix, $useGlobalIncludePath)
  296. {
  297. // TODO the class ComposerAutoloaderInit should be revert to a closure
  298. // when APC has been fixed:
  299. // - https://github.com/composer/composer/issues/959
  300. // - https://bugs.php.net/bug.php?id=52144
  301. // - https://bugs.php.net/bug.php?id=61576
  302. // - https://bugs.php.net/bug.php?id=59298
  303. $file = <<<HEADER
  304. <?php
  305. // autoload_real.php @generated by Composer
  306. class ComposerAutoloaderInit$suffix
  307. {
  308. private static \$loader;
  309. public static function loadClassLoader(\$class)
  310. {
  311. if ('Composer\\Autoload\\ClassLoader' === \$class) {
  312. require __DIR__ . '/ClassLoader.php';
  313. }
  314. }
  315. public static function getLoader()
  316. {
  317. if (null !== self::\$loader) {
  318. return self::\$loader;
  319. }
  320. spl_autoload_register(array('ComposerAutoloaderInit$suffix', 'loadClassLoader'), true, true);
  321. self::\$loader = \$loader = new \\Composer\\Autoload\\ClassLoader();
  322. spl_autoload_unregister(array('ComposerAutoloaderInit$suffix', 'loadClassLoader'));
  323. \$vendorDir = $vendorPathCode;
  324. \$baseDir = $appBaseDirCode;
  325. HEADER;
  326. if ($useIncludePath) {
  327. $file .= <<<'INCLUDE_PATH'
  328. $includePaths = require __DIR__ . '/include_paths.php';
  329. array_push($includePaths, get_include_path());
  330. set_include_path(join(PATH_SEPARATOR, $includePaths));
  331. INCLUDE_PATH;
  332. }
  333. if ($usePSR0) {
  334. $file .= <<<'PSR0'
  335. $map = require __DIR__ . '/autoload_namespaces.php';
  336. foreach ($map as $namespace => $path) {
  337. $loader->set($namespace, $path);
  338. }
  339. PSR0;
  340. }
  341. if ($useClassMap) {
  342. $file .= <<<'CLASSMAP'
  343. $classMap = require __DIR__ . '/autoload_classmap.php';
  344. if ($classMap) {
  345. $loader->addClassMap($classMap);
  346. }
  347. CLASSMAP;
  348. }
  349. if ($useGlobalIncludePath) {
  350. $file .= <<<'INCLUDEPATH'
  351. $loader->setUseIncludePath(true);
  352. INCLUDEPATH;
  353. }
  354. if ($targetDirLoader) {
  355. $file .= <<<REGISTER_AUTOLOAD
  356. spl_autoload_register(array('ComposerAutoloaderInit$suffix', 'autoload'), true, true);
  357. REGISTER_AUTOLOAD;
  358. }
  359. $file .= <<<REGISTER_LOADER
  360. \$loader->register(true);
  361. REGISTER_LOADER;
  362. if ($useIncludeFiles) {
  363. $file .= <<<'INCLUDE_FILES'
  364. $includeFiles = require __DIR__ . '/autoload_files.php';
  365. foreach ($includeFiles as $file) {
  366. require $file;
  367. }
  368. INCLUDE_FILES;
  369. }
  370. $file .= <<<METHOD_FOOTER
  371. return \$loader;
  372. }
  373. METHOD_FOOTER;
  374. $file .= $targetDirLoader;
  375. return $file . <<<FOOTER
  376. }
  377. FOOTER;
  378. }
  379. protected function parseAutoloadsType(array $packageMap, $type, PackageInterface $mainPackage)
  380. {
  381. $autoloads = array();
  382. foreach ($packageMap as $item) {
  383. list($package, $installPath) = $item;
  384. $autoload = $package->getAutoload();
  385. // skip misconfigured packages
  386. if (!isset($autoload[$type]) || !is_array($autoload[$type])) {
  387. continue;
  388. }
  389. if (null !== $package->getTargetDir() && $package !== $mainPackage) {
  390. $installPath = substr($installPath, 0, -strlen('/'.$package->getTargetDir()));
  391. }
  392. foreach ($autoload[$type] as $namespace => $paths) {
  393. foreach ((array) $paths as $path) {
  394. // remove target-dir from file paths of the root package
  395. if ($type === 'files' && $package === $mainPackage && $package->getTargetDir() && !is_readable($installPath.'/'.$path)) {
  396. $targetDir = str_replace('\\<dirsep\\>', '[\\\\/]', preg_quote(str_replace(array('/', '\\'), '<dirsep>', $package->getTargetDir())));
  397. $path = ltrim(preg_replace('{^'.$targetDir.'}', '', ltrim($path, '\\/')), '\\/');
  398. }
  399. // add target-dir from file paths that don't have it
  400. if ($type === 'files' && $package !== $mainPackage && $package->getTargetDir() && !is_readable($installPath.'/'.$path)) {
  401. $path = $package->getTargetDir() . '/' . $path;
  402. }
  403. // remove target-dir from classmap entries of the root package
  404. if ($type === 'classmap' && $package === $mainPackage && $package->getTargetDir() && !is_readable($installPath.'/'.$path)) {
  405. $targetDir = str_replace('\\<dirsep\\>', '[\\\\/]', preg_quote(str_replace(array('/', '\\'), '<dirsep>', $package->getTargetDir())));
  406. $path = ltrim(preg_replace('{^'.$targetDir.'}', '', ltrim($path, '\\/')), '\\/');
  407. }
  408. // add target-dir to classmap entries that don't have it
  409. if ($type === 'classmap' && $package !== $mainPackage && $package->getTargetDir() && !is_readable($installPath.'/'.$path)) {
  410. $path = $package->getTargetDir() . '/' . $path;
  411. }
  412. if (empty($installPath)) {
  413. $autoloads[$namespace][] = empty($path) ? '.' : $path;
  414. } else {
  415. $autoloads[$namespace][] = $installPath.'/'.$path;
  416. }
  417. }
  418. }
  419. }
  420. return $autoloads;
  421. }
  422. protected function sortPackageMap(array $packageMap)
  423. {
  424. $positions = array();
  425. $names = array();
  426. $indexes = array();
  427. foreach ($packageMap as $position => $item) {
  428. $mainName = $item[0]->getName();
  429. $names = array_merge(array_fill_keys($item[0]->getNames(), $mainName), $names);
  430. $names[$mainName] = $mainName;
  431. $indexes[$mainName] = $positions[$mainName] = $position;
  432. }
  433. foreach ($packageMap as $item) {
  434. $position = $positions[$item[0]->getName()];
  435. foreach (array_merge($item[0]->getRequires(), $item[0]->getDevRequires()) as $link) {
  436. $target = $link->getTarget();
  437. if (!isset($names[$target])) {
  438. continue;
  439. }
  440. $target = $names[$target];
  441. if ($positions[$target] <= $position) {
  442. continue;
  443. }
  444. foreach ($positions as $key => $value) {
  445. if ($value >= $position) {
  446. break;
  447. }
  448. $positions[$key]--;
  449. }
  450. $positions[$target] = $position - 1;
  451. }
  452. asort($positions);
  453. }
  454. $sortedPackageMap = array();
  455. foreach (array_keys($positions) as $packageName) {
  456. $sortedPackageMap[] = $packageMap[$indexes[$packageName]];
  457. }
  458. return $sortedPackageMap;
  459. }
  460. }