AutoloadGenerator.php 26 KB

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