AutoloadGenerator.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  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\IO\IOInterface;
  16. use Composer\Package\AliasPackage;
  17. use Composer\Package\PackageInterface;
  18. use Composer\Repository\InstalledRepositoryInterface;
  19. use Composer\Util\Filesystem;
  20. use Composer\Script\ScriptEvents;
  21. /**
  22. * @author Igor Wiedler <igor@wiedler.ch>
  23. * @author Jordi Boggiano <j.boggiano@seld.be>
  24. */
  25. class AutoloadGenerator
  26. {
  27. /**
  28. * @var EventDispatcher
  29. */
  30. private $eventDispatcher;
  31. /**
  32. * @var IOInterface
  33. */
  34. private $io;
  35. /**
  36. * @var bool
  37. */
  38. private $devMode = false;
  39. /**
  40. * @var bool
  41. */
  42. private $classMapAuthoritative = false;
  43. /**
  44. * @var bool
  45. */
  46. private $runScripts = false;
  47. public function __construct(EventDispatcher $eventDispatcher, IOInterface $io = null)
  48. {
  49. $this->eventDispatcher = $eventDispatcher;
  50. $this->io = $io;
  51. }
  52. public function setDevMode($devMode = true)
  53. {
  54. $this->devMode = (boolean) $devMode;
  55. }
  56. /**
  57. * Whether or not generated autoloader considers the class map
  58. * authoritative.
  59. *
  60. * @param bool $classMapAuthoritative
  61. */
  62. public function setClassMapAuthoritative($classMapAuthoritative)
  63. {
  64. $this->classMapAuthoritative = (boolean) $classMapAuthoritative;
  65. }
  66. /**
  67. * Set whether to run scripts or not
  68. *
  69. * @param bool $runScripts
  70. */
  71. public function setRunScripts($runScripts = true)
  72. {
  73. $this->runScripts = (boolean) $runScripts;
  74. }
  75. public function dump(Config $config, InstalledRepositoryInterface $localRepo, PackageInterface $mainPackage, InstallationManager $installationManager, $targetDir, $scanPsr0Packages = false, $suffix = '')
  76. {
  77. if ($this->classMapAuthoritative) {
  78. // Force scanPsr0Packages when classmap is authoritative
  79. $scanPsr0Packages = true;
  80. }
  81. if ($this->runScripts) {
  82. $this->eventDispatcher->dispatchScript(ScriptEvents::PRE_AUTOLOAD_DUMP, $this->devMode, array(), array(
  83. 'optimize' => (bool) $scanPsr0Packages,
  84. ));
  85. }
  86. $filesystem = new Filesystem();
  87. $filesystem->ensureDirectoryExists($config->get('vendor-dir'));
  88. // Do not remove double realpath() calls.
  89. // Fixes failing Windows realpath() implementation.
  90. // See https://bugs.php.net/bug.php?id=72738
  91. $basePath = $filesystem->normalizePath(realpath(realpath(getcwd())));
  92. $vendorPath = $filesystem->normalizePath(realpath(realpath($config->get('vendor-dir'))));
  93. $useGlobalIncludePath = (bool) $config->get('use-include-path');
  94. $prependAutoloader = $config->get('prepend-autoloader') === false ? 'false' : 'true';
  95. $targetDir = $vendorPath.'/'.$targetDir;
  96. $filesystem->ensureDirectoryExists($targetDir);
  97. $vendorPathCode = $filesystem->findShortestPathCode(realpath($targetDir), $vendorPath, true);
  98. $vendorPathCode52 = str_replace('__DIR__', 'dirname(__FILE__)', $vendorPathCode);
  99. $vendorPathToTargetDirCode = $filesystem->findShortestPathCode($vendorPath, realpath($targetDir), true);
  100. $appBaseDirCode = $filesystem->findShortestPathCode($vendorPath, $basePath, true);
  101. $appBaseDirCode = str_replace('__DIR__', '$vendorDir', $appBaseDirCode);
  102. $namespacesFile = <<<EOF
  103. <?php
  104. // autoload_namespaces.php @generated by Composer
  105. \$vendorDir = $vendorPathCode52;
  106. \$baseDir = $appBaseDirCode;
  107. return array(
  108. EOF;
  109. $psr4File = <<<EOF
  110. <?php
  111. // autoload_psr4.php @generated by Composer
  112. \$vendorDir = $vendorPathCode52;
  113. \$baseDir = $appBaseDirCode;
  114. return array(
  115. EOF;
  116. // Collect information from all packages.
  117. $packageMap = $this->buildPackageMap($installationManager, $mainPackage, $localRepo->getCanonicalPackages());
  118. $autoloads = $this->parseAutoloads($packageMap, $mainPackage);
  119. // Process the 'psr-0' base directories.
  120. foreach ($autoloads['psr-0'] as $namespace => $paths) {
  121. $exportedPaths = array();
  122. foreach ($paths as $path) {
  123. $exportedPaths[] = $this->getPathCode($filesystem, $basePath, $vendorPath, $path);
  124. }
  125. $exportedPrefix = var_export($namespace, true);
  126. $namespacesFile .= " $exportedPrefix => ";
  127. $namespacesFile .= "array(".implode(', ', $exportedPaths)."),\n";
  128. }
  129. $namespacesFile .= ");\n";
  130. // Process the 'psr-4' base directories.
  131. foreach ($autoloads['psr-4'] as $namespace => $paths) {
  132. $exportedPaths = array();
  133. foreach ($paths as $path) {
  134. $exportedPaths[] = $this->getPathCode($filesystem, $basePath, $vendorPath, $path);
  135. }
  136. $exportedPrefix = var_export($namespace, true);
  137. $psr4File .= " $exportedPrefix => ";
  138. $psr4File .= "array(".implode(', ', $exportedPaths)."),\n";
  139. }
  140. $psr4File .= ");\n";
  141. $classmapFile = <<<EOF
  142. <?php
  143. // autoload_classmap.php @generated by Composer
  144. \$vendorDir = $vendorPathCode52;
  145. \$baseDir = $appBaseDirCode;
  146. return array(
  147. EOF;
  148. // add custom psr-0 autoloading if the root package has a target dir
  149. $targetDirLoader = null;
  150. $mainAutoload = $mainPackage->getAutoload();
  151. if ($mainPackage->getTargetDir() && !empty($mainAutoload['psr-0'])) {
  152. $levels = count(explode('/', $filesystem->normalizePath($mainPackage->getTargetDir())));
  153. $prefixes = implode(', ', array_map(function ($prefix) {
  154. return var_export($prefix, true);
  155. }, array_keys($mainAutoload['psr-0'])));
  156. $baseDirFromTargetDirCode = $filesystem->findShortestPathCode($targetDir, $basePath, true);
  157. $targetDirLoader = <<<EOF
  158. public static function autoload(\$class)
  159. {
  160. \$dir = $baseDirFromTargetDirCode . '/';
  161. \$prefixes = array($prefixes);
  162. foreach (\$prefixes as \$prefix) {
  163. if (0 !== strpos(\$class, \$prefix)) {
  164. continue;
  165. }
  166. \$path = \$dir . implode('/', array_slice(explode('\\\\', \$class), $levels)).'.php';
  167. if (!\$path = stream_resolve_include_path(\$path)) {
  168. return false;
  169. }
  170. require \$path;
  171. return true;
  172. }
  173. }
  174. EOF;
  175. }
  176. $blacklist = null;
  177. if (!empty($autoloads['exclude-from-classmap'])) {
  178. $blacklist = '{(' . implode('|', $autoloads['exclude-from-classmap']) . ')}';
  179. }
  180. // flatten array
  181. $classMap = array();
  182. if ($scanPsr0Packages) {
  183. $namespacesToScan = array();
  184. // Scan the PSR-0/4 directories for class files, and add them to the class map
  185. foreach (array('psr-0', 'psr-4') as $psrType) {
  186. foreach ($autoloads[$psrType] as $namespace => $paths) {
  187. $namespacesToScan[$namespace][] = array('paths' => $paths, 'type' => $psrType);
  188. }
  189. }
  190. krsort($namespacesToScan);
  191. foreach ($namespacesToScan as $namespace => $groups) {
  192. foreach ($groups as $group) {
  193. $psrType = $group['type'];
  194. foreach ($group['paths'] as $dir) {
  195. $dir = $filesystem->normalizePath($filesystem->isAbsolutePath($dir) ? $dir : $basePath.'/'.$dir);
  196. if (!is_dir($dir)) {
  197. continue;
  198. }
  199. $namespaceFilter = $namespace === '' ? null : $namespace;
  200. $classMap = $this->addClassMapCode($filesystem, $basePath, $vendorPath, $dir, $blacklist, $namespaceFilter, $classMap);
  201. }
  202. }
  203. }
  204. }
  205. foreach ($autoloads['classmap'] as $dir) {
  206. $classMap = $this->addClassMapCode($filesystem, $basePath, $vendorPath, $dir, $blacklist, null, $classMap);
  207. }
  208. ksort($classMap);
  209. foreach ($classMap as $class => $code) {
  210. $classmapFile .= ' '.var_export($class, true).' => '.$code;
  211. }
  212. $classmapFile .= ");\n";
  213. if (!$suffix) {
  214. if (!$config->get('autoloader-suffix') && is_readable($vendorPath.'/autoload.php')) {
  215. $content = file_get_contents($vendorPath.'/autoload.php');
  216. if (preg_match('{ComposerAutoloaderInit([^:\s]+)::}', $content, $match)) {
  217. $suffix = $match[1];
  218. }
  219. }
  220. if (!$suffix) {
  221. $suffix = $config->get('autoloader-suffix') ?: md5(uniqid('', true));
  222. }
  223. }
  224. file_put_contents($targetDir.'/autoload_namespaces.php', $namespacesFile);
  225. file_put_contents($targetDir.'/autoload_psr4.php', $psr4File);
  226. file_put_contents($targetDir.'/autoload_classmap.php', $classmapFile);
  227. $includePathFilePath = $targetDir.'/include_paths.php';
  228. if ($includePathFileContents = $this->getIncludePathsFile($packageMap, $filesystem, $basePath, $vendorPath, $vendorPathCode52, $appBaseDirCode)) {
  229. file_put_contents($includePathFilePath, $includePathFileContents);
  230. } elseif (file_exists($includePathFilePath)) {
  231. unlink($includePathFilePath);
  232. }
  233. $includeFilesFilePath = $targetDir.'/autoload_files.php';
  234. if ($includeFilesFileContents = $this->getIncludeFilesFile($autoloads['files'], $filesystem, $basePath, $vendorPath, $vendorPathCode52, $appBaseDirCode)) {
  235. file_put_contents($includeFilesFilePath, $includeFilesFileContents);
  236. } elseif (file_exists($includeFilesFilePath)) {
  237. unlink($includeFilesFilePath);
  238. }
  239. file_put_contents($targetDir.'/autoload_static.php', $this->getStaticFile($suffix, $targetDir, $vendorPath, $basePath, $staticPhpVersion));
  240. file_put_contents($vendorPath.'/autoload.php', $this->getAutoloadFile($vendorPathToTargetDirCode, $suffix));
  241. file_put_contents($targetDir.'/autoload_real.php', $this->getAutoloadRealFile(true, (bool) $includePathFileContents, $targetDirLoader, (bool) $includeFilesFileContents, $vendorPathCode, $appBaseDirCode, $suffix, $useGlobalIncludePath, $prependAutoloader, $staticPhpVersion));
  242. $this->safeCopy(__DIR__.'/ClassLoader.php', $targetDir.'/ClassLoader.php');
  243. $this->safeCopy(__DIR__.'/../../../LICENSE', $targetDir.'/LICENSE');
  244. if ($this->runScripts) {
  245. $this->eventDispatcher->dispatchScript(ScriptEvents::POST_AUTOLOAD_DUMP, $this->devMode, array(), array(
  246. 'optimize' => (bool) $scanPsr0Packages,
  247. ));
  248. }
  249. }
  250. private function addClassMapCode($filesystem, $basePath, $vendorPath, $dir, $blacklist = null, $namespaceFilter = null, array $classMap = array())
  251. {
  252. foreach ($this->generateClassMap($dir, $blacklist, $namespaceFilter) as $class => $path) {
  253. $pathCode = $this->getPathCode($filesystem, $basePath, $vendorPath, $path).",\n";
  254. if (!isset($classMap[$class])) {
  255. $classMap[$class] = $pathCode;
  256. } elseif ($this->io && $classMap[$class] !== $pathCode && !preg_match('{/(test|fixture|example|stub)s?/}i', strtr($classMap[$class].' '.$path, '\\', '/'))) {
  257. $this->io->writeError(
  258. '<warning>Warning: Ambiguous class resolution, "'.$class.'"'.
  259. ' was found in both "'.str_replace(array('$vendorDir . \'', "',\n"), array($vendorPath, ''), $classMap[$class]).'" and "'.$path.'", the first will be used.</warning>'
  260. );
  261. }
  262. }
  263. return $classMap;
  264. }
  265. private function generateClassMap($dir, $blacklist = null, $namespaceFilter = null, $showAmbiguousWarning = true)
  266. {
  267. return ClassMapGenerator::createMap($dir, $blacklist, $showAmbiguousWarning ? $this->io : null, $namespaceFilter);
  268. }
  269. public function buildPackageMap(InstallationManager $installationManager, PackageInterface $mainPackage, array $packages)
  270. {
  271. // build package => install path map
  272. $packageMap = array(array($mainPackage, ''));
  273. foreach ($packages as $package) {
  274. if ($package instanceof AliasPackage) {
  275. continue;
  276. }
  277. $this->validatePackage($package);
  278. $packageMap[] = array(
  279. $package,
  280. $installationManager->getInstallPath($package),
  281. );
  282. }
  283. return $packageMap;
  284. }
  285. /**
  286. * @param PackageInterface $package
  287. *
  288. * @throws \InvalidArgumentException Throws an exception, if the package has illegal settings.
  289. */
  290. protected function validatePackage(PackageInterface $package)
  291. {
  292. $autoload = $package->getAutoload();
  293. if (!empty($autoload['psr-4']) && null !== $package->getTargetDir()) {
  294. $name = $package->getName();
  295. $package->getTargetDir();
  296. throw new \InvalidArgumentException("PSR-4 autoloading is incompatible with the target-dir property, remove the target-dir in package '$name'.");
  297. }
  298. if (!empty($autoload['psr-4'])) {
  299. foreach ($autoload['psr-4'] as $namespace => $dirs) {
  300. if ($namespace !== '' && '\\' !== substr($namespace, -1)) {
  301. throw new \InvalidArgumentException("psr-4 namespaces must end with a namespace separator, '$namespace' does not, use '$namespace\\'.");
  302. }
  303. }
  304. }
  305. }
  306. /**
  307. * Compiles an ordered list of namespace => path mappings
  308. *
  309. * @param array $packageMap array of array(package, installDir-relative-to-composer.json)
  310. * @param PackageInterface $mainPackage root package instance
  311. * @return array array('psr-0' => array('Ns\\Foo' => array('installDir')))
  312. */
  313. public function parseAutoloads(array $packageMap, PackageInterface $mainPackage)
  314. {
  315. $mainPackageMap = array_shift($packageMap);
  316. $sortedPackageMap = $this->sortPackageMap($packageMap);
  317. $sortedPackageMap[] = $mainPackageMap;
  318. array_unshift($packageMap, $mainPackageMap);
  319. $psr0 = $this->parseAutoloadsType($packageMap, 'psr-0', $mainPackage);
  320. $psr4 = $this->parseAutoloadsType($packageMap, 'psr-4', $mainPackage);
  321. $classmap = $this->parseAutoloadsType(array_reverse($sortedPackageMap), 'classmap', $mainPackage);
  322. $files = $this->parseAutoloadsType($sortedPackageMap, 'files', $mainPackage);
  323. $exclude = $this->parseAutoloadsType($sortedPackageMap, 'exclude-from-classmap', $mainPackage);
  324. krsort($psr0);
  325. krsort($psr4);
  326. return array(
  327. 'psr-0' => $psr0,
  328. 'psr-4' => $psr4,
  329. 'classmap' => $classmap,
  330. 'files' => $files,
  331. 'exclude-from-classmap' => $exclude,
  332. );
  333. }
  334. /**
  335. * Registers an autoloader based on an autoload map returned by parseAutoloads
  336. *
  337. * @param array $autoloads see parseAutoloads return value
  338. * @return ClassLoader
  339. */
  340. public function createLoader(array $autoloads)
  341. {
  342. $loader = new ClassLoader();
  343. if (isset($autoloads['psr-0'])) {
  344. foreach ($autoloads['psr-0'] as $namespace => $path) {
  345. $loader->add($namespace, $path);
  346. }
  347. }
  348. if (isset($autoloads['psr-4'])) {
  349. foreach ($autoloads['psr-4'] as $namespace => $path) {
  350. $loader->addPsr4($namespace, $path);
  351. }
  352. }
  353. if (isset($autoloads['classmap'])) {
  354. foreach ($autoloads['classmap'] as $dir) {
  355. try {
  356. $loader->addClassMap($this->generateClassMap($dir, null, null, false));
  357. } catch (\RuntimeException $e) {
  358. $this->io->writeError('<warning>'.$e->getMessage().'</warning>');
  359. }
  360. }
  361. }
  362. return $loader;
  363. }
  364. protected function getIncludePathsFile(array $packageMap, Filesystem $filesystem, $basePath, $vendorPath, $vendorPathCode, $appBaseDirCode)
  365. {
  366. $includePaths = array();
  367. foreach ($packageMap as $item) {
  368. list($package, $installPath) = $item;
  369. if (null !== $package->getTargetDir() && strlen($package->getTargetDir()) > 0) {
  370. $installPath = substr($installPath, 0, -strlen('/'.$package->getTargetDir()));
  371. }
  372. foreach ($package->getIncludePaths() as $includePath) {
  373. $includePath = trim($includePath, '/');
  374. $includePaths[] = empty($installPath) ? $includePath : $installPath.'/'.$includePath;
  375. }
  376. }
  377. if (!$includePaths) {
  378. return;
  379. }
  380. $includePathsCode = '';
  381. foreach ($includePaths as $path) {
  382. $includePathsCode .= " " . $this->getPathCode($filesystem, $basePath, $vendorPath, $path) . ",\n";
  383. }
  384. return <<<EOF
  385. <?php
  386. // include_paths.php @generated by Composer
  387. \$vendorDir = $vendorPathCode;
  388. \$baseDir = $appBaseDirCode;
  389. return array(
  390. $includePathsCode);
  391. EOF;
  392. }
  393. protected function getIncludeFilesFile(array $files, Filesystem $filesystem, $basePath, $vendorPath, $vendorPathCode, $appBaseDirCode)
  394. {
  395. $filesCode = '';
  396. foreach ($files as $fileIdentifier => $functionFile) {
  397. $filesCode .= ' ' . var_export($fileIdentifier, true) . ' => '
  398. . $this->getPathCode($filesystem, $basePath, $vendorPath, $functionFile) . ",\n";
  399. }
  400. if (!$filesCode) {
  401. return false;
  402. }
  403. return <<<EOF
  404. <?php
  405. // autoload_files.php @generated by Composer
  406. \$vendorDir = $vendorPathCode;
  407. \$baseDir = $appBaseDirCode;
  408. return array(
  409. $filesCode);
  410. EOF;
  411. }
  412. protected function getPathCode(Filesystem $filesystem, $basePath, $vendorPath, $path)
  413. {
  414. if (!$filesystem->isAbsolutePath($path)) {
  415. $path = $basePath . '/' . $path;
  416. }
  417. $path = $filesystem->normalizePath($path);
  418. $baseDir = '';
  419. if (strpos($path.'/', $vendorPath.'/') === 0) {
  420. $path = substr($path, strlen($vendorPath));
  421. $baseDir = '$vendorDir';
  422. if ($path !== false) {
  423. $baseDir .= " . ";
  424. }
  425. } else {
  426. $path = $filesystem->normalizePath($filesystem->findShortestPath($basePath, $path, true));
  427. if (!$filesystem->isAbsolutePath($path)) {
  428. $baseDir = '$baseDir . ';
  429. $path = '/' . $path;
  430. }
  431. }
  432. if (preg_match('/\.phar$/', $path)) {
  433. $baseDir = "'phar://' . " . $baseDir;
  434. }
  435. return $baseDir . (($path !== false) ? var_export($path, true) : "");
  436. }
  437. protected function getAutoloadFile($vendorPathToTargetDirCode, $suffix)
  438. {
  439. $lastChar = $vendorPathToTargetDirCode[strlen($vendorPathToTargetDirCode)-1];
  440. if ("'" === $lastChar || '"' === $lastChar) {
  441. $vendorPathToTargetDirCode = substr($vendorPathToTargetDirCode, 0, -1).'/autoload_real.php'.$lastChar;
  442. } else {
  443. $vendorPathToTargetDirCode .= " . '/autoload_real.php'";
  444. }
  445. return <<<AUTOLOAD
  446. <?php
  447. // autoload.php @generated by Composer
  448. require_once $vendorPathToTargetDirCode;
  449. return ComposerAutoloaderInit$suffix::getLoader();
  450. AUTOLOAD;
  451. }
  452. protected function getAutoloadRealFile($useClassMap, $useIncludePath, $targetDirLoader, $useIncludeFiles, $vendorPathCode, $appBaseDirCode, $suffix, $useGlobalIncludePath, $prependAutoloader, $staticPhpVersion = 70000)
  453. {
  454. $file = <<<HEADER
  455. <?php
  456. // autoload_real.php @generated by Composer
  457. class ComposerAutoloaderInit$suffix
  458. {
  459. private static \$loader;
  460. public static function loadClassLoader(\$class)
  461. {
  462. if ('Composer\\Autoload\\ClassLoader' === \$class) {
  463. require __DIR__ . '/ClassLoader.php';
  464. }
  465. }
  466. public static function getLoader()
  467. {
  468. if (null !== self::\$loader) {
  469. return self::\$loader;
  470. }
  471. spl_autoload_register(array('ComposerAutoloaderInit$suffix', 'loadClassLoader'), true, $prependAutoloader);
  472. self::\$loader = \$loader = new \\Composer\\Autoload\\ClassLoader();
  473. spl_autoload_unregister(array('ComposerAutoloaderInit$suffix', 'loadClassLoader'));
  474. HEADER;
  475. if ($useIncludePath) {
  476. $file .= <<<'INCLUDE_PATH'
  477. $includePaths = require __DIR__ . '/include_paths.php';
  478. array_push($includePaths, get_include_path());
  479. set_include_path(join(PATH_SEPARATOR, $includePaths));
  480. INCLUDE_PATH;
  481. }
  482. $file .= <<<STATIC_INIT
  483. \$useStaticLoader = PHP_VERSION_ID >= $staticPhpVersion && !defined('HHVM_VERSION');
  484. if (\$useStaticLoader) {
  485. require_once __DIR__ . '/autoload_static.php';
  486. call_user_func(\Composer\Autoload\ComposerStaticInit$suffix::getInitializer(\$loader));
  487. } else {
  488. STATIC_INIT;
  489. if (!$this->classMapAuthoritative) {
  490. $file .= <<<'PSR04'
  491. $map = require __DIR__ . '/autoload_namespaces.php';
  492. foreach ($map as $namespace => $path) {
  493. $loader->set($namespace, $path);
  494. }
  495. $map = require __DIR__ . '/autoload_psr4.php';
  496. foreach ($map as $namespace => $path) {
  497. $loader->setPsr4($namespace, $path);
  498. }
  499. PSR04;
  500. }
  501. if ($useClassMap) {
  502. $file .= <<<'CLASSMAP'
  503. $classMap = require __DIR__ . '/autoload_classmap.php';
  504. if ($classMap) {
  505. $loader->addClassMap($classMap);
  506. }
  507. CLASSMAP;
  508. }
  509. $file .= " }\n\n";
  510. if ($this->classMapAuthoritative) {
  511. $file .= <<<'CLASSMAPAUTHORITATIVE'
  512. $loader->setClassMapAuthoritative(true);
  513. CLASSMAPAUTHORITATIVE;
  514. }
  515. if ($useGlobalIncludePath) {
  516. $file .= <<<'INCLUDEPATH'
  517. $loader->setUseIncludePath(true);
  518. INCLUDEPATH;
  519. }
  520. if ($targetDirLoader) {
  521. $file .= <<<REGISTER_TARGET_DIR_AUTOLOAD
  522. spl_autoload_register(array('ComposerAutoloaderInit$suffix', 'autoload'), true, true);
  523. REGISTER_TARGET_DIR_AUTOLOAD;
  524. }
  525. $file .= <<<REGISTER_LOADER
  526. \$loader->register($prependAutoloader);
  527. REGISTER_LOADER;
  528. if ($useIncludeFiles) {
  529. $file .= <<<INCLUDE_FILES
  530. if (\$useStaticLoader) {
  531. \$includeFiles = Composer\Autoload\ComposerStaticInit$suffix::\$files;
  532. } else {
  533. \$includeFiles = require __DIR__ . '/autoload_files.php';
  534. }
  535. foreach (\$includeFiles as \$fileIdentifier => \$file) {
  536. composerRequire$suffix(\$fileIdentifier, \$file);
  537. }
  538. INCLUDE_FILES;
  539. }
  540. $file .= <<<METHOD_FOOTER
  541. return \$loader;
  542. }
  543. METHOD_FOOTER;
  544. $file .= $targetDirLoader;
  545. if ($useIncludeFiles) {
  546. return $file . <<<FOOTER
  547. }
  548. function composerRequire$suffix(\$fileIdentifier, \$file)
  549. {
  550. if (empty(\$GLOBALS['__composer_autoload_files'][\$fileIdentifier])) {
  551. require \$file;
  552. \$GLOBALS['__composer_autoload_files'][\$fileIdentifier] = true;
  553. }
  554. }
  555. FOOTER;
  556. }
  557. return $file . <<<FOOTER
  558. }
  559. FOOTER;
  560. }
  561. protected function getStaticFile($suffix, $targetDir, $vendorPath, $basePath, &$staticPhpVersion)
  562. {
  563. $staticPhpVersion = 50600;
  564. $file = <<<HEADER
  565. <?php
  566. // autoload_static.php @generated by Composer
  567. namespace Composer\Autoload;
  568. class ComposerStaticInit$suffix
  569. {
  570. HEADER;
  571. $loader = new ClassLoader();
  572. $map = require $targetDir . '/autoload_namespaces.php';
  573. foreach ($map as $namespace => $path) {
  574. $loader->set($namespace, $path);
  575. }
  576. $map = require $targetDir . '/autoload_psr4.php';
  577. foreach ($map as $namespace => $path) {
  578. $loader->setPsr4($namespace, $path);
  579. }
  580. $classMap = require $targetDir . '/autoload_classmap.php';
  581. if ($classMap) {
  582. $loader->addClassMap($classMap);
  583. }
  584. $filesystem = new Filesystem();
  585. $vendorPathCode = ' => ' . $filesystem->findShortestPathCode(realpath($targetDir), $vendorPath, true, true) . " . '/";
  586. $appBaseDirCode = ' => ' . $filesystem->findShortestPathCode(realpath($targetDir), $basePath, true, true) . " . '/";
  587. $absoluteVendorPathCode = ' => ' . substr(var_export(rtrim($vendorDir, '\\/') . '/', true), 0, -1);
  588. $absoluteAppBaseDirCode = ' => ' . substr(var_export(rtrim($baseDir, '\\/') . '/', true), 0, -1);
  589. $initializer = '';
  590. $prefix = "\0Composer\Autoload\ClassLoader\0";
  591. $prefixLen = strlen($prefix);
  592. if (file_exists($targetDir . '/autoload_files.php')) {
  593. $maps = array('files' => require $targetDir . '/autoload_files.php');
  594. } else {
  595. $maps = array();
  596. }
  597. foreach ((array) $loader as $prop => $value) {
  598. if ($value && 0 === strpos($prop, $prefix)) {
  599. $maps[substr($prop, $prefixLen)] = $value;
  600. }
  601. }
  602. foreach ($maps as $prop => $value) {
  603. if (count($value) > 32767) {
  604. // Static arrays are limited to 32767 values on PHP 5.6
  605. // See https://bugs.php.net/68057
  606. $staticPhpVersion = 70000;
  607. }
  608. $value = var_export($value, true);
  609. $value = str_replace($absoluteVendorPathCode, $vendorPathCode, $value);
  610. $value = str_replace($absoluteAppBaseDirCode, $appBaseDirCode, $value);
  611. $value = ltrim(preg_replace('/^ */m', ' $0$0', $value));
  612. $file .= sprintf(" public static $%s = %s;\n\n", $prop, $value);
  613. if ('files' !== $prop) {
  614. $initializer .= " \$loader->$prop = ComposerStaticInit$suffix::\$$prop;\n";
  615. }
  616. }
  617. return $file . <<<INITIALIZER
  618. public static function getInitializer(ClassLoader \$loader)
  619. {
  620. return \Closure::bind(function () use (\$loader) {
  621. $initializer
  622. }, null, ClassLoader::class);
  623. }
  624. }
  625. INITIALIZER;
  626. }
  627. protected function parseAutoloadsType(array $packageMap, $type, PackageInterface $mainPackage)
  628. {
  629. $autoloads = array();
  630. foreach ($packageMap as $item) {
  631. list($package, $installPath) = $item;
  632. $autoload = $package->getAutoload();
  633. if ($this->devMode && $package === $mainPackage) {
  634. $autoload = array_merge_recursive($autoload, $package->getDevAutoload());
  635. }
  636. // skip misconfigured packages
  637. if (!isset($autoload[$type]) || !is_array($autoload[$type])) {
  638. continue;
  639. }
  640. if (null !== $package->getTargetDir() && $package !== $mainPackage) {
  641. $installPath = substr($installPath, 0, -strlen('/'.$package->getTargetDir()));
  642. }
  643. foreach ($autoload[$type] as $namespace => $paths) {
  644. foreach ((array) $paths as $path) {
  645. if (($type === 'files' || $type === 'classmap' || $type === 'exclude-from-classmap') && $package->getTargetDir() && !is_readable($installPath.'/'.$path)) {
  646. // remove target-dir from file paths of the root package
  647. if ($package === $mainPackage) {
  648. $targetDir = str_replace('\\<dirsep\\>', '[\\\\/]', preg_quote(str_replace(array('/', '\\'), '<dirsep>', $package->getTargetDir())));
  649. $path = ltrim(preg_replace('{^'.$targetDir.'}', '', ltrim($path, '\\/')), '\\/');
  650. } else {
  651. // add target-dir from file paths that don't have it
  652. $path = $package->getTargetDir() . '/' . $path;
  653. }
  654. }
  655. if ($type === 'exclude-from-classmap') {
  656. // first escape user input
  657. $path = preg_replace('{/+}', '/', preg_quote(trim(strtr($path, '\\', '/'), '/')));
  658. // add support for wildcards * and **
  659. $path = str_replace('\\*\\*', '.+?', $path);
  660. $path = str_replace('\\*', '[^/]+?', $path);
  661. // add support for up-level relative paths
  662. $updir = null;
  663. $path = preg_replace_callback(
  664. '{^((?:(?:\\\\\\.){1,2}+/)+)}',
  665. function ($matches) use (&$updir) {
  666. if (isset($matches[1])) {
  667. // undo preg_quote for the matched string
  668. $updir = str_replace('\\.', '.', $matches[1]);
  669. }
  670. return '';
  671. },
  672. $path
  673. );
  674. if (empty($installPath)) {
  675. $installPath = strtr(getcwd(), '\\', '/');
  676. }
  677. $resolvedPath = realpath($installPath . '/' . $updir);
  678. $autoloads[] = preg_quote(strtr($resolvedPath, '\\', '/')) . '/' . $path;
  679. continue;
  680. }
  681. $relativePath = empty($installPath) ? (empty($path) ? '.' : $path) : $installPath.'/'.$path;
  682. if ($type === 'files') {
  683. $autoloads[$this->getFileIdentifier($package, $path)] = $relativePath;
  684. continue;
  685. } elseif ($type === 'classmap') {
  686. $autoloads[] = $relativePath;
  687. continue;
  688. }
  689. $autoloads[$namespace][] = $relativePath;
  690. }
  691. }
  692. }
  693. return $autoloads;
  694. }
  695. protected function getFileIdentifier(PackageInterface $package, $path)
  696. {
  697. return md5($package->getName() . ':' . $path);
  698. }
  699. /**
  700. * Sorts packages by dependency weight
  701. *
  702. * Packages of equal weight retain the original order
  703. *
  704. * @param array $packageMap
  705. * @return array
  706. */
  707. protected function sortPackageMap(array $packageMap)
  708. {
  709. $packages = array();
  710. $paths = array();
  711. $usageList = array();
  712. foreach ($packageMap as $item) {
  713. list($package, $path) = $item;
  714. $name = $package->getName();
  715. $packages[$name] = $package;
  716. $paths[$name] = $path;
  717. foreach (array_merge($package->getRequires(), $package->getDevRequires()) as $link) {
  718. $target = $link->getTarget();
  719. $usageList[$target][] = $name;
  720. }
  721. }
  722. $computing = array();
  723. $computed = array();
  724. $computeImportance = function ($name) use (&$computeImportance, &$computing, &$computed, $usageList) {
  725. // reusing computed importance
  726. if (isset($computed[$name])) {
  727. return $computed[$name];
  728. }
  729. // canceling circular dependency
  730. if (isset($computing[$name])) {
  731. return 0;
  732. }
  733. $computing[$name] = true;
  734. $weight = 0;
  735. if (isset($usageList[$name])) {
  736. foreach ($usageList[$name] as $user) {
  737. $weight -= 1 - $computeImportance($user);
  738. }
  739. }
  740. unset($computing[$name]);
  741. $computed[$name] = $weight;
  742. return $weight;
  743. };
  744. $weightList = array();
  745. foreach ($packages as $name => $package) {
  746. $weight = $computeImportance($name);
  747. $weightList[$name] = $weight;
  748. }
  749. $stable_sort = function (&$array) {
  750. static $transform, $restore;
  751. $i = 0;
  752. if (!$transform) {
  753. $transform = function (&$v, $k) use (&$i) {
  754. $v = array($v, ++$i, $k, $v);
  755. };
  756. $restore = function (&$v, $k) {
  757. $v = $v[3];
  758. };
  759. }
  760. array_walk($array, $transform);
  761. asort($array);
  762. array_walk($array, $restore);
  763. };
  764. $stable_sort($weightList);
  765. $sortedPackageMap = array();
  766. foreach (array_keys($weightList) as $name) {
  767. $sortedPackageMap[] = array($packages[$name], $paths[$name]);
  768. }
  769. return $sortedPackageMap;
  770. }
  771. /**
  772. * Copy file using stream_copy_to_stream to work around https://bugs.php.net/bug.php?id=6463
  773. *
  774. * @param string $source
  775. * @param string $target
  776. */
  777. protected function safeCopy($source, $target)
  778. {
  779. $source = fopen($source, 'r');
  780. $target = fopen($target, 'w+');
  781. stream_copy_to_stream($source, $target);
  782. fclose($source);
  783. fclose($target);
  784. }
  785. }