Installer.php 42 KB

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