AutoloadGenerator.php 35 KB

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