AutoloadGenerator.php 35 KB

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