AutoloadGenerator.php 32 KB

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