AutoloadGenerator.php 27 KB

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