AutoloadGenerator.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  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. foreach ($group['paths'] as $dir) {
  194. $dir = $filesystem->normalizePath($filesystem->isAbsolutePath($dir) ? $dir : $basePath.'/'.$dir);
  195. if (!is_dir($dir)) {
  196. continue;
  197. }
  198. $namespaceFilter = $namespace === '' ? null : $namespace;
  199. $classMap = $this->addClassMapCode($filesystem, $basePath, $vendorPath, $dir, $blacklist, $namespaceFilter, $classMap);
  200. }
  201. }
  202. }
  203. }
  204. foreach ($autoloads['classmap'] as $dir) {
  205. $classMap = $this->addClassMapCode($filesystem, $basePath, $vendorPath, $dir, $blacklist, null, $classMap);
  206. }
  207. ksort($classMap);
  208. foreach ($classMap as $class => $code) {
  209. $classmapFile .= ' '.var_export($class, true).' => '.$code;
  210. }
  211. $classmapFile .= ");\n";
  212. if (!$suffix) {
  213. if (!$config->get('autoloader-suffix') && is_readable($vendorPath.'/autoload.php')) {
  214. $content = file_get_contents($vendorPath.'/autoload.php');
  215. if (preg_match('{ComposerAutoloaderInit([^:\s]+)::}', $content, $match)) {
  216. $suffix = $match[1];
  217. }
  218. }
  219. if (!$suffix) {
  220. $suffix = $config->get('autoloader-suffix') ?: md5(uniqid('', true));
  221. }
  222. }
  223. file_put_contents($targetDir.'/autoload_namespaces.php', $namespacesFile);
  224. file_put_contents($targetDir.'/autoload_psr4.php', $psr4File);
  225. file_put_contents($targetDir.'/autoload_classmap.php', $classmapFile);
  226. $includePathFilePath = $targetDir.'/include_paths.php';
  227. if ($includePathFileContents = $this->getIncludePathsFile($packageMap, $filesystem, $basePath, $vendorPath, $vendorPathCode52, $appBaseDirCode)) {
  228. file_put_contents($includePathFilePath, $includePathFileContents);
  229. } elseif (file_exists($includePathFilePath)) {
  230. unlink($includePathFilePath);
  231. }
  232. $includeFilesFilePath = $targetDir.'/autoload_files.php';
  233. if ($includeFilesFileContents = $this->getIncludeFilesFile($autoloads['files'], $filesystem, $basePath, $vendorPath, $vendorPathCode52, $appBaseDirCode)) {
  234. file_put_contents($includeFilesFilePath, $includeFilesFileContents);
  235. } elseif (file_exists($includeFilesFilePath)) {
  236. unlink($includeFilesFilePath);
  237. }
  238. file_put_contents($targetDir.'/autoload_static.php', $this->getStaticFile($suffix, $targetDir, $vendorPath, $basePath, $staticPhpVersion));
  239. file_put_contents($vendorPath.'/autoload.php', $this->getAutoloadFile($vendorPathToTargetDirCode, $suffix));
  240. file_put_contents($targetDir.'/autoload_real.php', $this->getAutoloadRealFile(true, (bool) $includePathFileContents, $targetDirLoader, (bool) $includeFilesFileContents, $vendorPathCode, $appBaseDirCode, $suffix, $useGlobalIncludePath, $prependAutoloader, $staticPhpVersion));
  241. $this->safeCopy(__DIR__.'/ClassLoader.php', $targetDir.'/ClassLoader.php');
  242. $this->safeCopy(__DIR__.'/../../../LICENSE', $targetDir.'/LICENSE');
  243. if ($this->runScripts) {
  244. $this->eventDispatcher->dispatchScript(ScriptEvents::POST_AUTOLOAD_DUMP, $this->devMode, array(), array(
  245. 'optimize' => (bool) $scanPsr0Packages,
  246. ));
  247. }
  248. }
  249. private function addClassMapCode($filesystem, $basePath, $vendorPath, $dir, $blacklist = null, $namespaceFilter = null, array $classMap = array())
  250. {
  251. foreach ($this->generateClassMap($dir, $blacklist, $namespaceFilter) as $class => $path) {
  252. $pathCode = $this->getPathCode($filesystem, $basePath, $vendorPath, $path).",\n";
  253. if (!isset($classMap[$class])) {
  254. $classMap[$class] = $pathCode;
  255. } elseif ($this->io && $classMap[$class] !== $pathCode && !preg_match('{/(test|fixture|example|stub)s?/}i', strtr($classMap[$class].' '.$path, '\\', '/'))) {
  256. $this->io->writeError(
  257. '<warning>Warning: Ambiguous class resolution, "'.$class.'"'.
  258. ' was found in both "'.str_replace(array('$vendorDir . \'', "',\n"), array($vendorPath, ''), $classMap[$class]).'" and "'.$path.'", the first will be used.</warning>'
  259. );
  260. }
  261. }
  262. return $classMap;
  263. }
  264. private function generateClassMap($dir, $blacklist = null, $namespaceFilter = null, $showAmbiguousWarning = true)
  265. {
  266. return ClassMapGenerator::createMap($dir, $blacklist, $showAmbiguousWarning ? $this->io : null, $namespaceFilter);
  267. }
  268. public function buildPackageMap(InstallationManager $installationManager, PackageInterface $mainPackage, array $packages)
  269. {
  270. // build package => install path map
  271. $packageMap = array(array($mainPackage, ''));
  272. foreach ($packages as $package) {
  273. if ($package instanceof AliasPackage) {
  274. continue;
  275. }
  276. $this->validatePackage($package);
  277. $packageMap[] = array(
  278. $package,
  279. $installationManager->getInstallPath($package),
  280. );
  281. }
  282. return $packageMap;
  283. }
  284. /**
  285. * @param PackageInterface $package
  286. *
  287. * @throws \InvalidArgumentException Throws an exception, if the package has illegal settings.
  288. */
  289. protected function validatePackage(PackageInterface $package)
  290. {
  291. $autoload = $package->getAutoload();
  292. if (!empty($autoload['psr-4']) && null !== $package->getTargetDir()) {
  293. $name = $package->getName();
  294. $package->getTargetDir();
  295. throw new \InvalidArgumentException("PSR-4 autoloading is incompatible with the target-dir property, remove the target-dir in package '$name'.");
  296. }
  297. if (!empty($autoload['psr-4'])) {
  298. foreach ($autoload['psr-4'] as $namespace => $dirs) {
  299. if ($namespace !== '' && '\\' !== substr($namespace, -1)) {
  300. throw new \InvalidArgumentException("psr-4 namespaces must end with a namespace separator, '$namespace' does not, use '$namespace\\'.");
  301. }
  302. }
  303. }
  304. }
  305. /**
  306. * Compiles an ordered list of namespace => path mappings
  307. *
  308. * @param array $packageMap array of array(package, installDir-relative-to-composer.json)
  309. * @param PackageInterface $mainPackage root package instance
  310. * @return array array('psr-0' => array('Ns\\Foo' => array('installDir')))
  311. */
  312. public function parseAutoloads(array $packageMap, PackageInterface $mainPackage)
  313. {
  314. $mainPackageMap = array_shift($packageMap);
  315. $sortedPackageMap = $this->sortPackageMap($packageMap);
  316. $sortedPackageMap[] = $mainPackageMap;
  317. array_unshift($packageMap, $mainPackageMap);
  318. $psr0 = $this->parseAutoloadsType($packageMap, 'psr-0', $mainPackage);
  319. $psr4 = $this->parseAutoloadsType($packageMap, 'psr-4', $mainPackage);
  320. $classmap = $this->parseAutoloadsType(array_reverse($sortedPackageMap), 'classmap', $mainPackage);
  321. $files = $this->parseAutoloadsType($sortedPackageMap, 'files', $mainPackage);
  322. $exclude = $this->parseAutoloadsType($sortedPackageMap, 'exclude-from-classmap', $mainPackage);
  323. krsort($psr0);
  324. krsort($psr4);
  325. return array(
  326. 'psr-0' => $psr0,
  327. 'psr-4' => $psr4,
  328. 'classmap' => $classmap,
  329. 'files' => $files,
  330. 'exclude-from-classmap' => $exclude,
  331. );
  332. }
  333. /**
  334. * Registers an autoloader based on an autoload map returned by parseAutoloads
  335. *
  336. * @param array $autoloads see parseAutoloads return value
  337. * @return ClassLoader
  338. */
  339. public function createLoader(array $autoloads)
  340. {
  341. $loader = new ClassLoader();
  342. if (isset($autoloads['psr-0'])) {
  343. foreach ($autoloads['psr-0'] as $namespace => $path) {
  344. $loader->add($namespace, $path);
  345. }
  346. }
  347. if (isset($autoloads['psr-4'])) {
  348. foreach ($autoloads['psr-4'] as $namespace => $path) {
  349. $loader->addPsr4($namespace, $path);
  350. }
  351. }
  352. if (isset($autoloads['classmap'])) {
  353. foreach ($autoloads['classmap'] as $dir) {
  354. try {
  355. $loader->addClassMap($this->generateClassMap($dir, null, null, false));
  356. } catch (\RuntimeException $e) {
  357. $this->io->writeError('<warning>'.$e->getMessage().'</warning>');
  358. }
  359. }
  360. }
  361. return $loader;
  362. }
  363. protected function getIncludePathsFile(array $packageMap, Filesystem $filesystem, $basePath, $vendorPath, $vendorPathCode, $appBaseDirCode)
  364. {
  365. $includePaths = array();
  366. foreach ($packageMap as $item) {
  367. list($package, $installPath) = $item;
  368. if (null !== $package->getTargetDir() && strlen($package->getTargetDir()) > 0) {
  369. $installPath = substr($installPath, 0, -strlen('/'.$package->getTargetDir()));
  370. }
  371. foreach ($package->getIncludePaths() as $includePath) {
  372. $includePath = trim($includePath, '/');
  373. $includePaths[] = empty($installPath) ? $includePath : $installPath.'/'.$includePath;
  374. }
  375. }
  376. if (!$includePaths) {
  377. return;
  378. }
  379. $includePathsCode = '';
  380. foreach ($includePaths as $path) {
  381. $includePathsCode .= " " . $this->getPathCode($filesystem, $basePath, $vendorPath, $path) . ",\n";
  382. }
  383. return <<<EOF
  384. <?php
  385. // include_paths.php @generated by Composer
  386. \$vendorDir = $vendorPathCode;
  387. \$baseDir = $appBaseDirCode;
  388. return array(
  389. $includePathsCode);
  390. EOF;
  391. }
  392. protected function getIncludeFilesFile(array $files, Filesystem $filesystem, $basePath, $vendorPath, $vendorPathCode, $appBaseDirCode)
  393. {
  394. $filesCode = '';
  395. foreach ($files as $fileIdentifier => $functionFile) {
  396. $filesCode .= ' ' . var_export($fileIdentifier, true) . ' => '
  397. . $this->getPathCode($filesystem, $basePath, $vendorPath, $functionFile) . ",\n";
  398. }
  399. if (!$filesCode) {
  400. return false;
  401. }
  402. return <<<EOF
  403. <?php
  404. // autoload_files.php @generated by Composer
  405. \$vendorDir = $vendorPathCode;
  406. \$baseDir = $appBaseDirCode;
  407. return array(
  408. $filesCode);
  409. EOF;
  410. }
  411. protected function getPathCode(Filesystem $filesystem, $basePath, $vendorPath, $path)
  412. {
  413. if (!$filesystem->isAbsolutePath($path)) {
  414. $path = $basePath . '/' . $path;
  415. }
  416. $path = $filesystem->normalizePath($path);
  417. $baseDir = '';
  418. if (strpos($path.'/', $vendorPath.'/') === 0) {
  419. $path = substr($path, strlen($vendorPath));
  420. $baseDir = '$vendorDir';
  421. if ($path !== false) {
  422. $baseDir .= " . ";
  423. }
  424. } else {
  425. $path = $filesystem->normalizePath($filesystem->findShortestPath($basePath, $path, true));
  426. if (!$filesystem->isAbsolutePath($path)) {
  427. $baseDir = '$baseDir . ';
  428. $path = '/' . $path;
  429. }
  430. }
  431. if (preg_match('/\.phar$/', $path)) {
  432. $baseDir = "'phar://' . " . $baseDir;
  433. }
  434. return $baseDir . (($path !== false) ? var_export($path, true) : "");
  435. }
  436. protected function getAutoloadFile($vendorPathToTargetDirCode, $suffix)
  437. {
  438. $lastChar = $vendorPathToTargetDirCode[strlen($vendorPathToTargetDirCode)-1];
  439. if ("'" === $lastChar || '"' === $lastChar) {
  440. $vendorPathToTargetDirCode = substr($vendorPathToTargetDirCode, 0, -1).'/autoload_real.php'.$lastChar;
  441. } else {
  442. $vendorPathToTargetDirCode .= " . '/autoload_real.php'";
  443. }
  444. return <<<AUTOLOAD
  445. <?php
  446. // autoload.php @generated by Composer
  447. require_once $vendorPathToTargetDirCode;
  448. return ComposerAutoloaderInit$suffix::getLoader();
  449. AUTOLOAD;
  450. }
  451. protected function getAutoloadRealFile($useClassMap, $useIncludePath, $targetDirLoader, $useIncludeFiles, $vendorPathCode, $appBaseDirCode, $suffix, $useGlobalIncludePath, $prependAutoloader, $staticPhpVersion = 70000)
  452. {
  453. $file = <<<HEADER
  454. <?php
  455. // autoload_real.php @generated by Composer
  456. class ComposerAutoloaderInit$suffix
  457. {
  458. private static \$loader;
  459. public static function loadClassLoader(\$class)
  460. {
  461. if ('Composer\\Autoload\\ClassLoader' === \$class) {
  462. require __DIR__ . '/ClassLoader.php';
  463. }
  464. }
  465. public static function getLoader()
  466. {
  467. if (null !== self::\$loader) {
  468. return self::\$loader;
  469. }
  470. spl_autoload_register(array('ComposerAutoloaderInit$suffix', 'loadClassLoader'), true, $prependAutoloader);
  471. self::\$loader = \$loader = new \\Composer\\Autoload\\ClassLoader();
  472. spl_autoload_unregister(array('ComposerAutoloaderInit$suffix', 'loadClassLoader'));
  473. HEADER;
  474. if ($useIncludePath) {
  475. $file .= <<<'INCLUDE_PATH'
  476. $includePaths = require __DIR__ . '/include_paths.php';
  477. array_push($includePaths, get_include_path());
  478. set_include_path(implode(PATH_SEPARATOR, $includePaths));
  479. INCLUDE_PATH;
  480. }
  481. $file .= <<<STATIC_INIT
  482. \$useStaticLoader = PHP_VERSION_ID >= $staticPhpVersion && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
  483. if (\$useStaticLoader) {
  484. require_once __DIR__ . '/autoload_static.php';
  485. call_user_func(\Composer\Autoload\ComposerStaticInit$suffix::getInitializer(\$loader));
  486. } else {
  487. STATIC_INIT;
  488. if (!$this->classMapAuthoritative) {
  489. $file .= <<<'PSR04'
  490. $map = require __DIR__ . '/autoload_namespaces.php';
  491. foreach ($map as $namespace => $path) {
  492. $loader->set($namespace, $path);
  493. }
  494. $map = require __DIR__ . '/autoload_psr4.php';
  495. foreach ($map as $namespace => $path) {
  496. $loader->setPsr4($namespace, $path);
  497. }
  498. PSR04;
  499. }
  500. if ($useClassMap) {
  501. $file .= <<<'CLASSMAP'
  502. $classMap = require __DIR__ . '/autoload_classmap.php';
  503. if ($classMap) {
  504. $loader->addClassMap($classMap);
  505. }
  506. CLASSMAP;
  507. }
  508. $file .= " }\n\n";
  509. if ($this->classMapAuthoritative) {
  510. $file .= <<<'CLASSMAPAUTHORITATIVE'
  511. $loader->setClassMapAuthoritative(true);
  512. CLASSMAPAUTHORITATIVE;
  513. }
  514. if ($useGlobalIncludePath) {
  515. $file .= <<<'INCLUDEPATH'
  516. $loader->setUseIncludePath(true);
  517. INCLUDEPATH;
  518. }
  519. if ($targetDirLoader) {
  520. $file .= <<<REGISTER_TARGET_DIR_AUTOLOAD
  521. spl_autoload_register(array('ComposerAutoloaderInit$suffix', 'autoload'), true, true);
  522. REGISTER_TARGET_DIR_AUTOLOAD;
  523. }
  524. $file .= <<<REGISTER_LOADER
  525. \$loader->register($prependAutoloader);
  526. REGISTER_LOADER;
  527. if ($useIncludeFiles) {
  528. $file .= <<<INCLUDE_FILES
  529. if (\$useStaticLoader) {
  530. \$includeFiles = Composer\Autoload\ComposerStaticInit$suffix::\$files;
  531. } else {
  532. \$includeFiles = require __DIR__ . '/autoload_files.php';
  533. }
  534. foreach (\$includeFiles as \$fileIdentifier => \$file) {
  535. composerRequire$suffix(\$fileIdentifier, \$file);
  536. }
  537. INCLUDE_FILES;
  538. }
  539. $file .= <<<METHOD_FOOTER
  540. return \$loader;
  541. }
  542. METHOD_FOOTER;
  543. $file .= $targetDirLoader;
  544. if ($useIncludeFiles) {
  545. return $file . <<<FOOTER
  546. }
  547. function composerRequire$suffix(\$fileIdentifier, \$file)
  548. {
  549. if (empty(\$GLOBALS['__composer_autoload_files'][\$fileIdentifier])) {
  550. require \$file;
  551. \$GLOBALS['__composer_autoload_files'][\$fileIdentifier] = true;
  552. }
  553. }
  554. FOOTER;
  555. }
  556. return $file . <<<FOOTER
  557. }
  558. FOOTER;
  559. }
  560. protected function getStaticFile($suffix, $targetDir, $vendorPath, $basePath, &$staticPhpVersion)
  561. {
  562. $staticPhpVersion = 50600;
  563. $file = <<<HEADER
  564. <?php
  565. // autoload_static.php @generated by Composer
  566. namespace Composer\Autoload;
  567. class ComposerStaticInit$suffix
  568. {
  569. HEADER;
  570. $loader = new ClassLoader();
  571. $map = require $targetDir . '/autoload_namespaces.php';
  572. foreach ($map as $namespace => $path) {
  573. $loader->set($namespace, $path);
  574. }
  575. $map = require $targetDir . '/autoload_psr4.php';
  576. foreach ($map as $namespace => $path) {
  577. $loader->setPsr4($namespace, $path);
  578. }
  579. $classMap = require $targetDir . '/autoload_classmap.php';
  580. if ($classMap) {
  581. $loader->addClassMap($classMap);
  582. }
  583. $filesystem = new Filesystem();
  584. $vendorPathCode = ' => ' . $filesystem->findShortestPathCode(realpath($targetDir), $vendorPath, true, true) . " . '/";
  585. $appBaseDirCode = ' => ' . $filesystem->findShortestPathCode(realpath($targetDir), $basePath, true, true) . " . '/";
  586. $absoluteVendorPathCode = ' => ' . substr(var_export(rtrim($vendorDir, '\\/') . '/', true), 0, -1);
  587. $absoluteAppBaseDirCode = ' => ' . substr(var_export(rtrim($baseDir, '\\/') . '/', true), 0, -1);
  588. $initializer = '';
  589. $prefix = "\0Composer\Autoload\ClassLoader\0";
  590. $prefixLen = strlen($prefix);
  591. if (file_exists($targetDir . '/autoload_files.php')) {
  592. $maps = array('files' => require $targetDir . '/autoload_files.php');
  593. } else {
  594. $maps = array();
  595. }
  596. foreach ((array) $loader as $prop => $value) {
  597. if ($value && 0 === strpos($prop, $prefix)) {
  598. $maps[substr($prop, $prefixLen)] = $value;
  599. }
  600. }
  601. foreach ($maps as $prop => $value) {
  602. if (count($value) > 32767) {
  603. // Static arrays are limited to 32767 values on PHP 5.6
  604. // See https://bugs.php.net/68057
  605. $staticPhpVersion = 70000;
  606. }
  607. $value = var_export($value, true);
  608. $value = str_replace($absoluteVendorPathCode, $vendorPathCode, $value);
  609. $value = str_replace($absoluteAppBaseDirCode, $appBaseDirCode, $value);
  610. $value = ltrim(preg_replace('/^ */m', ' $0$0', $value));
  611. $file .= sprintf(" public static $%s = %s;\n\n", $prop, $value);
  612. if ('files' !== $prop) {
  613. $initializer .= " \$loader->$prop = ComposerStaticInit$suffix::\$$prop;\n";
  614. }
  615. }
  616. return $file . <<<INITIALIZER
  617. public static function getInitializer(ClassLoader \$loader)
  618. {
  619. return \Closure::bind(function () use (\$loader) {
  620. $initializer
  621. }, null, ClassLoader::class);
  622. }
  623. }
  624. INITIALIZER;
  625. }
  626. protected function parseAutoloadsType(array $packageMap, $type, PackageInterface $mainPackage)
  627. {
  628. $autoloads = array();
  629. foreach ($packageMap as $item) {
  630. list($package, $installPath) = $item;
  631. $autoload = $package->getAutoload();
  632. if ($this->devMode && $package === $mainPackage) {
  633. $autoload = array_merge_recursive($autoload, $package->getDevAutoload());
  634. }
  635. // skip misconfigured packages
  636. if (!isset($autoload[$type]) || !is_array($autoload[$type])) {
  637. continue;
  638. }
  639. if (null !== $package->getTargetDir() && $package !== $mainPackage) {
  640. $installPath = substr($installPath, 0, -strlen('/'.$package->getTargetDir()));
  641. }
  642. foreach ($autoload[$type] as $namespace => $paths) {
  643. foreach ((array) $paths as $path) {
  644. if (($type === 'files' || $type === 'classmap' || $type === 'exclude-from-classmap') && $package->getTargetDir() && !is_readable($installPath.'/'.$path)) {
  645. // remove target-dir from file paths of the root package
  646. if ($package === $mainPackage) {
  647. $targetDir = str_replace('\\<dirsep\\>', '[\\\\/]', preg_quote(str_replace(array('/', '\\'), '<dirsep>', $package->getTargetDir())));
  648. $path = ltrim(preg_replace('{^'.$targetDir.'}', '', ltrim($path, '\\/')), '\\/');
  649. } else {
  650. // add target-dir from file paths that don't have it
  651. $path = $package->getTargetDir() . '/' . $path;
  652. }
  653. }
  654. if ($type === 'exclude-from-classmap') {
  655. // first escape user input
  656. $path = preg_replace('{/+}', '/', preg_quote(trim(strtr($path, '\\', '/'), '/')));
  657. // add support for wildcards * and **
  658. $path = str_replace('\\*\\*', '.+?', $path);
  659. $path = str_replace('\\*', '[^/]+?', $path);
  660. // add support for up-level relative paths
  661. $updir = null;
  662. $path = preg_replace_callback(
  663. '{^((?:(?:\\\\\\.){1,2}+/)+)}',
  664. function ($matches) use (&$updir) {
  665. if (isset($matches[1])) {
  666. // undo preg_quote for the matched string
  667. $updir = str_replace('\\.', '.', $matches[1]);
  668. }
  669. return '';
  670. },
  671. $path
  672. );
  673. if (empty($installPath)) {
  674. $installPath = strtr(getcwd(), '\\', '/');
  675. }
  676. $resolvedPath = realpath($installPath . '/' . $updir);
  677. $autoloads[] = preg_quote(strtr($resolvedPath, '\\', '/')) . '/' . $path;
  678. continue;
  679. }
  680. $relativePath = empty($installPath) ? (empty($path) ? '.' : $path) : $installPath.'/'.$path;
  681. if ($type === 'files') {
  682. $autoloads[$this->getFileIdentifier($package, $path)] = $relativePath;
  683. continue;
  684. } elseif ($type === 'classmap') {
  685. $autoloads[] = $relativePath;
  686. continue;
  687. }
  688. $autoloads[$namespace][] = $relativePath;
  689. }
  690. }
  691. }
  692. return $autoloads;
  693. }
  694. protected function getFileIdentifier(PackageInterface $package, $path)
  695. {
  696. return md5($package->getName() . ':' . $path);
  697. }
  698. /**
  699. * Sorts packages by dependency weight
  700. *
  701. * Packages of equal weight retain the original order
  702. *
  703. * @param array $packageMap
  704. * @return array
  705. */
  706. protected function sortPackageMap(array $packageMap)
  707. {
  708. $packages = array();
  709. $paths = array();
  710. $usageList = array();
  711. foreach ($packageMap as $item) {
  712. list($package, $path) = $item;
  713. $name = $package->getName();
  714. $packages[$name] = $package;
  715. $paths[$name] = $path;
  716. foreach (array_merge($package->getRequires(), $package->getDevRequires()) as $link) {
  717. $target = $link->getTarget();
  718. $usageList[$target][] = $name;
  719. }
  720. }
  721. $computing = array();
  722. $computed = array();
  723. $computeImportance = function ($name) use (&$computeImportance, &$computing, &$computed, $usageList) {
  724. // reusing computed importance
  725. if (isset($computed[$name])) {
  726. return $computed[$name];
  727. }
  728. // canceling circular dependency
  729. if (isset($computing[$name])) {
  730. return 0;
  731. }
  732. $computing[$name] = true;
  733. $weight = 0;
  734. if (isset($usageList[$name])) {
  735. foreach ($usageList[$name] as $user) {
  736. $weight -= 1 - $computeImportance($user);
  737. }
  738. }
  739. unset($computing[$name]);
  740. $computed[$name] = $weight;
  741. return $weight;
  742. };
  743. $weightList = array();
  744. foreach ($packages as $name => $package) {
  745. $weight = $computeImportance($name);
  746. $weightList[$name] = $weight;
  747. }
  748. $stable_sort = function (&$array) {
  749. static $transform, $restore;
  750. $i = 0;
  751. if (!$transform) {
  752. $transform = function (&$v, $k) use (&$i) {
  753. $v = array($v, ++$i, $k, $v);
  754. };
  755. $restore = function (&$v, $k) {
  756. $v = $v[3];
  757. };
  758. }
  759. array_walk($array, $transform);
  760. asort($array);
  761. array_walk($array, $restore);
  762. };
  763. $stable_sort($weightList);
  764. $sortedPackageMap = array();
  765. foreach (array_keys($weightList) as $name) {
  766. $sortedPackageMap[] = array($packages[$name], $paths[$name]);
  767. }
  768. return $sortedPackageMap;
  769. }
  770. /**
  771. * Copy file using stream_copy_to_stream to work around https://bugs.php.net/bug.php?id=6463
  772. *
  773. * @param string $source
  774. * @param string $target
  775. */
  776. protected function safeCopy($source, $target)
  777. {
  778. $source = fopen($source, 'r');
  779. $target = fopen($target, 'w+');
  780. stream_copy_to_stream($source, $target);
  781. fclose($source);
  782. fclose($target);
  783. }
  784. }