Installer.php 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244
  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;
  12. use Composer\Autoload\AutoloadGenerator;
  13. use Composer\DependencyResolver\DefaultPolicy;
  14. use Composer\DependencyResolver\LocalRepoTransaction;
  15. use Composer\DependencyResolver\LockTransaction;
  16. use Composer\DependencyResolver\Operation\UpdateOperation;
  17. use Composer\DependencyResolver\Operation\InstallOperation;
  18. use Composer\DependencyResolver\Operation\UninstallOperation;
  19. use Composer\DependencyResolver\Operation\MarkAliasUninstalledOperation;
  20. use Composer\DependencyResolver\Operation\OperationInterface;
  21. use Composer\DependencyResolver\PolicyInterface;
  22. use Composer\DependencyResolver\Pool;
  23. use Composer\DependencyResolver\Request;
  24. use Composer\DependencyResolver\Rule;
  25. use Composer\DependencyResolver\Solver;
  26. use Composer\DependencyResolver\SolverProblemsException;
  27. use Composer\Downloader\DownloadManager;
  28. use Composer\EventDispatcher\EventDispatcher;
  29. use Composer\Installer\InstallationManager;
  30. use Composer\Installer\InstallerEvents;
  31. use Composer\Installer\NoopInstaller;
  32. use Composer\Installer\SuggestedPackagesReporter;
  33. use Composer\IO\IOInterface;
  34. use Composer\Package\AliasPackage;
  35. use Composer\Package\RootAliasPackage;
  36. use Composer\Package\BasePackage;
  37. use Composer\Package\CompletePackage;
  38. use Composer\Package\CompletePackageInterface;
  39. use Composer\Package\Link;
  40. use Composer\Package\LinkConstraint\VersionConstraint;
  41. use Composer\Package\Loader\ArrayLoader;
  42. use Composer\Package\Dumper\ArrayDumper;
  43. use Composer\Package\Package;
  44. use Composer\Repository\ArrayRepository;
  45. use Composer\Repository\RepositorySet;
  46. use Composer\Semver\Constraint\Constraint;
  47. use Composer\Package\Locker;
  48. use Composer\Package\PackageInterface;
  49. use Composer\Package\RootPackageInterface;
  50. use Composer\Repository\CompositeRepository;
  51. use Composer\Repository\InstalledArrayRepository;
  52. use Composer\Repository\InstalledRepository;
  53. use Composer\Repository\RootPackageRepository;
  54. use Composer\Repository\PlatformRepository;
  55. use Composer\Repository\RepositoryInterface;
  56. use Composer\Repository\RepositoryManager;
  57. use Composer\Repository\WritableRepositoryInterface;
  58. use Composer\Script\ScriptEvents;
  59. /**
  60. * @author Jordi Boggiano <j.boggiano@seld.be>
  61. * @author Beau Simensen <beau@dflydev.com>
  62. * @author Konstantin Kudryashov <ever.zet@gmail.com>
  63. * @author Nils Adermann <naderman@naderman.de>
  64. */
  65. class Installer
  66. {
  67. /**
  68. * @var IOInterface
  69. */
  70. protected $io;
  71. /**
  72. * @var Config
  73. */
  74. protected $config;
  75. /**
  76. * @var RootPackageInterface
  77. */
  78. protected $package;
  79. // TODO can we get rid of the below and just use the package itself?
  80. /**
  81. * @var RootPackageInterface
  82. */
  83. protected $fixedRootPackage;
  84. /**
  85. * @var DownloadManager
  86. */
  87. protected $downloadManager;
  88. /**
  89. * @var RepositoryManager
  90. */
  91. protected $repositoryManager;
  92. /**
  93. * @var Locker
  94. */
  95. protected $locker;
  96. /**
  97. * @var InstallationManager
  98. */
  99. protected $installationManager;
  100. /**
  101. * @var EventDispatcher
  102. */
  103. protected $eventDispatcher;
  104. /**
  105. * @var AutoloadGenerator
  106. */
  107. protected $autoloadGenerator;
  108. protected $preferSource = false;
  109. protected $preferDist = false;
  110. protected $optimizeAutoloader = false;
  111. protected $classMapAuthoritative = false;
  112. protected $apcuAutoloader = false;
  113. protected $devMode = false;
  114. protected $dryRun = false;
  115. protected $verbose = false;
  116. protected $update = false;
  117. protected $dumpAutoloader = true;
  118. protected $runScripts = true;
  119. protected $ignorePlatformReqs = false;
  120. protected $preferStable = false;
  121. protected $preferLowest = false;
  122. protected $writeLock;
  123. protected $executeOperations = true;
  124. /**
  125. * Array of package names/globs flagged for update
  126. *
  127. * @var array|null
  128. */
  129. protected $updateMirrors = false;
  130. protected $updateAllowList = null;
  131. protected $updateAllowTransitiveDependencies = Request::UPDATE_ONLY_LISTED;
  132. /**
  133. * @var SuggestedPackagesReporter
  134. */
  135. protected $suggestedPackagesReporter;
  136. /**
  137. * @var RepositoryInterface
  138. */
  139. protected $additionalFixedRepository;
  140. /**
  141. * Constructor
  142. *
  143. * @param IOInterface $io
  144. * @param Config $config
  145. * @param RootPackageInterface $package
  146. * @param DownloadManager $downloadManager
  147. * @param RepositoryManager $repositoryManager
  148. * @param Locker $locker
  149. * @param InstallationManager $installationManager
  150. * @param EventDispatcher $eventDispatcher
  151. * @param AutoloadGenerator $autoloadGenerator
  152. */
  153. public function __construct(IOInterface $io, Config $config, RootPackageInterface $package, DownloadManager $downloadManager, RepositoryManager $repositoryManager, Locker $locker, InstallationManager $installationManager, EventDispatcher $eventDispatcher, AutoloadGenerator $autoloadGenerator)
  154. {
  155. $this->io = $io;
  156. $this->config = $config;
  157. $this->package = $package;
  158. $this->downloadManager = $downloadManager;
  159. $this->repositoryManager = $repositoryManager;
  160. $this->locker = $locker;
  161. $this->installationManager = $installationManager;
  162. $this->eventDispatcher = $eventDispatcher;
  163. $this->autoloadGenerator = $autoloadGenerator;
  164. $this->writeLock = $config->get('lock');
  165. }
  166. /**
  167. * Run installation (or update)
  168. *
  169. * @throws \Exception
  170. * @return int 0 on success or a positive error code on failure
  171. */
  172. public function run()
  173. {
  174. // Disable GC to save CPU cycles, as the dependency solver can create hundreds of thousands
  175. // of PHP objects, the GC can spend quite some time walking the tree of references looking
  176. // for stuff to collect while there is nothing to collect. This slows things down dramatically
  177. // and turning it off results in much better performance. Do not try this at home however.
  178. gc_collect_cycles();
  179. gc_disable();
  180. if ($this->updateAllowList && $this->updateMirrors) {
  181. throw new \RuntimeException("The installer options updateMirrors and updateAllowList are mutually exclusive.");
  182. }
  183. // Force update if there is no lock file present
  184. if (!$this->update && !$this->locker->isLocked()) {
  185. $this->io->writeError('<warning>No lock file found. Updating dependencies instead of installing from lock file. Use composer update over composer install if you do not have a lock file.</warning>');
  186. $this->update = true;
  187. }
  188. if ($this->dryRun) {
  189. $this->verbose = true;
  190. $this->runScripts = false;
  191. $this->executeOperations = false;
  192. $this->writeLock = false;
  193. $this->dumpAutoloader = false;
  194. $this->mockLocalRepositories($this->repositoryManager);
  195. }
  196. if ($this->runScripts) {
  197. $_SERVER['COMPOSER_DEV_MODE'] = (int) $this->devMode;
  198. putenv('COMPOSER_DEV_MODE='.$_SERVER['COMPOSER_DEV_MODE']);
  199. // dispatch pre event
  200. // should we treat this more strictly as running an update and then running an install, triggering events multiple times?
  201. $eventName = $this->update ? ScriptEvents::PRE_UPDATE_CMD : ScriptEvents::PRE_INSTALL_CMD;
  202. $this->eventDispatcher->dispatchScript($eventName, $this->devMode);
  203. }
  204. $this->downloadManager->setPreferSource($this->preferSource);
  205. $this->downloadManager->setPreferDist($this->preferDist);
  206. $localRepo = $this->repositoryManager->getLocalRepository();
  207. if (!$this->suggestedPackagesReporter) {
  208. $this->suggestedPackagesReporter = new SuggestedPackagesReporter($this->io);
  209. }
  210. try {
  211. if ($this->update) {
  212. // TODO introduce option to set doInstall to false (update lock file without vendor install)
  213. $res = $this->doUpdate($localRepo, true);
  214. } else {
  215. $res = $this->doInstall($localRepo);
  216. }
  217. if ($res !== 0) {
  218. return $res;
  219. }
  220. } catch (\Exception $e) {
  221. if ($this->executeOperations && $this->config->get('notify-on-install')) {
  222. $this->installationManager->notifyInstalls($this->io);
  223. }
  224. throw $e;
  225. }
  226. if ($this->executeOperations && $this->config->get('notify-on-install')) {
  227. $this->installationManager->notifyInstalls($this->io);
  228. }
  229. if ($this->update) {
  230. $installedRepo = new InstalledRepository(array(
  231. $this->locker->getLockedRepository($this->devMode),
  232. $this->createPlatformRepo(false),
  233. new RootPackageRepository(clone $this->package),
  234. ));
  235. $this->suggestedPackagesReporter->outputMinimalistic($installedRepo);
  236. }
  237. // Find abandoned packages and warn user
  238. $lockedRepository = $this->locker->getLockedRepository(true);
  239. foreach ($lockedRepository->getPackages() as $package) {
  240. if (!$package instanceof CompletePackage || !$package->isAbandoned()) {
  241. continue;
  242. }
  243. $replacement = is_string($package->getReplacementPackage())
  244. ? 'Use ' . $package->getReplacementPackage() . ' instead'
  245. : 'No replacement was suggested';
  246. $this->io->writeError(
  247. sprintf(
  248. "<warning>Package %s is abandoned, you should avoid using it. %s.</warning>",
  249. $package->getPrettyName(),
  250. $replacement
  251. )
  252. );
  253. }
  254. if ($this->dumpAutoloader) {
  255. // write autoloader
  256. if ($this->optimizeAutoloader) {
  257. $this->io->writeError('<info>Generating optimized autoload files</info>');
  258. } else {
  259. $this->io->writeError('<info>Generating autoload files</info>');
  260. }
  261. $this->autoloadGenerator->setDevMode($this->devMode);
  262. $this->autoloadGenerator->setClassMapAuthoritative($this->classMapAuthoritative);
  263. $this->autoloadGenerator->setApcu($this->apcuAutoloader);
  264. $this->autoloadGenerator->setRunScripts($this->runScripts);
  265. $this->autoloadGenerator->dump($this->config, $localRepo, $this->package, $this->installationManager, 'composer', $this->optimizeAutoloader);
  266. }
  267. if ($this->executeOperations) {
  268. // force binaries re-generation in case they are missing
  269. foreach ($localRepo->getPackages() as $package) {
  270. $this->installationManager->ensureBinariesPresence($package);
  271. }
  272. }
  273. $fundingCount = 0;
  274. foreach ($localRepo->getPackages() as $package) {
  275. if ($package instanceof CompletePackageInterface && !$package instanceof AliasPackage && $package->getFunding()) {
  276. $fundingCount++;
  277. }
  278. }
  279. if ($fundingCount) {
  280. $this->io->writeError(array(
  281. sprintf(
  282. "<info>%d package%s you are using %s looking for funding.</info>",
  283. $fundingCount,
  284. 1 === $fundingCount ? '' : 's',
  285. 1 === $fundingCount ? 'is' : 'are'
  286. ),
  287. '<info>Use the `composer fund` command to find out more!</info>',
  288. ));
  289. }
  290. if ($this->runScripts) {
  291. // dispatch post event
  292. $eventName = $this->update ? ScriptEvents::POST_UPDATE_CMD : ScriptEvents::POST_INSTALL_CMD;
  293. $this->eventDispatcher->dispatchScript($eventName, $this->devMode);
  294. }
  295. // re-enable GC except on HHVM which triggers a warning here
  296. if (!defined('HHVM_VERSION')) {
  297. gc_enable();
  298. }
  299. return 0;
  300. }
  301. protected function doUpdate(RepositoryInterface $localRepo, $doInstall)
  302. {
  303. $platformRepo = $this->createPlatformRepo(true);
  304. $aliases = $this->getRootAliases(true);
  305. $lockedRepository = null;
  306. if ($this->locker->isLocked()) {
  307. $lockedRepository = $this->locker->getLockedRepository(true);
  308. }
  309. if ($this->updateAllowList) {
  310. if (!$lockedRepository) {
  311. $this->io->writeError('<error>Cannot update only a partial set of packages without a lock file present.</error>', true, IOInterface::QUIET);
  312. return 1;
  313. }
  314. }
  315. $this->io->writeError('<info>Loading composer repositories with package information</info>');
  316. // creating repository set
  317. $policy = $this->createPolicy(true);
  318. $repositorySet = $this->createRepositorySet(true, $platformRepo, $aliases);
  319. $repositories = $this->repositoryManager->getRepositories();
  320. foreach ($repositories as $repository) {
  321. $repositorySet->addRepository($repository);
  322. }
  323. if ($lockedRepository) {
  324. $repositorySet->addRepository($lockedRepository);
  325. }
  326. $request = $this->createRequest($this->fixedRootPackage, $platformRepo, $lockedRepository);
  327. $this->io->writeError('<info>Updating dependencies</info>');
  328. $links = array_merge($this->package->getRequires(), $this->package->getDevRequires());
  329. // if we're updating mirrors we want to keep exactly the same versions installed which are in the lock file, but we want current remote metadata
  330. if ($this->updateMirrors) {
  331. foreach ($lockedRepository->getPackages() as $lockedPackage) {
  332. $request->requireName($lockedPackage->getName(), new Constraint('==', $lockedPackage->getVersion()));
  333. }
  334. } else {
  335. foreach ($links as $link) {
  336. $request->requireName($link->getTarget(), $link->getConstraint());
  337. }
  338. }
  339. // pass the allow list into the request, so the pool builder can apply it
  340. if ($this->updateAllowList) {
  341. $request->setUpdateAllowList($this->updateAllowList, $this->updateAllowTransitiveDependencies);
  342. }
  343. $pool = $repositorySet->createPool($request, $this->io, $this->eventDispatcher);
  344. // solve dependencies
  345. $solver = new Solver($policy, $pool, $this->io);
  346. try {
  347. $lockTransaction = $solver->solve($request, $this->ignorePlatformReqs);
  348. $ruleSetSize = $solver->getRuleSetSize();
  349. $solver = null;
  350. } catch (SolverProblemsException $e) {
  351. $this->io->writeError('<error>Your requirements could not be resolved to an installable set of packages.</error>', true, IOInterface::QUIET);
  352. $this->io->writeError($e->getPrettyString($repositorySet, $request, $pool));
  353. if (!$this->devMode) {
  354. $this->io->writeError('<warning>Running update with --no-dev does not mean require-dev is ignored, it just means the packages will not be installed. If dev requirements are blocking the update you have to resolve those problems.</warning>', true, IOInterface::QUIET);
  355. }
  356. return max(1, $e->getCode());
  357. }
  358. $this->io->writeError("Analyzed ".count($pool)." packages to resolve dependencies", true, IOInterface::VERBOSE);
  359. $this->io->writeError("Analyzed ".$ruleSetSize." rules to resolve dependencies", true, IOInterface::VERBOSE);
  360. if (!$lockTransaction->getOperations()) {
  361. $this->io->writeError('Nothing to modify in lock file');
  362. }
  363. $exitCode = $this->extractDevPackages($lockTransaction, $platformRepo, $aliases, $policy);
  364. if ($exitCode !== 0) {
  365. return $exitCode;
  366. }
  367. // write lock
  368. $platformReqs = $this->extractPlatformRequirements($this->package->getRequires());
  369. $platformDevReqs = $this->extractPlatformRequirements($this->package->getDevRequires());
  370. $installsUpdates = $uninstalls = array();
  371. if ($lockTransaction->getOperations()) {
  372. $installNames = $updateNames = $uninstallNames = array();
  373. foreach ($lockTransaction->getOperations() as $operation) {
  374. if ($operation instanceof InstallOperation) {
  375. $installsUpdates[] = $operation;
  376. $installNames[] = $operation->getPackage()->getPrettyName().':'.$operation->getPackage()->getFullPrettyVersion();
  377. } elseif ($operation instanceof UpdateOperation) {
  378. $installsUpdates[] = $operation;
  379. $updateNames[] = $operation->getTargetPackage()->getPrettyName().':'.$operation->getTargetPackage()->getFullPrettyVersion();
  380. } elseif ($operation instanceof UninstallOperation) {
  381. $uninstalls[] = $operation;
  382. $uninstallNames[] = $operation->getPackage()->getPrettyName();
  383. }
  384. }
  385. $this->io->writeError(sprintf(
  386. "<info>Lock file operations: %d install%s, %d update%s, %d removal%s</info>",
  387. count($installNames),
  388. 1 === count($installNames) ? '' : 's',
  389. count($updateNames),
  390. 1 === count($updateNames) ? '' : 's',
  391. count($uninstalls),
  392. 1 === count($uninstalls) ? '' : 's'
  393. ));
  394. if ($installNames) {
  395. $this->io->writeError("Installs: ".implode(', ', $installNames), true, IOInterface::VERBOSE);
  396. }
  397. if ($updateNames) {
  398. $this->io->writeError("Updates: ".implode(', ', $updateNames), true, IOInterface::VERBOSE);
  399. }
  400. if ($uninstalls) {
  401. $this->io->writeError("Removals: ".implode(', ', $uninstallNames), true, IOInterface::VERBOSE);
  402. }
  403. }
  404. $sortByName = function ($a, $b) {
  405. if ($a instanceof UpdateOperation) {
  406. $a = $a->getTargetPackage()->getName();
  407. } else {
  408. $a = $a->getPackage()->getName();
  409. }
  410. if ($b instanceof UpdateOperation) {
  411. $b = $b->getTargetPackage()->getName();
  412. } else {
  413. $b = $b->getPackage()->getName();
  414. }
  415. return strcmp($a, $b);
  416. };
  417. usort($uninstalls, $sortByName);
  418. usort($installsUpdates, $sortByName);
  419. foreach (array_merge($uninstalls, $installsUpdates) as $operation) {
  420. // collect suggestions
  421. if ($operation instanceof InstallOperation) {
  422. $this->suggestedPackagesReporter->addSuggestionsFromPackage($operation->getPackage());
  423. }
  424. // output op, but alias op only in debug verbosity
  425. if (false === strpos($operation->getOperationType(), 'Alias') || $this->io->isDebug()) {
  426. $this->io->writeError(' - ' . $operation->show(true));
  427. }
  428. }
  429. $updatedLock = $this->locker->setLockData(
  430. $lockTransaction->getNewLockPackages(false, $this->updateMirrors),
  431. $lockTransaction->getNewLockPackages(true, $this->updateMirrors),
  432. $platformReqs,
  433. $platformDevReqs,
  434. $lockTransaction->getAliases($aliases),
  435. $this->package->getMinimumStability(),
  436. $this->package->getStabilityFlags(),
  437. $this->preferStable || $this->package->getPreferStable(),
  438. $this->preferLowest,
  439. $this->config->get('platform') ?: array(),
  440. $this->writeLock && $this->executeOperations
  441. );
  442. if ($updatedLock && $this->writeLock && $this->executeOperations) {
  443. $this->io->writeError('<info>Writing lock file</info>');
  444. }
  445. // see https://github.com/composer/composer/issues/2764
  446. if ($this->executeOperations && count($lockTransaction->getOperations()) > 0) {
  447. $vendorDir = $this->config->get('vendor-dir');
  448. if (is_dir($vendorDir)) {
  449. // suppress errors as this fails sometimes on OSX for no apparent reason
  450. // see https://github.com/composer/composer/issues/4070#issuecomment-129792748
  451. @touch($vendorDir);
  452. }
  453. }
  454. if ($doInstall) {
  455. // TODO ensure lock is used from locker as-is, since it may not have been written to disk in case of executeOperations == false
  456. return $this->doInstall($localRepo, true);
  457. }
  458. return 0;
  459. }
  460. /**
  461. * Run the solver a second time on top of the existing update result with only the current result set in the pool
  462. * and see what packages would get removed if we only had the non-dev packages in the solver request
  463. */
  464. protected function extractDevPackages(LockTransaction $lockTransaction, $platformRepo, $aliases, $policy)
  465. {
  466. if (!$this->package->getDevRequires()) {
  467. return 0;
  468. }
  469. $resultRepo = new ArrayRepository(array());
  470. $loader = new ArrayLoader(null, true);
  471. $dumper = new ArrayDumper();
  472. foreach ($lockTransaction->getNewLockPackages(false) as $pkg) {
  473. $resultRepo->addPackage($loader->load($dumper->dump($pkg)));
  474. }
  475. $repositorySet = $this->createRepositorySet(true, $platformRepo, $aliases);
  476. $repositorySet->addRepository($resultRepo);
  477. $request = $this->createRequest($this->fixedRootPackage, $platformRepo, null);
  478. $links = $this->package->getRequires();
  479. foreach ($links as $link) {
  480. $request->requireName($link->getTarget(), $link->getConstraint());
  481. }
  482. $pool = $repositorySet->createPoolWithAllPackages();
  483. $solver = new Solver($policy, $pool, $this->io);
  484. try {
  485. $nonDevLockTransaction = $solver->solve($request, $this->ignorePlatformReqs);
  486. $solver = null;
  487. } catch (SolverProblemsException $e) {
  488. $this->io->writeError('<error>Unable to find a compatible set of packages based on your non-dev requirements alone.</error>', true, IOInterface::QUIET);
  489. $this->io->writeError('Your requirements can be resolved successfully when require-dev packages are present.');
  490. $this->io->writeError('You may need to move packages from require-dev or some of their dependencies to require.');
  491. $this->io->writeError($e->getPrettyString($repositorySet, $request, $pool, true));
  492. return max(1, $e->getCode());
  493. }
  494. $lockTransaction->setNonDevPackages($nonDevLockTransaction);
  495. return 0;
  496. }
  497. /**
  498. * @param RepositoryInterface $localRepo
  499. * @param bool $alreadySolved Whether the function is called as part of an update command or independently
  500. * @return int exit code
  501. */
  502. protected function doInstall(RepositoryInterface $localRepo, $alreadySolved = false)
  503. {
  504. $this->io->writeError('<info>Installing dependencies from lock file'.($this->devMode ? ' (including require-dev)' : '').'</info>');
  505. $lockedRepository = $this->locker->getLockedRepository($this->devMode);
  506. // verify that the lock file works with the current platform repository
  507. // we can skip this part if we're doing this as the second step after an update
  508. if (!$alreadySolved) {
  509. $this->io->writeError('<info>Verifying lock file contents can be installed on current platform.</info>');
  510. $platformRepo = $this->createPlatformRepo(false);
  511. // creating repository set
  512. $policy = $this->createPolicy(false);
  513. // use aliases from lock file only, so empty root aliases here
  514. $repositorySet = $this->createRepositorySet(false, $platformRepo, array(), $lockedRepository);
  515. $repositorySet->addRepository($lockedRepository);
  516. // creating requirements request
  517. $request = $this->createRequest($this->fixedRootPackage, $platformRepo, $lockedRepository);
  518. if (!$this->locker->isFresh()) {
  519. $this->io->writeError('<warning>Warning: The lock file is not up to date with the latest changes in composer.json. You may be getting outdated dependencies. It is recommended that you run `composer update` or `composer update <package name>`.</warning>', true, IOInterface::QUIET);
  520. }
  521. foreach ($lockedRepository->getPackages() as $package) {
  522. $request->fixPackage($package);
  523. }
  524. foreach ($this->locker->getPlatformRequirements($this->devMode) as $link) {
  525. $request->requireName($link->getTarget(), $link->getConstraint());
  526. }
  527. $pool = $repositorySet->createPool($request, $this->io, $this->eventDispatcher);
  528. // solve dependencies
  529. $solver = new Solver($policy, $pool, $this->io);
  530. try {
  531. $lockTransaction = $solver->solve($request, $this->ignorePlatformReqs);
  532. $solver = null;
  533. // installing the locked packages on this platform resulted in lock modifying operations, there wasn't a conflict, but the lock file as-is seems to not work on this system
  534. if (0 !== count($lockTransaction->getOperations())) {
  535. $this->io->writeError('<error>Your lock file cannot be installed on this system without changes. Please run composer update.</error>', true, IOInterface::QUIET);
  536. // TODO actually display operations to explain what happened?
  537. return 1;
  538. }
  539. } catch (SolverProblemsException $e) {
  540. $this->io->writeError('<error>Your lock file does not contain a compatible set of packages. Please run composer update.</error>', true, IOInterface::QUIET);
  541. $this->io->writeError($e->getPrettyString($repositorySet, $request, $pool));
  542. return max(1, $e->getCode());
  543. }
  544. }
  545. // TODO in how far do we need to do anything here to ensure dev packages being updated to latest in lock without version change are treated correctly?
  546. $localRepoTransaction = new LocalRepoTransaction($lockedRepository, $localRepo);
  547. $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::PRE_OPERATIONS_EXEC, $this->devMode, $this->executeOperations, $localRepoTransaction);
  548. if (!$localRepoTransaction->getOperations()) {
  549. $this->io->writeError('Nothing to install, update or remove');
  550. }
  551. if ($localRepoTransaction->getOperations()) {
  552. $installs = $updates = $uninstalls = array();
  553. foreach ($localRepoTransaction->getOperations() as $operation) {
  554. if ($operation instanceof InstallOperation) {
  555. $installs[] = $operation->getPackage()->getPrettyName().':'.$operation->getPackage()->getFullPrettyVersion();
  556. } elseif ($operation instanceof UpdateOperation) {
  557. $updates[] = $operation->getTargetPackage()->getPrettyName().':'.$operation->getTargetPackage()->getFullPrettyVersion();
  558. } elseif ($operation instanceof UninstallOperation) {
  559. $uninstalls[] = $operation->getPackage()->getPrettyName();
  560. }
  561. }
  562. $this->io->writeError(sprintf(
  563. "<info>Package operations: %d install%s, %d update%s, %d removal%s</info>",
  564. count($installs),
  565. 1 === count($installs) ? '' : 's',
  566. count($updates),
  567. 1 === count($updates) ? '' : 's',
  568. count($uninstalls),
  569. 1 === count($uninstalls) ? '' : 's'
  570. ));
  571. if ($installs) {
  572. $this->io->writeError("Installs: ".implode(', ', $installs), true, IOInterface::VERBOSE);
  573. }
  574. if ($updates) {
  575. $this->io->writeError("Updates: ".implode(', ', $updates), true, IOInterface::VERBOSE);
  576. }
  577. if ($uninstalls) {
  578. $this->io->writeError("Removals: ".implode(', ', $uninstalls), true, IOInterface::VERBOSE);
  579. }
  580. }
  581. if ($this->executeOperations) {
  582. $this->installationManager->execute($localRepo, $localRepoTransaction->getOperations(), $this->devMode);
  583. } else {
  584. foreach ($localRepoTransaction->getOperations() as $operation) {
  585. // output op, but alias op only in debug verbosity
  586. if (false === strpos($operation->getOperationType(), 'Alias') || $this->io->isDebug()) {
  587. $this->io->writeError(' - ' . $operation->show(false));
  588. }
  589. }
  590. }
  591. return 0;
  592. }
  593. private function createPlatformRepo($forUpdate)
  594. {
  595. if ($forUpdate) {
  596. $platformOverrides = $this->config->get('platform') ?: array();
  597. } else {
  598. $platformOverrides = $this->locker->getPlatformOverrides();
  599. }
  600. return new PlatformRepository(array(), $platformOverrides);
  601. }
  602. /**
  603. * @param bool $forUpdate
  604. * @param PlatformRepository $platformRepo
  605. * @param array $rootAliases
  606. * @param RepositoryInterface|null $lockedRepository
  607. * @return RepositorySet
  608. */
  609. private function createRepositorySet($forUpdate, PlatformRepository $platformRepo, array $rootAliases = array(), $lockedRepository = null)
  610. {
  611. if ($forUpdate) {
  612. $minimumStability = $this->package->getMinimumStability();
  613. $stabilityFlags = $this->package->getStabilityFlags();
  614. $requires = array_merge($this->package->getRequires(), $this->package->getDevRequires());
  615. } else {
  616. $minimumStability = $this->locker->getMinimumStability();
  617. $stabilityFlags = $this->locker->getStabilityFlags();
  618. $requires = array();
  619. foreach ($lockedRepository->getPackages() as $package) {
  620. $constraint = new Constraint('=', $package->getVersion());
  621. $constraint->setPrettyString($package->getPrettyVersion());
  622. $requires[$package->getName()] = $constraint;
  623. }
  624. }
  625. $rootRequires = array();
  626. foreach ($requires as $req => $constraint) {
  627. // skip platform requirements from the root package to avoid filtering out existing platform packages
  628. if ($this->ignorePlatformReqs && preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $req)) {
  629. continue;
  630. }
  631. if ($constraint instanceof Link) {
  632. $rootRequires[$req] = $constraint->getConstraint();
  633. } else {
  634. $rootRequires[$req] = $constraint;
  635. }
  636. }
  637. $this->fixedRootPackage = clone $this->package;
  638. $this->fixedRootPackage->setRequires(array());
  639. $this->fixedRootPackage->setDevRequires(array());
  640. $repositorySet = new RepositorySet($minimumStability, $stabilityFlags, $rootAliases, $this->package->getReferences(), $rootRequires);
  641. $repositorySet->addRepository(new RootPackageRepository($this->fixedRootPackage));
  642. $repositorySet->addRepository($platformRepo);
  643. if ($this->additionalFixedRepository) {
  644. $repositorySet->addRepository($this->additionalFixedRepository);
  645. }
  646. return $repositorySet;
  647. }
  648. /**
  649. * @return DefaultPolicy
  650. */
  651. private function createPolicy($forUpdate)
  652. {
  653. $preferStable = null;
  654. $preferLowest = null;
  655. if (!$forUpdate) {
  656. $preferStable = $this->locker->getPreferStable();
  657. $preferLowest = $this->locker->getPreferLowest();
  658. }
  659. // old lock file without prefer stable/lowest will return null
  660. // so in this case we use the composer.json info
  661. if (null === $preferStable) {
  662. $preferStable = $this->preferStable || $this->package->getPreferStable();
  663. }
  664. if (null === $preferLowest) {
  665. $preferLowest = $this->preferLowest;
  666. }
  667. return new DefaultPolicy($preferStable, $preferLowest);
  668. }
  669. /**
  670. * @param RootPackageInterface $rootPackage
  671. * @param PlatformRepository $platformRepo
  672. * @param RepositoryInterface|null $lockedRepository
  673. * @return Request
  674. */
  675. private function createRequest(RootPackageInterface $rootPackage, PlatformRepository $platformRepo, $lockedRepository = null)
  676. {
  677. $request = new Request($lockedRepository);
  678. $request->fixPackage($rootPackage, false);
  679. if ($rootPackage instanceof RootAliasPackage) {
  680. $request->fixPackage($rootPackage->getAliasOf(), false);
  681. }
  682. $fixedPackages = $platformRepo->getPackages();
  683. if ($this->additionalFixedRepository) {
  684. $fixedPackages = array_merge($fixedPackages, $this->additionalFixedRepository->getPackages());
  685. }
  686. // fix the version of all platform packages + additionally installed packages
  687. // to prevent the solver trying to remove or update those
  688. // TODO why not replaces?
  689. $provided = $rootPackage->getProvides();
  690. foreach ($fixedPackages as $package) {
  691. // skip platform packages that are provided by the root package
  692. if ($package->getRepository() !== $platformRepo
  693. || !isset($provided[$package->getName()])
  694. || !$provided[$package->getName()]->getConstraint()->matches(new Constraint('=', $package->getVersion()))
  695. ) {
  696. $request->fixPackage($package, false);
  697. }
  698. }
  699. return $request;
  700. }
  701. /**
  702. * @param bool $forUpdate
  703. * @return array
  704. */
  705. private function getRootAliases($forUpdate)
  706. {
  707. if ($forUpdate) {
  708. $aliases = $this->package->getAliases();
  709. } else {
  710. $aliases = $this->locker->getAliases();
  711. }
  712. $normalizedAliases = array();
  713. foreach ($aliases as $alias) {
  714. $normalizedAliases[$alias['package']][$alias['version']] = array(
  715. 'alias' => $alias['alias'],
  716. 'alias_normalized' => $alias['alias_normalized'],
  717. );
  718. }
  719. return $normalizedAliases;
  720. }
  721. /**
  722. * @param array $links
  723. * @return array
  724. */
  725. private function extractPlatformRequirements($links)
  726. {
  727. $platformReqs = array();
  728. foreach ($links as $link) {
  729. if (preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $link->getTarget())) {
  730. $platformReqs[$link->getTarget()] = $link->getPrettyConstraint();
  731. }
  732. }
  733. return $platformReqs;
  734. }
  735. /**
  736. * Replace local repositories with InstalledArrayRepository instances
  737. *
  738. * This is to prevent any accidental modification of the existing repos on disk
  739. *
  740. * @param RepositoryManager $rm
  741. */
  742. private function mockLocalRepositories(RepositoryManager $rm)
  743. {
  744. $packages = array();
  745. foreach ($rm->getLocalRepository()->getPackages() as $package) {
  746. $packages[(string) $package] = clone $package;
  747. }
  748. foreach ($packages as $key => $package) {
  749. if ($package instanceof AliasPackage) {
  750. $alias = (string) $package->getAliasOf();
  751. $packages[$key] = new AliasPackage($packages[$alias], $package->getVersion(), $package->getPrettyVersion());
  752. }
  753. }
  754. $rm->setLocalRepository(
  755. new InstalledArrayRepository($packages)
  756. );
  757. }
  758. /**
  759. * Create Installer
  760. *
  761. * @param IOInterface $io
  762. * @param Composer $composer
  763. * @return Installer
  764. */
  765. public static function create(IOInterface $io, Composer $composer)
  766. {
  767. return new static(
  768. $io,
  769. $composer->getConfig(),
  770. $composer->getPackage(),
  771. $composer->getDownloadManager(),
  772. $composer->getRepositoryManager(),
  773. $composer->getLocker(),
  774. $composer->getInstallationManager(),
  775. $composer->getEventDispatcher(),
  776. $composer->getAutoloadGenerator()
  777. );
  778. }
  779. /**
  780. * @param RepositoryInterface $additionalFixedRepository
  781. * @return $this
  782. */
  783. public function setAdditionalFixedRepository(RepositoryInterface $additionalFixedRepository)
  784. {
  785. $this->additionalFixedRepository = $additionalFixedRepository;
  786. return $this;
  787. }
  788. /**
  789. * Whether to run in drymode or not
  790. *
  791. * @param bool $dryRun
  792. * @return Installer
  793. */
  794. public function setDryRun($dryRun = true)
  795. {
  796. $this->dryRun = (bool) $dryRun;
  797. return $this;
  798. }
  799. /**
  800. * Checks, if this is a dry run (simulation mode).
  801. *
  802. * @return bool
  803. */
  804. public function isDryRun()
  805. {
  806. return $this->dryRun;
  807. }
  808. /**
  809. * prefer source installation
  810. *
  811. * @param bool $preferSource
  812. * @return Installer
  813. */
  814. public function setPreferSource($preferSource = true)
  815. {
  816. $this->preferSource = (bool) $preferSource;
  817. return $this;
  818. }
  819. /**
  820. * prefer dist installation
  821. *
  822. * @param bool $preferDist
  823. * @return Installer
  824. */
  825. public function setPreferDist($preferDist = true)
  826. {
  827. $this->preferDist = (bool) $preferDist;
  828. return $this;
  829. }
  830. /**
  831. * Whether or not generated autoloader are optimized
  832. *
  833. * @param bool $optimizeAutoloader
  834. * @return Installer
  835. */
  836. public function setOptimizeAutoloader($optimizeAutoloader = false)
  837. {
  838. $this->optimizeAutoloader = (bool) $optimizeAutoloader;
  839. if (!$this->optimizeAutoloader) {
  840. // Force classMapAuthoritative off when not optimizing the
  841. // autoloader
  842. $this->setClassMapAuthoritative(false);
  843. }
  844. return $this;
  845. }
  846. /**
  847. * Whether or not generated autoloader considers the class map
  848. * authoritative.
  849. *
  850. * @param bool $classMapAuthoritative
  851. * @return Installer
  852. */
  853. public function setClassMapAuthoritative($classMapAuthoritative = false)
  854. {
  855. $this->classMapAuthoritative = (bool) $classMapAuthoritative;
  856. if ($this->classMapAuthoritative) {
  857. // Force optimizeAutoloader when classmap is authoritative
  858. $this->setOptimizeAutoloader(true);
  859. }
  860. return $this;
  861. }
  862. /**
  863. * Whether or not generated autoloader considers APCu caching.
  864. *
  865. * @param bool $apcuAutoloader
  866. * @return Installer
  867. */
  868. public function setApcuAutoloader($apcuAutoloader = false)
  869. {
  870. $this->apcuAutoloader = (bool) $apcuAutoloader;
  871. return $this;
  872. }
  873. /**
  874. * update packages
  875. *
  876. * @param bool $update
  877. * @return Installer
  878. */
  879. public function setUpdate($update = true)
  880. {
  881. $this->update = (bool) $update;
  882. return $this;
  883. }
  884. /**
  885. * enables dev packages
  886. *
  887. * @param bool $devMode
  888. * @return Installer
  889. */
  890. public function setDevMode($devMode = true)
  891. {
  892. $this->devMode = (bool) $devMode;
  893. return $this;
  894. }
  895. /**
  896. * set whether to run autoloader or not
  897. *
  898. * This is disabled implicitly when enabling dryRun
  899. *
  900. * @param bool $dumpAutoloader
  901. * @return Installer
  902. */
  903. public function setDumpAutoloader($dumpAutoloader = true)
  904. {
  905. $this->dumpAutoloader = (bool) $dumpAutoloader;
  906. return $this;
  907. }
  908. /**
  909. * set whether to run scripts or not
  910. *
  911. * This is disabled implicitly when enabling dryRun
  912. *
  913. * @param bool $runScripts
  914. * @return Installer
  915. */
  916. public function setRunScripts($runScripts = true)
  917. {
  918. $this->runScripts = (bool) $runScripts;
  919. return $this;
  920. }
  921. /**
  922. * set the config instance
  923. *
  924. * @param Config $config
  925. * @return Installer
  926. */
  927. public function setConfig(Config $config)
  928. {
  929. $this->config = $config;
  930. return $this;
  931. }
  932. /**
  933. * run in verbose mode
  934. *
  935. * @param bool $verbose
  936. * @return Installer
  937. */
  938. public function setVerbose($verbose = true)
  939. {
  940. $this->verbose = (bool) $verbose;
  941. return $this;
  942. }
  943. /**
  944. * Checks, if running in verbose mode.
  945. *
  946. * @return bool
  947. */
  948. public function isVerbose()
  949. {
  950. return $this->verbose;
  951. }
  952. /**
  953. * set ignore Platform Package requirements
  954. *
  955. * @param bool $ignorePlatformReqs
  956. * @return Installer
  957. */
  958. public function setIgnorePlatformRequirements($ignorePlatformReqs = false)
  959. {
  960. $this->ignorePlatformReqs = (bool) $ignorePlatformReqs;
  961. return $this;
  962. }
  963. /**
  964. * Update the lock file to the exact same versions and references but use current remote metadata like URLs and mirror info
  965. *
  966. * @param bool $updateMirrors
  967. * @return Installer
  968. */
  969. public function setUpdateMirrors($updateMirrors)
  970. {
  971. $this->updateMirrors = $updateMirrors;
  972. return $this;
  973. }
  974. /**
  975. * restrict the update operation to a few packages, all other packages
  976. * that are already installed will be kept at their current version
  977. *
  978. * @param array $packages
  979. * @return Installer
  980. */
  981. public function setUpdateAllowList(array $packages)
  982. {
  983. $this->updateAllowList = array_flip(array_map('strtolower', $packages));
  984. return $this;
  985. }
  986. /**
  987. * Should dependencies of packages marked for update be updated?
  988. *
  989. * Depending on the chosen constant this will either only update the directly named packages, all transitive
  990. * dependencies which are not root requirement or all transitive dependencies including root requirements
  991. *
  992. * @param int $updateAllowTransitiveDependencies One of the UPDATE_ constants on the Request class
  993. * @return Installer
  994. */
  995. public function setUpdateAllowTransitiveDependencies($updateAllowTransitiveDependencies)
  996. {
  997. if (!in_array($updateAllowTransitiveDependencies, array(Request::UPDATE_ONLY_LISTED, Request::UPDATE_LISTED_WITH_TRANSITIVE_DEPS_NO_ROOT_REQUIRE, Request::UPDATE_LISTED_WITH_TRANSITIVE_DEPS), true)) {
  998. throw new \RuntimeException("Invalid value for updateAllowTransitiveDependencies supplied");
  999. }
  1000. $this->updateAllowTransitiveDependencies = $updateAllowTransitiveDependencies;
  1001. return $this;
  1002. }
  1003. /**
  1004. * Should packages be preferred in a stable version when updating?
  1005. *
  1006. * @param bool $preferStable
  1007. * @return Installer
  1008. */
  1009. public function setPreferStable($preferStable = true)
  1010. {
  1011. $this->preferStable = (bool) $preferStable;
  1012. return $this;
  1013. }
  1014. /**
  1015. * Should packages be preferred in a lowest version when updating?
  1016. *
  1017. * @param bool $preferLowest
  1018. * @return Installer
  1019. */
  1020. public function setPreferLowest($preferLowest = true)
  1021. {
  1022. $this->preferLowest = (bool) $preferLowest;
  1023. return $this;
  1024. }
  1025. /**
  1026. * Should the lock file be updated when updating?
  1027. *
  1028. * This is disabled implicitly when enabling dryRun
  1029. *
  1030. * @param bool $writeLock
  1031. * @return Installer
  1032. */
  1033. public function setWriteLock($writeLock = true)
  1034. {
  1035. $this->writeLock = (bool) $writeLock;
  1036. return $this;
  1037. }
  1038. /**
  1039. * Should the operations (package install, update and removal) be executed on disk?
  1040. *
  1041. * This is disabled implicitly when enabling dryRun
  1042. *
  1043. * @param bool $executeOperations
  1044. * @return Installer
  1045. */
  1046. public function setExecuteOperations($executeOperations = true)
  1047. {
  1048. $this->executeOperations = (bool) $executeOperations;
  1049. return $this;
  1050. }
  1051. /**
  1052. * Disables plugins.
  1053. *
  1054. * Call this if you want to ensure that third-party code never gets
  1055. * executed. The default is to automatically install, and execute
  1056. * custom third-party installers.
  1057. *
  1058. * @return Installer
  1059. */
  1060. public function disablePlugins()
  1061. {
  1062. $this->installationManager->disablePlugins();
  1063. return $this;
  1064. }
  1065. /**
  1066. * @param SuggestedPackagesReporter $suggestedPackagesReporter
  1067. * @return Installer
  1068. */
  1069. public function setSuggestedPackagesReporter(SuggestedPackagesReporter $suggestedPackagesReporter)
  1070. {
  1071. $this->suggestedPackagesReporter = $suggestedPackagesReporter;
  1072. return $this;
  1073. }
  1074. }