AutoloadGenerator.php 25 KB

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