AutoloadGenerator.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  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. const EXCLUDE_PATTERN = '.*%s';
  28. /**
  29. * @var EventDispatcher
  30. */
  31. private $eventDispatcher;
  32. /**
  33. * @var IOInterface
  34. */
  35. private $io;
  36. private $devMode = false;
  37. public function __construct(EventDispatcher $eventDispatcher, IOInterface $io = null)
  38. {
  39. $this->eventDispatcher = $eventDispatcher;
  40. $this->io = $io;
  41. }
  42. public function setDevMode($devMode = true)
  43. {
  44. $this->devMode = (boolean) $devMode;
  45. }
  46. public function dump(Config $config, InstalledRepositoryInterface $localRepo, PackageInterface $mainPackage, InstallationManager $installationManager, $targetDir, $scanPsr0Packages = false, $suffix = '')
  47. {
  48. $this->eventDispatcher->dispatchScript(ScriptEvents::PRE_AUTOLOAD_DUMP, $this->devMode, array(), array(
  49. 'optimize' => (bool) $scanPsr0Packages,
  50. ));
  51. $filesystem = new Filesystem();
  52. $filesystem->ensureDirectoryExists($config->get('vendor-dir'));
  53. $basePath = $filesystem->normalizePath(realpath(getcwd()));
  54. $vendorPath = $filesystem->normalizePath(realpath($config->get('vendor-dir')));
  55. $useGlobalIncludePath = (bool) $config->get('use-include-path');
  56. $prependAutoloader = $config->get('prepend-autoloader') === false ? 'false' : 'true';
  57. $classMapAuthoritative = $config->get('classmap-authoritative');
  58. $targetDir = $vendorPath.'/'.$targetDir;
  59. $filesystem->ensureDirectoryExists($targetDir);
  60. $vendorPathCode = $filesystem->findShortestPathCode(realpath($targetDir), $vendorPath, true);
  61. $vendorPathCode52 = str_replace('__DIR__', 'dirname(__FILE__)', $vendorPathCode);
  62. $vendorPathToTargetDirCode = $filesystem->findShortestPathCode($vendorPath, realpath($targetDir), true);
  63. $appBaseDirCode = $filesystem->findShortestPathCode($vendorPath, $basePath, true);
  64. $appBaseDirCode = str_replace('__DIR__', '$vendorDir', $appBaseDirCode);
  65. $namespacesFile = <<<EOF
  66. <?php
  67. // autoload_namespaces.php @generated by Composer
  68. \$vendorDir = $vendorPathCode52;
  69. \$baseDir = $appBaseDirCode;
  70. return array(
  71. EOF;
  72. $psr4File = <<<EOF
  73. <?php
  74. // autoload_psr4.php @generated by Composer
  75. \$vendorDir = $vendorPathCode52;
  76. \$baseDir = $appBaseDirCode;
  77. return array(
  78. EOF;
  79. // Collect information from all packages.
  80. $packageMap = $this->buildPackageMap($installationManager, $mainPackage, $localRepo->getCanonicalPackages());
  81. $autoloads = $this->parseAutoloads($packageMap, $mainPackage);
  82. // Process the 'psr-0' base directories.
  83. foreach ($autoloads['psr-0'] as $namespace => $paths) {
  84. $exportedPaths = array();
  85. foreach ($paths as $path) {
  86. $exportedPaths[] = $this->getPathCode($filesystem, $basePath, $vendorPath, $path);
  87. }
  88. $exportedPrefix = var_export($namespace, true);
  89. $namespacesFile .= " $exportedPrefix => ";
  90. $namespacesFile .= "array(".implode(', ', $exportedPaths)."),\n";
  91. }
  92. $namespacesFile .= ");\n";
  93. // Process the 'psr-4' base directories.
  94. foreach ($autoloads['psr-4'] as $namespace => $paths) {
  95. $exportedPaths = array();
  96. foreach ($paths as $path) {
  97. $exportedPaths[] = $this->getPathCode($filesystem, $basePath, $vendorPath, $path);
  98. }
  99. $exportedPrefix = var_export($namespace, true);
  100. $psr4File .= " $exportedPrefix => ";
  101. $psr4File .= "array(".implode(', ', $exportedPaths)."),\n";
  102. }
  103. $psr4File .= ");\n";
  104. $classmapFile = <<<EOF
  105. <?php
  106. // autoload_classmap.php @generated by Composer
  107. \$vendorDir = $vendorPathCode52;
  108. \$baseDir = $appBaseDirCode;
  109. return array(
  110. EOF;
  111. // add custom psr-0 autoloading if the root package has a target dir
  112. $targetDirLoader = null;
  113. $mainAutoload = $mainPackage->getAutoload();
  114. if ($mainPackage->getTargetDir() && !empty($mainAutoload['psr-0'])) {
  115. $levels = count(explode('/', $filesystem->normalizePath($mainPackage->getTargetDir())));
  116. $prefixes = implode(', ', array_map(function ($prefix) {
  117. return var_export($prefix, true);
  118. }, array_keys($mainAutoload['psr-0'])));
  119. $baseDirFromTargetDirCode = $filesystem->findShortestPathCode($targetDir, $basePath, true);
  120. $targetDirLoader = <<<EOF
  121. public static function autoload(\$class)
  122. {
  123. \$dir = $baseDirFromTargetDirCode . '/';
  124. \$prefixes = array($prefixes);
  125. foreach (\$prefixes as \$prefix) {
  126. if (0 !== strpos(\$class, \$prefix)) {
  127. continue;
  128. }
  129. \$path = \$dir . implode('/', array_slice(explode('\\\\', \$class), $levels)).'.php';
  130. if (!\$path = stream_resolve_include_path(\$path)) {
  131. return false;
  132. }
  133. require \$path;
  134. return true;
  135. }
  136. }
  137. EOF;
  138. }
  139. $blacklist = '';
  140. if (!empty($autoloads['exclude-from-classmap'])) {
  141. $blacklist = '{(' . implode('|', $autoloads['exclude-from-classmap']) . ')}';
  142. }
  143. // flatten array
  144. $classMap = array();
  145. if ($scanPsr0Packages) {
  146. // Scan the PSR-0/4 directories for class files, and add them to the class map
  147. foreach (array('psr-0', 'psr-4') as $psrType) {
  148. foreach ($autoloads[$psrType] as $namespace => $paths) {
  149. foreach ($paths as $dir) {
  150. $dir = $filesystem->normalizePath($filesystem->isAbsolutePath($dir) ? $dir : $basePath.'/'.$dir);
  151. if (!is_dir($dir)) {
  152. continue;
  153. }
  154. $namespaceFilter = $namespace === '' ? null : $namespace;
  155. foreach (ClassMapGenerator::createMap($dir, $blacklist, $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, $blacklist, $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. $exclude = $this->parseAutoloadsType($sortedPackageMap, 'exclude-from-classmap', $mainPackage);
  257. krsort($psr0);
  258. krsort($psr4);
  259. return
  260. array(
  261. 'psr-0' => $psr0,
  262. 'psr-4' => $psr4,
  263. 'classmap' => $classmap,
  264. 'files' => $files,
  265. 'exclude-from-classmap' => $exclude
  266. );
  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. if ($type === 'exclude-from-classmap') {
  494. // first escape user input
  495. $path = sprintf(self::EXCLUDE_PATTERN, preg_quote($path));
  496. if ($package === $mainPackage && $package->getTargetDir() && !is_readable($installPath.'/'.$path)) {
  497. // remove target-dir from classmap entries of the root package
  498. $targetDir = str_replace('\\<dirsep\\>', '[\\\\/]', preg_quote(str_replace(array('/', '\\'), '<dirsep>', $package->getTargetDir())));
  499. $path = ltrim(preg_replace('{^'.$targetDir.'}', '', ltrim($path, '\\/')), '\\/');
  500. }
  501. elseif($package !== $mainPackage && $package->getTargetDir() && !is_readable($installPath.'/'.$path)) {
  502. // add target-dir to exclude entries that don't have it
  503. $path = preg_quote($package->getTargetDir()) . '/' . $path;
  504. }
  505. $autoloads[] = empty($installPath) ? $path : preg_quote($installPath) . '/' . $path;
  506. continue;
  507. }
  508. $relativePath = empty($installPath) ? (empty($path) ? '.' : $path) : $installPath.'/'.$path;
  509. if ($type === 'files' || $type === 'classmap') {
  510. $autoloads[] = $relativePath;
  511. continue;
  512. }
  513. $autoloads[$namespace][] = $relativePath;
  514. }
  515. }
  516. }
  517. return $autoloads;
  518. }
  519. /**
  520. * Sorts packages by dependency weight
  521. *
  522. * Packages of equal weight retain the original order
  523. *
  524. * @param array $packageMap
  525. * @return array
  526. */
  527. protected function sortPackageMap(array $packageMap)
  528. {
  529. $packages = array();
  530. $paths = array();
  531. $usageList = array();
  532. foreach ($packageMap as $item) {
  533. list($package, $path) = $item;
  534. $name = $package->getName();
  535. $packages[$name] = $package;
  536. $paths[$name] = $path;
  537. foreach (array_merge($package->getRequires(), $package->getDevRequires()) as $link) {
  538. $target = $link->getTarget();
  539. $usageList[$target][] = $name;
  540. }
  541. }
  542. $computing = array();
  543. $computed = array();
  544. $computeImportance = function ($name) use (&$computeImportance, &$computing, &$computed, $usageList) {
  545. // reusing computed importance
  546. if (isset($computed[$name])) {
  547. return $computed[$name];
  548. }
  549. // canceling circular dependency
  550. if (isset($computing[$name])) {
  551. return 0;
  552. }
  553. $computing[$name] = true;
  554. $weight = 0;
  555. if (isset($usageList[$name])) {
  556. foreach ($usageList[$name] as $user) {
  557. $weight -= 1 - $computeImportance($user);
  558. }
  559. }
  560. unset($computing[$name]);
  561. $computed[$name] = $weight;
  562. return $weight;
  563. };
  564. $weightList = array();
  565. foreach ($packages as $name => $package) {
  566. $weight = $computeImportance($name);
  567. $weightList[$name] = $weight;
  568. }
  569. $stable_sort = function (&$array) {
  570. static $transform, $restore;
  571. $i = 0;
  572. if (!$transform) {
  573. $transform = function (&$v, $k) use (&$i) {
  574. $v = array($v, ++$i, $k, $v);
  575. };
  576. $restore = function (&$v, $k) {
  577. $v = $v[3];
  578. };
  579. }
  580. array_walk($array, $transform);
  581. asort($array);
  582. array_walk($array, $restore);
  583. };
  584. $stable_sort($weightList);
  585. $sortedPackageMap = array();
  586. foreach (array_keys($weightList) as $name) {
  587. $sortedPackageMap[] = array($packages[$name], $paths[$name]);
  588. }
  589. return $sortedPackageMap;
  590. }
  591. }