Installer.php 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073
  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\Operation\UpdateOperation;
  15. use Composer\DependencyResolver\Operation\InstallOperation;
  16. use Composer\DependencyResolver\Operation\UninstallOperation;
  17. use Composer\DependencyResolver\Operation\OperationInterface;
  18. use Composer\DependencyResolver\Pool;
  19. use Composer\DependencyResolver\Request;
  20. use Composer\DependencyResolver\Rule;
  21. use Composer\DependencyResolver\Solver;
  22. use Composer\DependencyResolver\SolverProblemsException;
  23. use Composer\Downloader\DownloadManager;
  24. use Composer\EventDispatcher\EventDispatcher;
  25. use Composer\Installer\InstallationManager;
  26. use Composer\Config;
  27. use Composer\Installer\NoopInstaller;
  28. use Composer\IO\IOInterface;
  29. use Composer\Json\JsonFile;
  30. use Composer\Package\AliasPackage;
  31. use Composer\Package\Link;
  32. use Composer\Package\LinkConstraint\VersionConstraint;
  33. use Composer\Package\Locker;
  34. use Composer\Package\PackageInterface;
  35. use Composer\Package\RootPackageInterface;
  36. use Composer\Repository\CompositeRepository;
  37. use Composer\Repository\InstalledArrayRepository;
  38. use Composer\Repository\InstalledFilesystemRepository;
  39. use Composer\Repository\PlatformRepository;
  40. use Composer\Repository\RepositoryInterface;
  41. use Composer\Repository\RepositoryManager;
  42. use Composer\Script\ScriptEvents;
  43. /**
  44. * @author Jordi Boggiano <j.boggiano@seld.be>
  45. * @author Beau Simensen <beau@dflydev.com>
  46. * @author Konstantin Kudryashov <ever.zet@gmail.com>
  47. * @author Nils Adermann <naderman@naderman.de>
  48. */
  49. class Installer
  50. {
  51. /**
  52. * @var IOInterface
  53. */
  54. protected $io;
  55. /**
  56. * @var Config
  57. */
  58. protected $config;
  59. /**
  60. * @var RootPackageInterface
  61. */
  62. protected $package;
  63. /**
  64. * @var DownloadManager
  65. */
  66. protected $downloadManager;
  67. /**
  68. * @var RepositoryManager
  69. */
  70. protected $repositoryManager;
  71. /**
  72. * @var Locker
  73. */
  74. protected $locker;
  75. /**
  76. * @var InstallationManager
  77. */
  78. protected $installationManager;
  79. /**
  80. * @var EventDispatcher
  81. */
  82. protected $eventDispatcher;
  83. /**
  84. * @var AutoloadGenerator
  85. */
  86. protected $autoloadGenerator;
  87. protected $preferSource = false;
  88. protected $preferDist = false;
  89. protected $optimizeAutoloader = false;
  90. protected $devMode = false;
  91. protected $dryRun = false;
  92. protected $verbose = false;
  93. protected $update = false;
  94. protected $runScripts = true;
  95. protected $updateWhitelist = null;
  96. /**
  97. * @var array
  98. */
  99. protected $suggestedPackages;
  100. /**
  101. * @var RepositoryInterface
  102. */
  103. protected $additionalInstalledRepository;
  104. /**
  105. * Constructor
  106. *
  107. * @param IOInterface $io
  108. * @param Config $config
  109. * @param RootPackageInterface $package
  110. * @param DownloadManager $downloadManager
  111. * @param RepositoryManager $repositoryManager
  112. * @param Locker $locker
  113. * @param InstallationManager $installationManager
  114. * @param EventDispatcher $eventDispatcher
  115. * @param AutoloadGenerator $autoloadGenerator
  116. */
  117. public function __construct(IOInterface $io, Config $config, RootPackageInterface $package, DownloadManager $downloadManager, RepositoryManager $repositoryManager, Locker $locker, InstallationManager $installationManager, EventDispatcher $eventDispatcher, AutoloadGenerator $autoloadGenerator)
  118. {
  119. $this->io = $io;
  120. $this->config = $config;
  121. $this->package = $package;
  122. $this->downloadManager = $downloadManager;
  123. $this->repositoryManager = $repositoryManager;
  124. $this->locker = $locker;
  125. $this->installationManager = $installationManager;
  126. $this->eventDispatcher = $eventDispatcher;
  127. $this->autoloadGenerator = $autoloadGenerator;
  128. }
  129. /**
  130. * Run installation (or update)
  131. */
  132. public function run()
  133. {
  134. if ($this->dryRun) {
  135. $this->verbose = true;
  136. $this->runScripts = false;
  137. $this->installationManager->addInstaller(new NoopInstaller);
  138. $this->mockLocalRepositories($this->repositoryManager);
  139. }
  140. // TODO remove this BC feature at some point
  141. // purge old require-dev packages to avoid conflicts with the new way of handling dev requirements
  142. $devRepo = new InstalledFilesystemRepository(new JsonFile($this->config->get('vendor-dir').'/composer/installed_dev.json'));
  143. if ($devRepo->getPackages()) {
  144. $this->io->write('<warning>BC Notice: Removing old dev packages to migrate to the new require-dev handling.</warning>');
  145. foreach ($devRepo->getPackages() as $package) {
  146. if ($this->installationManager->isPackageInstalled($devRepo, $package)) {
  147. $this->installationManager->uninstall($devRepo, new UninstallOperation($package));
  148. }
  149. }
  150. unlink($this->config->get('vendor-dir').'/composer/installed_dev.json');
  151. }
  152. unset($devRepo, $package);
  153. // end BC
  154. if ($this->preferSource) {
  155. $this->downloadManager->setPreferSource(true);
  156. }
  157. if ($this->preferDist) {
  158. $this->downloadManager->setPreferDist(true);
  159. }
  160. // clone root package to have one in the installed repo that does not require anything
  161. // we don't want it to be uninstallable, but its requirements should not conflict
  162. // with the lock file for example
  163. $installedRootPackage = clone $this->package;
  164. $installedRootPackage->setRequires(array());
  165. $installedRootPackage->setDevRequires(array());
  166. // create installed repo, this contains all local packages + platform packages (php & extensions)
  167. $localRepo = $this->repositoryManager->getLocalRepository();
  168. $platformRepo = new PlatformRepository();
  169. $repos = array(
  170. $localRepo,
  171. new InstalledArrayRepository(array($installedRootPackage)),
  172. $platformRepo,
  173. );
  174. $installedRepo = new CompositeRepository($repos);
  175. if ($this->additionalInstalledRepository) {
  176. $installedRepo->addRepository($this->additionalInstalledRepository);
  177. }
  178. $aliases = $this->getRootAliases();
  179. $this->aliasPlatformPackages($platformRepo, $aliases);
  180. if ($this->runScripts) {
  181. // dispatch pre event
  182. $eventName = $this->update ? ScriptEvents::PRE_UPDATE_CMD : ScriptEvents::PRE_INSTALL_CMD;
  183. $this->eventDispatcher->dispatchCommandEvent($eventName, $this->devMode);
  184. }
  185. try {
  186. $this->suggestedPackages = array();
  187. if (!$this->doInstall($localRepo, $installedRepo, $platformRepo, $aliases, $this->devMode)) {
  188. return false;
  189. }
  190. } catch (\Exception $e) {
  191. $this->installationManager->notifyInstalls();
  192. throw $e;
  193. }
  194. $this->installationManager->notifyInstalls();
  195. // output suggestions
  196. foreach ($this->suggestedPackages as $suggestion) {
  197. $target = $suggestion['target'];
  198. foreach ($installedRepo->getPackages() as $package) {
  199. if (in_array($target, $package->getNames())) {
  200. continue 2;
  201. }
  202. }
  203. $this->io->write($suggestion['source'].' suggests installing '.$suggestion['target'].' ('.$suggestion['reason'].')');
  204. }
  205. if (!$this->dryRun) {
  206. // write lock
  207. if ($this->update || !$this->locker->isLocked()) {
  208. $localRepo->reload();
  209. // if this is not run in dev mode and the root has dev requires, the lock must
  210. // contain null to prevent dev installs from a non-dev lock
  211. $devPackages = ($this->devMode || !$this->package->getDevRequires()) ? array() : null;
  212. // split dev and non-dev requirements by checking what would be removed if we update without the dev requirements
  213. if ($this->devMode && $this->package->getDevRequires()) {
  214. $policy = $this->createPolicy();
  215. $pool = $this->createPool();
  216. $pool->addRepository($installedRepo, $aliases);
  217. // creating requirements request
  218. $request = $this->createRequest($pool, $this->package, $platformRepo);
  219. $request->updateAll();
  220. foreach ($this->package->getRequires() as $link) {
  221. $request->install($link->getTarget(), $link->getConstraint());
  222. }
  223. $solver = new Solver($policy, $pool, $installedRepo);
  224. $ops = $solver->solve($request);
  225. foreach ($ops as $op) {
  226. if ($op->getJobType() === 'uninstall') {
  227. $devPackages[] = $op->getPackage();
  228. }
  229. }
  230. }
  231. $platformReqs = $this->extractPlatformRequirements($this->package->getRequires());
  232. $platformDevReqs = $this->devMode ? $this->extractPlatformRequirements($this->package->getDevRequires()) : array();
  233. $updatedLock = $this->locker->setLockData(
  234. array_diff($localRepo->getCanonicalPackages(), (array) $devPackages),
  235. $devPackages,
  236. $platformReqs,
  237. $platformDevReqs,
  238. $aliases,
  239. $this->package->getMinimumStability(),
  240. $this->package->getStabilityFlags()
  241. );
  242. if ($updatedLock) {
  243. $this->io->write('<info>Writing lock file</info>');
  244. }
  245. }
  246. // write autoloader
  247. $this->io->write('<info>Generating autoload files</info>');
  248. $this->autoloadGenerator->dump($this->config, $localRepo, $this->package, $this->installationManager, 'composer', $this->optimizeAutoloader);
  249. if ($this->runScripts) {
  250. // dispatch post event
  251. $eventName = $this->update ? ScriptEvents::POST_UPDATE_CMD : ScriptEvents::POST_INSTALL_CMD;
  252. $this->eventDispatcher->dispatchCommandEvent($eventName, $this->devMode);
  253. }
  254. }
  255. return true;
  256. }
  257. protected function doInstall($localRepo, $installedRepo, $platformRepo, $aliases, $withDevReqs)
  258. {
  259. // init vars
  260. $lockedRepository = null;
  261. $repositories = null;
  262. // initialize locker to create aliased packages
  263. $installFromLock = false;
  264. if (!$this->update && $this->locker->isLocked()) {
  265. $installFromLock = true;
  266. try {
  267. $lockedRepository = $this->locker->getLockedRepository($withDevReqs);
  268. } catch (\RuntimeException $e) {
  269. // if there are dev requires, then we really can not install
  270. if ($this->package->getDevRequires()) {
  271. throw $e;
  272. }
  273. // no require-dev in composer.json and the lock file was created with no dev info, so skip them
  274. $lockedRepository = $this->locker->getLockedRepository();
  275. }
  276. }
  277. $this->whitelistUpdateDependencies(
  278. $localRepo,
  279. $withDevReqs,
  280. $this->package->getRequires(),
  281. $this->package->getDevRequires()
  282. );
  283. $this->io->write('<info>Loading composer repositories with package information</info>');
  284. // creating repository pool
  285. $policy = $this->createPolicy();
  286. $pool = $this->createPool();
  287. $pool->addRepository($installedRepo, $aliases);
  288. if ($installFromLock) {
  289. $pool->addRepository($lockedRepository, $aliases);
  290. }
  291. if (!$installFromLock) {
  292. $repositories = $this->repositoryManager->getRepositories();
  293. foreach ($repositories as $repository) {
  294. $pool->addRepository($repository, $aliases);
  295. }
  296. }
  297. // creating requirements request
  298. $request = $this->createRequest($pool, $this->package, $platformRepo);
  299. if (!$installFromLock) {
  300. // remove unstable packages from the localRepo if they don't match the current stability settings
  301. $removedUnstablePackages = array();
  302. foreach ($localRepo->getPackages() as $package) {
  303. if (
  304. !$pool->isPackageAcceptable($package->getNames(), $package->getStability())
  305. && $this->installationManager->isPackageInstalled($localRepo, $package)
  306. ) {
  307. $removedUnstablePackages[$package->getName()] = true;
  308. $request->remove($package->getName(), new VersionConstraint('=', $package->getVersion()));
  309. }
  310. }
  311. }
  312. if ($this->update) {
  313. $this->io->write('<info>Updating dependencies'.($withDevReqs?' (including require-dev)':'').'</info>');
  314. $request->updateAll();
  315. if ($withDevReqs) {
  316. $links = array_merge($this->package->getRequires(), $this->package->getDevRequires());
  317. } else {
  318. $links = $this->package->getRequires();
  319. }
  320. foreach ($links as $link) {
  321. $request->install($link->getTarget(), $link->getConstraint());
  322. }
  323. // if the updateWhitelist is enabled, packages not in it are also fixed
  324. // to the version specified in the lock, or their currently installed version
  325. if ($this->updateWhitelist) {
  326. if ($this->locker->isLocked()) {
  327. try {
  328. $currentPackages = $this->locker->getLockedRepository($withDevReqs)->getPackages();
  329. } catch (\RuntimeException $e) {
  330. // fetch only non-dev packages from lock if doing a dev update fails due to a previously incomplete lock file
  331. $currentPackages = $this->locker->getLockedRepository()->getPackages();
  332. }
  333. } else {
  334. $currentPackages = $installedRepo->getPackages();
  335. }
  336. // collect packages to fixate from root requirements as well as installed packages
  337. $candidates = array();
  338. foreach ($links as $link) {
  339. $candidates[$link->getTarget()] = true;
  340. }
  341. foreach ($localRepo->getPackages() as $package) {
  342. $candidates[$package->getName()] = true;
  343. }
  344. // fix them to the version in lock (or currently installed) if they are not updateable
  345. foreach ($candidates as $candidate => $dummy) {
  346. foreach ($currentPackages as $curPackage) {
  347. if ($curPackage->getName() === $candidate) {
  348. if (!$this->isUpdateable($curPackage) && !isset($removedUnstablePackages[$curPackage->getName()])) {
  349. $constraint = new VersionConstraint('=', $curPackage->getVersion());
  350. $request->install($curPackage->getName(), $constraint);
  351. }
  352. break;
  353. }
  354. }
  355. }
  356. }
  357. } elseif ($installFromLock) {
  358. $this->io->write('<info>Installing dependencies'.($withDevReqs?' (including require-dev)':'').' from lock file</info>');
  359. if (!$this->locker->isFresh()) {
  360. $this->io->write('<warning>Warning: The lock file is not up to date with the latest changes in composer.json. You may be getting outdated dependencies. Run update to update them.</warning>');
  361. }
  362. foreach ($lockedRepository->getPackages() as $package) {
  363. $version = $package->getVersion();
  364. if (isset($aliases[$package->getName()][$version])) {
  365. $version = $aliases[$package->getName()][$version]['alias_normalized'];
  366. }
  367. $constraint = new VersionConstraint('=', $version);
  368. $constraint->setPrettyString($package->getPrettyVersion());
  369. $request->install($package->getName(), $constraint);
  370. }
  371. foreach ($this->locker->getPlatformRequirements($withDevReqs) as $link) {
  372. $request->install($link->getTarget(), $link->getConstraint());
  373. }
  374. } else {
  375. $this->io->write('<info>Installing dependencies'.($withDevReqs?' (including require-dev)':'').'</info>');
  376. if ($withDevReqs) {
  377. $links = array_merge($this->package->getRequires(), $this->package->getDevRequires());
  378. } else {
  379. $links = $this->package->getRequires();
  380. }
  381. foreach ($links as $link) {
  382. $request->install($link->getTarget(), $link->getConstraint());
  383. }
  384. }
  385. // force dev packages to have the latest links if we update or install from a (potentially new) lock
  386. $this->processDevPackages($localRepo, $pool, $policy, $repositories, $lockedRepository, $installFromLock, 'force-links');
  387. // solve dependencies
  388. $solver = new Solver($policy, $pool, $installedRepo);
  389. try {
  390. $operations = $solver->solve($request);
  391. } catch (SolverProblemsException $e) {
  392. $this->io->write('<error>Your requirements could not be resolved to an installable set of packages.</error>');
  393. $this->io->write($e->getMessage());
  394. return false;
  395. }
  396. // force dev packages to be updated if we update or install from a (potentially new) lock
  397. $operations = $this->processDevPackages($localRepo, $pool, $policy, $repositories, $lockedRepository, $installFromLock, 'force-updates', $operations);
  398. // execute operations
  399. if (!$operations) {
  400. $this->io->write('Nothing to install or update');
  401. }
  402. $operations = $this->movePluginsToFront($operations);
  403. foreach ($operations as $operation) {
  404. // collect suggestions
  405. if ('install' === $operation->getJobType()) {
  406. foreach ($operation->getPackage()->getSuggests() as $target => $reason) {
  407. $this->suggestedPackages[] = array(
  408. 'source' => $operation->getPackage()->getPrettyName(),
  409. 'target' => $target,
  410. 'reason' => $reason,
  411. );
  412. }
  413. }
  414. $event = 'Composer\Script\ScriptEvents::PRE_PACKAGE_'.strtoupper($operation->getJobType());
  415. if (defined($event) && $this->runScripts) {
  416. $this->eventDispatcher->dispatchPackageEvent(constant($event), $this->devMode, $operation);
  417. }
  418. // not installing from lock, force dev packages' references if they're in root package refs
  419. if (!$installFromLock) {
  420. $package = null;
  421. if ('update' === $operation->getJobType()) {
  422. $package = $operation->getTargetPackage();
  423. } elseif ('install' === $operation->getJobType()) {
  424. $package = $operation->getPackage();
  425. }
  426. if ($package && $package->isDev()) {
  427. $references = $this->package->getReferences();
  428. if (isset($references[$package->getName()])) {
  429. $package->setSourceReference($references[$package->getName()]);
  430. $package->setDistReference($references[$package->getName()]);
  431. }
  432. }
  433. }
  434. // output non-alias ops in dry run, output alias ops in debug verbosity
  435. if ($this->dryRun && false === strpos($operation->getJobType(), 'Alias')) {
  436. $this->io->write(' - ' . $operation);
  437. $this->io->write('');
  438. } elseif ($this->io->isDebug() && false !== strpos($operation->getJobType(), 'Alias')) {
  439. $this->io->write(' - ' . $operation);
  440. $this->io->write('');
  441. }
  442. $this->installationManager->execute($localRepo, $operation);
  443. // output reasons why the operation was ran, only for install/update operations
  444. if ($this->verbose && $this->io->isVeryVerbose() && in_array($operation->getJobType(), array('install', 'update'))) {
  445. $reason = $operation->getReason();
  446. if ($reason instanceof Rule) {
  447. switch ($reason->getReason()) {
  448. case Rule::RULE_JOB_INSTALL:
  449. $this->io->write(' REASON: Required by root: '.$reason->getRequiredPackage());
  450. $this->io->write('');
  451. break;
  452. case Rule::RULE_PACKAGE_REQUIRES:
  453. $this->io->write(' REASON: '.$reason->getPrettyString());
  454. $this->io->write('');
  455. break;
  456. }
  457. }
  458. }
  459. $event = 'Composer\Script\ScriptEvents::POST_PACKAGE_'.strtoupper($operation->getJobType());
  460. if (defined($event) && $this->runScripts) {
  461. $this->eventDispatcher->dispatchPackageEvent(constant($event), $this->devMode, $operation);
  462. }
  463. if (!$this->dryRun) {
  464. $localRepo->write();
  465. }
  466. }
  467. return true;
  468. }
  469. /**
  470. * Workaround: if your packages depend on plugins, we must be sure
  471. * that those are installed / updated first; else it would lead to packages
  472. * being installed multiple times in different folders, when running Composer
  473. * twice.
  474. *
  475. * While this does not fix the root-causes of https://github.com/composer/composer/issues/1147,
  476. * it at least fixes the symptoms and makes usage of composer possible (again)
  477. * in such scenarios.
  478. *
  479. * @param OperationInterface[] $operations
  480. * @return OperationInterface[] reordered operation list
  481. */
  482. private function movePluginsToFront(array $operations)
  483. {
  484. $installerOps = array();
  485. foreach ($operations as $idx => $op) {
  486. if ($op instanceof InstallOperation) {
  487. $package = $op->getPackage();
  488. } else if ($op instanceof UpdateOperation) {
  489. $package = $op->getTargetPackage();
  490. } else {
  491. continue;
  492. }
  493. if ($package->getRequires() === array() && ($package->getType() === 'composer-plugin' || $package->getType() === 'composer-installer')) {
  494. $installerOps[] = $op;
  495. unset($operations[$idx]);
  496. }
  497. }
  498. return array_merge($installerOps, $operations);
  499. }
  500. private function createPool()
  501. {
  502. $minimumStability = $this->package->getMinimumStability();
  503. $stabilityFlags = $this->package->getStabilityFlags();
  504. if (!$this->update && $this->locker->isLocked()) {
  505. $minimumStability = $this->locker->getMinimumStability();
  506. $stabilityFlags = $this->locker->getStabilityFlags();
  507. }
  508. return new Pool($minimumStability, $stabilityFlags);
  509. }
  510. private function createPolicy()
  511. {
  512. return new DefaultPolicy($this->package->getPreferStable());
  513. }
  514. private function createRequest(Pool $pool, RootPackageInterface $rootPackage, PlatformRepository $platformRepo)
  515. {
  516. $request = new Request($pool);
  517. $constraint = new VersionConstraint('=', $rootPackage->getVersion());
  518. $constraint->setPrettyString($rootPackage->getPrettyVersion());
  519. $request->install($rootPackage->getName(), $constraint);
  520. $fixedPackages = $platformRepo->getPackages();
  521. if ($this->additionalInstalledRepository) {
  522. $additionalFixedPackages = $this->additionalInstalledRepository->getPackages();
  523. $fixedPackages = array_merge($fixedPackages, $additionalFixedPackages);
  524. }
  525. // fix the version of all platform packages + additionally installed packages
  526. // to prevent the solver trying to remove or update those
  527. $provided = $rootPackage->getProvides();
  528. foreach ($fixedPackages as $package) {
  529. $constraint = new VersionConstraint('=', $package->getVersion());
  530. $constraint->setPrettyString($package->getPrettyVersion());
  531. // skip platform packages that are provided by the root package
  532. if ($package->getRepository() !== $platformRepo
  533. || !isset($provided[$package->getName()])
  534. || !$provided[$package->getName()]->getConstraint()->matches($constraint)
  535. ) {
  536. $request->install($package->getName(), $constraint);
  537. }
  538. }
  539. return $request;
  540. }
  541. private function processDevPackages($localRepo, $pool, $policy, $repositories, $lockedRepository, $installFromLock, $task, array $operations = null)
  542. {
  543. if ($task === 'force-updates' && null === $operations) {
  544. throw new \InvalidArgumentException('Missing operations argument');
  545. }
  546. if ($task === 'force-links') {
  547. $operations = array();
  548. }
  549. foreach ($localRepo->getCanonicalPackages() as $package) {
  550. // skip non-dev packages
  551. if (!$package->isDev()) {
  552. continue;
  553. }
  554. // skip packages that will be updated/uninstalled
  555. foreach ($operations as $operation) {
  556. if (('update' === $operation->getJobType() && $operation->getInitialPackage()->equals($package))
  557. || ('uninstall' === $operation->getJobType() && $operation->getPackage()->equals($package))
  558. ) {
  559. continue 2;
  560. }
  561. }
  562. // force update to locked version if it does not match the installed version
  563. if ($installFromLock) {
  564. foreach ($lockedRepository->findPackages($package->getName()) as $lockedPackage) {
  565. if ($lockedPackage->isDev() && $lockedPackage->getVersion() === $package->getVersion()) {
  566. if ($task === 'force-links') {
  567. $package->setRequires($lockedPackage->getRequires());
  568. $package->setConflicts($lockedPackage->getConflicts());
  569. $package->setProvides($lockedPackage->getProvides());
  570. $package->setReplaces($lockedPackage->getReplaces());
  571. } elseif ($task === 'force-updates') {
  572. if (($lockedPackage->getSourceReference() && $lockedPackage->getSourceReference() !== $package->getSourceReference())
  573. || ($lockedPackage->getDistReference() && $lockedPackage->getDistReference() !== $package->getDistReference())
  574. ) {
  575. $operations[] = new UpdateOperation($package, $lockedPackage);
  576. }
  577. }
  578. break;
  579. }
  580. }
  581. } else {
  582. // force update to latest on update
  583. if ($this->update) {
  584. // skip package if the whitelist is enabled and it is not in it
  585. if ($this->updateWhitelist && !$this->isUpdateable($package)) {
  586. continue;
  587. }
  588. // find similar packages (name/version) in all repositories
  589. $matches = $pool->whatProvides($package->getName(), new VersionConstraint('=', $package->getVersion()));
  590. foreach ($matches as $index => $match) {
  591. // skip local packages
  592. if (!in_array($match->getRepository(), $repositories, true)) {
  593. unset($matches[$index]);
  594. continue;
  595. }
  596. // skip providers/replacers
  597. if ($match->getName() !== $package->getName()) {
  598. unset($matches[$index]);
  599. continue;
  600. }
  601. $matches[$index] = $match->getId();
  602. }
  603. // select prefered package according to policy rules
  604. if ($matches && $matches = $policy->selectPreferedPackages($pool, array(), $matches)) {
  605. $newPackage = $pool->literalToPackage($matches[0]);
  606. if ($task === 'force-links' && $newPackage) {
  607. $package->setRequires($newPackage->getRequires());
  608. $package->setConflicts($newPackage->getConflicts());
  609. $package->setProvides($newPackage->getProvides());
  610. $package->setReplaces($newPackage->getReplaces());
  611. }
  612. if ($task === 'force-updates' && $newPackage && (
  613. (($newPackage->getSourceReference() && $newPackage->getSourceReference() !== $package->getSourceReference())
  614. || ($newPackage->getDistReference() && $newPackage->getDistReference() !== $package->getDistReference())
  615. )
  616. )) {
  617. $operations[] = new UpdateOperation($package, $newPackage);
  618. }
  619. }
  620. }
  621. if ($task === 'force-updates') {
  622. // force installed package to update to referenced version if it does not match the installed version
  623. $references = $this->package->getReferences();
  624. if (isset($references[$package->getName()]) && $references[$package->getName()] !== $package->getSourceReference()) {
  625. // changing the source ref to update to will be handled in the operations loop below
  626. $operations[] = new UpdateOperation($package, clone $package);
  627. }
  628. }
  629. }
  630. }
  631. return $operations;
  632. }
  633. private function getRootAliases()
  634. {
  635. if (!$this->update && $this->locker->isLocked()) {
  636. $aliases = $this->locker->getAliases();
  637. } else {
  638. $aliases = $this->package->getAliases();
  639. }
  640. $normalizedAliases = array();
  641. foreach ($aliases as $alias) {
  642. $normalizedAliases[$alias['package']][$alias['version']] = array(
  643. 'alias' => $alias['alias'],
  644. 'alias_normalized' => $alias['alias_normalized']
  645. );
  646. }
  647. return $normalizedAliases;
  648. }
  649. private function aliasPlatformPackages(PlatformRepository $platformRepo, $aliases)
  650. {
  651. foreach ($aliases as $package => $versions) {
  652. foreach ($versions as $version => $alias) {
  653. $packages = $platformRepo->findPackages($package, $version);
  654. foreach ($packages as $package) {
  655. $aliasPackage = new AliasPackage($package, $alias['alias_normalized'], $alias['alias']);
  656. $aliasPackage->setRootPackageAlias(true);
  657. $platformRepo->addPackage($aliasPackage);
  658. }
  659. }
  660. }
  661. }
  662. private function isUpdateable(PackageInterface $package)
  663. {
  664. if (!$this->updateWhitelist) {
  665. throw new \LogicException('isUpdateable should only be called when a whitelist is present');
  666. }
  667. foreach ($this->updateWhitelist as $whiteListedPattern => $void) {
  668. $cleanedWhiteListedPattern = str_replace('\\*', '.*', preg_quote($whiteListedPattern));
  669. if (preg_match("{^".$cleanedWhiteListedPattern."$}i", $package->getName())) {
  670. return true;
  671. }
  672. }
  673. return false;
  674. }
  675. private function extractPlatformRequirements($links)
  676. {
  677. $platformReqs = array();
  678. foreach ($links as $link) {
  679. if (preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $link->getTarget())) {
  680. $platformReqs[$link->getTarget()] = $link->getPrettyConstraint();
  681. }
  682. }
  683. return $platformReqs;
  684. }
  685. /**
  686. * Adds all dependencies of the update whitelist to the whitelist, too.
  687. *
  688. * Packages which are listed as requirements in the root package will be
  689. * skipped including their dependencies, unless they are listed in the
  690. * update whitelist themselves.
  691. *
  692. * @param RepositoryInterface $localRepo
  693. * @param boolean $devMode
  694. * @param array $rootRequires An array of links to packages in require of the root package
  695. * @param array $rootDevRequires An array of links to packages in require-dev of the root package
  696. */
  697. private function whitelistUpdateDependencies($localRepo, $devMode, array $rootRequires, array $rootDevRequires)
  698. {
  699. if (!$this->updateWhitelist) {
  700. return;
  701. }
  702. $requiredPackageNames = array();
  703. foreach (array_merge($rootRequires, $rootDevRequires) as $require) {
  704. $requiredPackageNames[] = $require->getTarget();
  705. }
  706. if ($devMode) {
  707. $rootRequires = array_merge($rootRequires, $rootDevRequires);
  708. }
  709. $skipPackages = array();
  710. foreach ($rootRequires as $require) {
  711. $skipPackages[$require->getTarget()] = true;
  712. }
  713. $pool = new Pool;
  714. $pool->addRepository($localRepo);
  715. $seen = array();
  716. foreach ($this->updateWhitelist as $packageName => $void) {
  717. $packageQueue = new \SplQueue;
  718. $depPackages = $pool->whatProvides($packageName);
  719. if (count($depPackages) == 0 && !in_array($packageName, $requiredPackageNames) && !in_array($packageName, array('nothing', 'lock'))) {
  720. $this->io->write('<warning>Package "' . $packageName . '" listed for update is not installed. Ignoring.<warning>');
  721. }
  722. foreach ($depPackages as $depPackage) {
  723. $packageQueue->enqueue($depPackage);
  724. }
  725. while (!$packageQueue->isEmpty()) {
  726. $package = $packageQueue->dequeue();
  727. if (isset($seen[$package->getId()])) {
  728. continue;
  729. }
  730. $seen[$package->getId()] = true;
  731. $this->updateWhitelist[$package->getName()] = true;
  732. $requires = $package->getRequires();
  733. if ($devMode) {
  734. $requires = array_merge($requires, $package->getDevRequires());
  735. }
  736. foreach ($requires as $require) {
  737. $requirePackages = $pool->whatProvides($require->getTarget());
  738. foreach ($requirePackages as $requirePackage) {
  739. if (isset($skipPackages[$requirePackage->getName()])) {
  740. continue;
  741. }
  742. $packageQueue->enqueue($requirePackage);
  743. }
  744. }
  745. }
  746. }
  747. }
  748. /**
  749. * Replace local repositories with InstalledArrayRepository instances
  750. *
  751. * This is to prevent any accidental modification of the existing repos on disk
  752. *
  753. * @param RepositoryManager $rm
  754. */
  755. private function mockLocalRepositories(RepositoryManager $rm)
  756. {
  757. $packages = array();
  758. foreach ($rm->getLocalRepository()->getPackages() as $package) {
  759. $packages[(string) $package] = clone $package;
  760. }
  761. foreach ($packages as $key => $package) {
  762. if ($package instanceof AliasPackage) {
  763. $alias = (string) $package->getAliasOf();
  764. $packages[$key] = new AliasPackage($packages[$alias], $package->getVersion(), $package->getPrettyVersion());
  765. }
  766. }
  767. $rm->setLocalRepository(
  768. new InstalledArrayRepository($packages)
  769. );
  770. }
  771. /**
  772. * Create Installer
  773. *
  774. * @param IOInterface $io
  775. * @param Composer $composer
  776. * @return Installer
  777. */
  778. public static function create(IOInterface $io, Composer $composer)
  779. {
  780. return new static(
  781. $io,
  782. $composer->getConfig(),
  783. $composer->getPackage(),
  784. $composer->getDownloadManager(),
  785. $composer->getRepositoryManager(),
  786. $composer->getLocker(),
  787. $composer->getInstallationManager(),
  788. $composer->getEventDispatcher(),
  789. $composer->getAutoloadGenerator()
  790. );
  791. }
  792. public function setAdditionalInstalledRepository(RepositoryInterface $additionalInstalledRepository)
  793. {
  794. $this->additionalInstalledRepository = $additionalInstalledRepository;
  795. return $this;
  796. }
  797. /**
  798. * Whether to run in drymode or not
  799. *
  800. * @param boolean $dryRun
  801. * @return Installer
  802. */
  803. public function setDryRun($dryRun = true)
  804. {
  805. $this->dryRun = (boolean) $dryRun;
  806. return $this;
  807. }
  808. /**
  809. * prefer source installation
  810. *
  811. * @param boolean $preferSource
  812. * @return Installer
  813. */
  814. public function setPreferSource($preferSource = true)
  815. {
  816. $this->preferSource = (boolean) $preferSource;
  817. return $this;
  818. }
  819. /**
  820. * prefer dist installation
  821. *
  822. * @param boolean $preferDist
  823. * @return Installer
  824. */
  825. public function setPreferDist($preferDist = true)
  826. {
  827. $this->preferDist = (boolean) $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 = (boolean) $optimizeAutoloader;
  839. return $this;
  840. }
  841. /**
  842. * update packages
  843. *
  844. * @param boolean $update
  845. * @return Installer
  846. */
  847. public function setUpdate($update = true)
  848. {
  849. $this->update = (boolean) $update;
  850. return $this;
  851. }
  852. /**
  853. * enables dev packages
  854. *
  855. * @param boolean $devMode
  856. * @return Installer
  857. */
  858. public function setDevMode($devMode = true)
  859. {
  860. $this->devMode = (boolean) $devMode;
  861. return $this;
  862. }
  863. /**
  864. * set whether to run scripts or not
  865. *
  866. * @param boolean $runScripts
  867. * @return Installer
  868. */
  869. public function setRunScripts($runScripts = true)
  870. {
  871. $this->runScripts = (boolean) $runScripts;
  872. return $this;
  873. }
  874. /**
  875. * set the config instance
  876. *
  877. * @param Config $config
  878. * @return Installer
  879. */
  880. public function setConfig(Config $config)
  881. {
  882. $this->config = $config;
  883. return $this;
  884. }
  885. /**
  886. * run in verbose mode
  887. *
  888. * @param boolean $verbose
  889. * @return Installer
  890. */
  891. public function setVerbose($verbose = true)
  892. {
  893. $this->verbose = (boolean) $verbose;
  894. return $this;
  895. }
  896. /**
  897. * restrict the update operation to a few packages, all other packages
  898. * that are already installed will be kept at their current version
  899. *
  900. * @param array $packages
  901. * @return Installer
  902. */
  903. public function setUpdateWhitelist(array $packages)
  904. {
  905. $this->updateWhitelist = array_flip(array_map('strtolower', $packages));
  906. return $this;
  907. }
  908. /**
  909. * Disables plugins.
  910. *
  911. * Call this if you want to ensure that third-party code never gets
  912. * executed. The default is to automatically install, and execute
  913. * custom third-party installers.
  914. *
  915. * @return Installer
  916. */
  917. public function disablePlugins()
  918. {
  919. $this->installationManager->disablePlugins();
  920. return $this;
  921. }
  922. }