AutoloadGenerator.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  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. if (is_readable($vendorPath.'/autoload.php')) {
  178. $content = file_get_contents($vendorPath.'/autoload.php');
  179. if (preg_match('{ComposerAutoloaderInit([^:\s]+)::}', $content, $match)) {
  180. $suffix = $match[1];
  181. }
  182. }
  183. if (!$suffix) {
  184. $suffix = $config->get('autoloader-suffix') ?: md5(uniqid('', true));
  185. }
  186. }
  187. file_put_contents($targetDir.'/autoload_namespaces.php', $namespacesFile);
  188. file_put_contents($targetDir.'/autoload_psr4.php', $psr4File);
  189. file_put_contents($targetDir.'/autoload_classmap.php', $classmapFile);
  190. if ($includePathFile = $this->getIncludePathsFile($packageMap, $filesystem, $basePath, $vendorPath, $vendorPathCode52, $appBaseDirCode)) {
  191. file_put_contents($targetDir.'/include_paths.php', $includePathFile);
  192. }
  193. if ($includeFilesFile = $this->getIncludeFilesFile($autoloads['files'], $filesystem, $basePath, $vendorPath, $vendorPathCode52, $appBaseDirCode)) {
  194. file_put_contents($targetDir.'/autoload_files.php', $includeFilesFile);
  195. }
  196. file_put_contents($vendorPath.'/autoload.php', $this->getAutoloadFile($vendorPathToTargetDirCode, $suffix));
  197. file_put_contents($targetDir.'/autoload_real.php', $this->getAutoloadRealFile(true, (bool) $includePathFile, $targetDirLoader, (bool) $includeFilesFile, $vendorPathCode, $appBaseDirCode, $suffix, $useGlobalIncludePath, $prependAutoloader, $classMapAuthoritative));
  198. // use stream_copy_to_stream instead of copy
  199. // to work around https://bugs.php.net/bug.php?id=64634
  200. $sourceLoader = fopen(__DIR__.'/ClassLoader.php', 'r');
  201. $targetLoader = fopen($targetDir.'/ClassLoader.php', 'w+');
  202. stream_copy_to_stream($sourceLoader, $targetLoader);
  203. fclose($sourceLoader);
  204. fclose($targetLoader);
  205. unset($sourceLoader, $targetLoader);
  206. $this->eventDispatcher->dispatchScript(ScriptEvents::POST_AUTOLOAD_DUMP, $this->devMode, array(), array(
  207. 'optimize' => (bool) $scanPsr0Packages,
  208. ));
  209. }
  210. public function buildPackageMap(InstallationManager $installationManager, PackageInterface $mainPackage, array $packages)
  211. {
  212. // build package => install path map
  213. $packageMap = array(array($mainPackage, ''));
  214. foreach ($packages as $package) {
  215. if ($package instanceof AliasPackage) {
  216. continue;
  217. }
  218. $this->validatePackage($package);
  219. $packageMap[] = array(
  220. $package,
  221. $installationManager->getInstallPath($package),
  222. );
  223. }
  224. return $packageMap;
  225. }
  226. /**
  227. * @param PackageInterface $package
  228. *
  229. * @throws \InvalidArgumentException Throws an exception, if the package has illegal settings.
  230. */
  231. protected function validatePackage(PackageInterface $package)
  232. {
  233. $autoload = $package->getAutoload();
  234. if (!empty($autoload['psr-4']) && null !== $package->getTargetDir()) {
  235. $name = $package->getName();
  236. $package->getTargetDir();
  237. throw new \InvalidArgumentException("PSR-4 autoloading is incompatible with the target-dir property, remove the target-dir in package '$name'.");
  238. }
  239. if (!empty($autoload['psr-4'])) {
  240. foreach ($autoload['psr-4'] as $namespace => $dirs) {
  241. if ($namespace !== '' && '\\' !== substr($namespace, -1)) {
  242. throw new \InvalidArgumentException("psr-4 namespaces must end with a namespace separator, '$namespace' does not, use '$namespace\\'.");
  243. }
  244. }
  245. }
  246. }
  247. /**
  248. * Compiles an ordered list of namespace => path mappings
  249. *
  250. * @param array $packageMap array of array(package, installDir-relative-to-composer.json)
  251. * @param PackageInterface $mainPackage root package instance
  252. * @return array array('psr-0' => array('Ns\\Foo' => array('installDir')))
  253. */
  254. public function parseAutoloads(array $packageMap, PackageInterface $mainPackage)
  255. {
  256. $mainPackageMap = array_shift($packageMap);
  257. $sortedPackageMap = $this->sortPackageMap($packageMap);
  258. $sortedPackageMap[] = $mainPackageMap;
  259. array_unshift($packageMap, $mainPackageMap);
  260. $psr0 = $this->parseAutoloadsType($packageMap, 'psr-0', $mainPackage);
  261. $psr4 = $this->parseAutoloadsType($packageMap, 'psr-4', $mainPackage);
  262. $classmap = $this->parseAutoloadsType($sortedPackageMap, 'classmap', $mainPackage);
  263. $files = $this->parseAutoloadsType($sortedPackageMap, 'files', $mainPackage);
  264. krsort($psr0);
  265. krsort($psr4);
  266. return array('psr-0' => $psr0, 'psr-4' => $psr4, 'classmap' => $classmap, 'files' => $files);
  267. }
  268. /**
  269. * Registers an autoloader based on an autoload map returned by parseAutoloads
  270. *
  271. * @param array $autoloads see parseAutoloads return value
  272. * @return ClassLoader
  273. */
  274. public function createLoader(array $autoloads)
  275. {
  276. $loader = new ClassLoader();
  277. if (isset($autoloads['psr-0'])) {
  278. foreach ($autoloads['psr-0'] as $namespace => $path) {
  279. $loader->add($namespace, $path);
  280. }
  281. }
  282. if (isset($autoloads['psr-4'])) {
  283. foreach ($autoloads['psr-4'] as $namespace => $path) {
  284. $loader->addPsr4($namespace, $path);
  285. }
  286. }
  287. return $loader;
  288. }
  289. protected function getIncludePathsFile(array $packageMap, Filesystem $filesystem, $basePath, $vendorPath, $vendorPathCode, $appBaseDirCode)
  290. {
  291. $includePaths = array();
  292. foreach ($packageMap as $item) {
  293. list($package, $installPath) = $item;
  294. if (null !== $package->getTargetDir() && strlen($package->getTargetDir()) > 0) {
  295. $installPath = substr($installPath, 0, -strlen('/'.$package->getTargetDir()));
  296. }
  297. foreach ($package->getIncludePaths() as $includePath) {
  298. $includePath = trim($includePath, '/');
  299. $includePaths[] = empty($installPath) ? $includePath : $installPath.'/'.$includePath;
  300. }
  301. }
  302. if (!$includePaths) {
  303. return;
  304. }
  305. $includePathsCode = '';
  306. foreach ($includePaths as $path) {
  307. $includePathsCode .= " " . $this->getPathCode($filesystem, $basePath, $vendorPath, $path) . ",\n";
  308. }
  309. return <<<EOF
  310. <?php
  311. // include_paths.php @generated by Composer
  312. \$vendorDir = $vendorPathCode;
  313. \$baseDir = $appBaseDirCode;
  314. return array(
  315. $includePathsCode);
  316. EOF;
  317. }
  318. protected function getIncludeFilesFile(array $files, Filesystem $filesystem, $basePath, $vendorPath, $vendorPathCode, $appBaseDirCode)
  319. {
  320. $filesCode = '';
  321. foreach ($files as $functionFile) {
  322. $filesCode .= ' '.$this->getPathCode($filesystem, $basePath, $vendorPath, $functionFile).",\n";
  323. }
  324. if (!$filesCode) {
  325. return false;
  326. }
  327. return <<<EOF
  328. <?php
  329. // autoload_files.php @generated by Composer
  330. \$vendorDir = $vendorPathCode;
  331. \$baseDir = $appBaseDirCode;
  332. return array(
  333. $filesCode);
  334. EOF;
  335. }
  336. protected function getPathCode(Filesystem $filesystem, $basePath, $vendorPath, $path)
  337. {
  338. if (!$filesystem->isAbsolutePath($path)) {
  339. $path = $basePath . '/' . $path;
  340. }
  341. $path = $filesystem->normalizePath($path);
  342. $baseDir = '';
  343. if (strpos($path.'/', $vendorPath.'/') === 0) {
  344. $path = substr($path, strlen($vendorPath));
  345. $baseDir = '$vendorDir';
  346. if ($path !== false) {
  347. $baseDir .= " . ";
  348. }
  349. } else {
  350. $path = $filesystem->normalizePath($filesystem->findShortestPath($basePath, $path, true));
  351. if (!$filesystem->isAbsolutePath($path)) {
  352. $baseDir = '$baseDir . ';
  353. $path = '/' . $path;
  354. }
  355. }
  356. if (preg_match('/\.phar$/', $path)) {
  357. $baseDir = "'phar://' . " . $baseDir;
  358. }
  359. return $baseDir . (($path !== false) ? var_export($path, true) : "");
  360. }
  361. protected function getAutoloadFile($vendorPathToTargetDirCode, $suffix)
  362. {
  363. return <<<AUTOLOAD
  364. <?php
  365. // autoload.php @generated by Composer
  366. require_once $vendorPathToTargetDirCode . '/autoload_real.php';
  367. return ComposerAutoloaderInit$suffix::getLoader();
  368. AUTOLOAD;
  369. }
  370. protected function getAutoloadRealFile($useClassMap, $useIncludePath, $targetDirLoader, $useIncludeFiles, $vendorPathCode, $appBaseDirCode, $suffix, $useGlobalIncludePath, $prependAutoloader, $classMapAuthoritative)
  371. {
  372. // TODO the class ComposerAutoloaderInit should be revert to a closure
  373. // when APC has been fixed:
  374. // - https://github.com/composer/composer/issues/959
  375. // - https://bugs.php.net/bug.php?id=52144
  376. // - https://bugs.php.net/bug.php?id=61576
  377. // - https://bugs.php.net/bug.php?id=59298
  378. $file = <<<HEADER
  379. <?php
  380. // autoload_real.php @generated by Composer
  381. class ComposerAutoloaderInit$suffix
  382. {
  383. private static \$loader;
  384. public static function loadClassLoader(\$class)
  385. {
  386. if ('Composer\\Autoload\\ClassLoader' === \$class) {
  387. require __DIR__ . '/ClassLoader.php';
  388. }
  389. }
  390. public static function getLoader()
  391. {
  392. if (null !== self::\$loader) {
  393. return self::\$loader;
  394. }
  395. spl_autoload_register(array('ComposerAutoloaderInit$suffix', 'loadClassLoader'), true, $prependAutoloader);
  396. self::\$loader = \$loader = new \\Composer\\Autoload\\ClassLoader();
  397. spl_autoload_unregister(array('ComposerAutoloaderInit$suffix', 'loadClassLoader'));
  398. HEADER;
  399. if ($useIncludePath) {
  400. $file .= <<<'INCLUDE_PATH'
  401. $includePaths = require __DIR__ . '/include_paths.php';
  402. array_push($includePaths, get_include_path());
  403. set_include_path(join(PATH_SEPARATOR, $includePaths));
  404. INCLUDE_PATH;
  405. }
  406. $file .= <<<'PSR0'
  407. $map = require __DIR__ . '/autoload_namespaces.php';
  408. foreach ($map as $namespace => $path) {
  409. $loader->set($namespace, $path);
  410. }
  411. PSR0;
  412. $file .= <<<'PSR4'
  413. $map = require __DIR__ . '/autoload_psr4.php';
  414. foreach ($map as $namespace => $path) {
  415. $loader->setPsr4($namespace, $path);
  416. }
  417. PSR4;
  418. if ($useClassMap) {
  419. $file .= <<<'CLASSMAP'
  420. $classMap = require __DIR__ . '/autoload_classmap.php';
  421. if ($classMap) {
  422. $loader->addClassMap($classMap);
  423. }
  424. CLASSMAP;
  425. }
  426. if ($classMapAuthoritative) {
  427. $file .= <<<'CLASSMAPAUTHORITATIVE'
  428. $loader->setClassMapAuthoritative(true);
  429. CLASSMAPAUTHORITATIVE;
  430. }
  431. if ($useGlobalIncludePath) {
  432. $file .= <<<'INCLUDEPATH'
  433. $loader->setUseIncludePath(true);
  434. INCLUDEPATH;
  435. }
  436. if ($targetDirLoader) {
  437. $file .= <<<REGISTER_AUTOLOAD
  438. spl_autoload_register(array('ComposerAutoloaderInit$suffix', 'autoload'), true, true);
  439. REGISTER_AUTOLOAD;
  440. }
  441. $file .= <<<REGISTER_LOADER
  442. \$loader->register($prependAutoloader);
  443. REGISTER_LOADER;
  444. if ($useIncludeFiles) {
  445. $file .= <<<INCLUDE_FILES
  446. \$includeFiles = require __DIR__ . '/autoload_files.php';
  447. foreach (\$includeFiles as \$file) {
  448. composerRequire$suffix(\$file);
  449. }
  450. INCLUDE_FILES;
  451. }
  452. $file .= <<<METHOD_FOOTER
  453. return \$loader;
  454. }
  455. METHOD_FOOTER;
  456. $file .= $targetDirLoader;
  457. return $file . <<<FOOTER
  458. }
  459. function composerRequire$suffix(\$file)
  460. {
  461. require \$file;
  462. }
  463. FOOTER;
  464. }
  465. protected function parseAutoloadsType(array $packageMap, $type, PackageInterface $mainPackage)
  466. {
  467. $autoloads = array();
  468. foreach ($packageMap as $item) {
  469. list($package, $installPath) = $item;
  470. $autoload = $package->getAutoload();
  471. if ($this->devMode && $package === $mainPackage) {
  472. $autoload = array_merge_recursive($autoload, $package->getDevAutoload());
  473. }
  474. // skip misconfigured packages
  475. if (!isset($autoload[$type]) || !is_array($autoload[$type])) {
  476. continue;
  477. }
  478. if (null !== $package->getTargetDir() && $package !== $mainPackage) {
  479. $installPath = substr($installPath, 0, -strlen('/'.$package->getTargetDir()));
  480. }
  481. foreach ($autoload[$type] as $namespace => $paths) {
  482. foreach ((array) $paths as $path) {
  483. if (($type === 'files' || $type === 'classmap') && $package->getTargetDir() && !is_readable($installPath.'/'.$path)) {
  484. // remove target-dir from file paths of the root package
  485. if ($package === $mainPackage) {
  486. $targetDir = str_replace('\\<dirsep\\>', '[\\\\/]', preg_quote(str_replace(array('/', '\\'), '<dirsep>', $package->getTargetDir())));
  487. $path = ltrim(preg_replace('{^'.$targetDir.'}', '', ltrim($path, '\\/')), '\\/');
  488. } else {
  489. // add target-dir from file paths that don't have it
  490. $path = $package->getTargetDir() . '/' . $path;
  491. }
  492. }
  493. $relativePath = empty($installPath) ? (empty($path) ? '.' : $path) : $installPath.'/'.$path;
  494. if ($type === 'files' || $type === 'classmap') {
  495. $autoloads[] = $relativePath;
  496. continue;
  497. }
  498. $autoloads[$namespace][] = $relativePath;
  499. }
  500. }
  501. }
  502. return $autoloads;
  503. }
  504. /**
  505. * Sorts packages by dependency weight
  506. *
  507. * Packages of equal weight retain the original order
  508. *
  509. * @param array $packageMap
  510. * @return array
  511. */
  512. protected function sortPackageMap(array $packageMap)
  513. {
  514. $packages = array();
  515. $paths = array();
  516. $usageList = array();
  517. foreach ($packageMap as $item) {
  518. list($package, $path) = $item;
  519. $name = $package->getName();
  520. $packages[$name] = $package;
  521. $paths[$name] = $path;
  522. foreach (array_merge($package->getRequires(), $package->getDevRequires()) as $link) {
  523. $target = $link->getTarget();
  524. $usageList[$target][] = $name;
  525. }
  526. }
  527. $computing = array();
  528. $computed = array();
  529. $computeImportance = function ($name) use (&$computeImportance, &$computing, &$computed, $usageList) {
  530. // reusing computed importance
  531. if (isset($computed[$name])) {
  532. return $computed[$name];
  533. }
  534. // canceling circular dependency
  535. if (isset($computing[$name])) {
  536. return 0;
  537. }
  538. $computing[$name] = true;
  539. $weight = 0;
  540. if (isset($usageList[$name])) {
  541. foreach ($usageList[$name] as $user) {
  542. $weight -= 1 - $computeImportance($user);
  543. }
  544. }
  545. unset($computing[$name]);
  546. $computed[$name] = $weight;
  547. return $weight;
  548. };
  549. $weightList = array();
  550. foreach ($packages as $name => $package) {
  551. $weight = $computeImportance($name);
  552. $weightList[$name] = $weight;
  553. }
  554. $stable_sort = function (&$array) {
  555. static $transform, $restore;
  556. $i = 0;
  557. if (!$transform) {
  558. $transform = function (&$v, $k) use (&$i) {
  559. $v = array($v, ++$i, $k, $v);
  560. };
  561. $restore = function (&$v, $k) {
  562. $v = $v[3];
  563. };
  564. }
  565. array_walk($array, $transform);
  566. asort($array);
  567. array_walk($array, $restore);
  568. };
  569. $stable_sort($weightList);
  570. $sortedPackageMap = array();
  571. foreach (array_keys($weightList) as $name) {
  572. $sortedPackageMap[] = array($packages[$name], $paths[$name]);
  573. }
  574. return $sortedPackageMap;
  575. }
  576. }