AutoloadGenerator.php 29 KB

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