AutoloadGenerator.php 23 KB

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