AutoloadGenerator.php 36 KB

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