AutoloadGenerator.php 26 KB

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