AutoloadGenerator.php 23 KB

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