AutoloadGenerator.php 34 KB

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