Installer.php 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827
  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\MarkAliasUninstalledOperation;
  18. use Composer\DependencyResolver\Operation\OperationInterface;
  19. use Composer\DependencyResolver\PolicyInterface;
  20. use Composer\DependencyResolver\Pool;
  21. use Composer\DependencyResolver\Request;
  22. use Composer\DependencyResolver\Rule;
  23. use Composer\DependencyResolver\Solver;
  24. use Composer\DependencyResolver\SolverProblemsException;
  25. use Composer\Downloader\DownloadManager;
  26. use Composer\EventDispatcher\EventDispatcher;
  27. use Composer\Installer\InstallationManager;
  28. use Composer\Installer\InstallerEvents;
  29. use Composer\Installer\NoopInstaller;
  30. use Composer\Installer\SuggestedPackagesReporter;
  31. use Composer\IO\IOInterface;
  32. use Composer\Package\AliasPackage;
  33. use Composer\Package\BasePackage;
  34. use Composer\Package\CompletePackage;
  35. use Composer\Package\CompletePackageInterface;
  36. use Composer\Package\Link;
  37. use Composer\Package\Loader\ArrayLoader;
  38. use Composer\Package\Dumper\ArrayDumper;
  39. use Composer\Semver\Constraint\Constraint;
  40. use Composer\Package\Locker;
  41. use Composer\Package\PackageInterface;
  42. use Composer\Package\RootPackageInterface;
  43. use Composer\Repository\CompositeRepository;
  44. use Composer\Repository\InstalledArrayRepository;
  45. use Composer\Repository\PlatformRepository;
  46. use Composer\Repository\RepositoryInterface;
  47. use Composer\Repository\RepositoryManager;
  48. use Composer\Repository\WritableRepositoryInterface;
  49. use Composer\Script\ScriptEvents;
  50. /**
  51. * @author Jordi Boggiano <j.boggiano@seld.be>
  52. * @author Beau Simensen <beau@dflydev.com>
  53. * @author Konstantin Kudryashov <ever.zet@gmail.com>
  54. * @author Nils Adermann <naderman@naderman.de>
  55. */
  56. class Installer
  57. {
  58. /**
  59. * @var IOInterface
  60. */
  61. protected $io;
  62. /**
  63. * @var Config
  64. */
  65. protected $config;
  66. /**
  67. * @var RootPackageInterface
  68. */
  69. protected $package;
  70. /**
  71. * @var DownloadManager
  72. */
  73. protected $downloadManager;
  74. /**
  75. * @var RepositoryManager
  76. */
  77. protected $repositoryManager;
  78. /**
  79. * @var Locker
  80. */
  81. protected $locker;
  82. /**
  83. * @var InstallationManager
  84. */
  85. protected $installationManager;
  86. /**
  87. * @var EventDispatcher
  88. */
  89. protected $eventDispatcher;
  90. /**
  91. * @var AutoloadGenerator
  92. */
  93. protected $autoloadGenerator;
  94. protected $preferSource = false;
  95. protected $preferDist = false;
  96. protected $optimizeAutoloader = false;
  97. protected $classMapAuthoritative = false;
  98. protected $apcuAutoloader = false;
  99. protected $devMode = false;
  100. protected $dryRun = false;
  101. protected $verbose = false;
  102. protected $update = false;
  103. protected $dumpAutoloader = true;
  104. protected $runScripts = true;
  105. protected $ignorePlatformReqs = false;
  106. protected $preferStable = false;
  107. protected $preferLowest = false;
  108. protected $skipSuggest = false;
  109. protected $writeLock;
  110. protected $executeOperations = true;
  111. /**
  112. * Array of package names/globs flagged for update
  113. *
  114. * @var array|null
  115. */
  116. protected $updateWhitelist = null;
  117. protected $whitelistDependencies = false; // TODO 2.0 rename to whitelistTransitiveDependencies
  118. protected $whitelistAllDependencies = false;
  119. /**
  120. * @var SuggestedPackagesReporter
  121. */
  122. protected $suggestedPackagesReporter;
  123. /**
  124. * @var RepositoryInterface
  125. */
  126. protected $additionalInstalledRepository;
  127. /**
  128. * Constructor
  129. *
  130. * @param IOInterface $io
  131. * @param Config $config
  132. * @param RootPackageInterface $package
  133. * @param DownloadManager $downloadManager
  134. * @param RepositoryManager $repositoryManager
  135. * @param Locker $locker
  136. * @param InstallationManager $installationManager
  137. * @param EventDispatcher $eventDispatcher
  138. * @param AutoloadGenerator $autoloadGenerator
  139. */
  140. public function __construct(IOInterface $io, Config $config, RootPackageInterface $package, DownloadManager $downloadManager, RepositoryManager $repositoryManager, Locker $locker, InstallationManager $installationManager, EventDispatcher $eventDispatcher, AutoloadGenerator $autoloadGenerator)
  141. {
  142. $this->io = $io;
  143. $this->config = $config;
  144. $this->package = $package;
  145. $this->downloadManager = $downloadManager;
  146. $this->repositoryManager = $repositoryManager;
  147. $this->locker = $locker;
  148. $this->installationManager = $installationManager;
  149. $this->eventDispatcher = $eventDispatcher;
  150. $this->autoloadGenerator = $autoloadGenerator;
  151. $this->writeLock = $config->get('lock');
  152. }
  153. /**
  154. * Run installation (or update)
  155. *
  156. * @throws \Exception
  157. * @return int 0 on success or a positive error code on failure
  158. */
  159. public function run()
  160. {
  161. // Disable GC to save CPU cycles, as the dependency solver can create hundreds of thousands
  162. // of PHP objects, the GC can spend quite some time walking the tree of references looking
  163. // for stuff to collect while there is nothing to collect. This slows things down dramatically
  164. // and turning it off results in much better performance. Do not try this at home however.
  165. gc_collect_cycles();
  166. gc_disable();
  167. // Force update if there is no lock file present
  168. if (!$this->update && !$this->locker->isLocked()) {
  169. $this->update = true;
  170. }
  171. if ($this->dryRun) {
  172. $this->verbose = true;
  173. $this->runScripts = false;
  174. $this->executeOperations = false;
  175. $this->writeLock = false;
  176. $this->dumpAutoloader = false;
  177. $this->installationManager->addInstaller(new NoopInstaller);
  178. $this->mockLocalRepositories($this->repositoryManager);
  179. }
  180. if ($this->runScripts) {
  181. $_SERVER['COMPOSER_DEV_MODE'] = (int) $this->devMode;
  182. putenv('COMPOSER_DEV_MODE='.$_SERVER['COMPOSER_DEV_MODE']);
  183. // dispatch pre event
  184. $eventName = $this->update ? ScriptEvents::PRE_UPDATE_CMD : ScriptEvents::PRE_INSTALL_CMD;
  185. $this->eventDispatcher->dispatchScript($eventName, $this->devMode);
  186. }
  187. $this->downloadManager->setPreferSource($this->preferSource);
  188. $this->downloadManager->setPreferDist($this->preferDist);
  189. // create installed repo, this contains all local packages + platform packages (php & extensions)
  190. $localRepo = $this->repositoryManager->getLocalRepository();
  191. if ($this->update) {
  192. $platformOverrides = $this->config->get('platform') ?: array();
  193. } else {
  194. $platformOverrides = $this->locker->getPlatformOverrides();
  195. }
  196. $platformRepo = new PlatformRepository(array(), $platformOverrides);
  197. $installedRepo = $this->createInstalledRepo($localRepo, $platformRepo);
  198. $aliases = $this->getRootAliases();
  199. $this->aliasPlatformPackages($platformRepo, $aliases);
  200. if (!$this->suggestedPackagesReporter) {
  201. $this->suggestedPackagesReporter = new SuggestedPackagesReporter($this->io);
  202. }
  203. try {
  204. list($res, $devPackages) = $this->doInstall($localRepo, $installedRepo, $platformRepo, $aliases);
  205. if ($res !== 0) {
  206. return $res;
  207. }
  208. } catch (\Exception $e) {
  209. if ($this->executeOperations && $this->config->get('notify-on-install')) {
  210. $this->installationManager->notifyInstalls($this->io);
  211. }
  212. throw $e;
  213. }
  214. if ($this->executeOperations && $this->config->get('notify-on-install')) {
  215. $this->installationManager->notifyInstalls($this->io);
  216. }
  217. // output suggestions if we're in dev mode
  218. if ($this->devMode && !$this->skipSuggest) {
  219. $this->suggestedPackagesReporter->output($installedRepo);
  220. }
  221. # Find abandoned packages and warn user
  222. foreach ($localRepo->getPackages() as $package) {
  223. if (!$package instanceof CompletePackage || !$package->isAbandoned()) {
  224. continue;
  225. }
  226. $replacement = is_string($package->getReplacementPackage())
  227. ? 'Use ' . $package->getReplacementPackage() . ' instead'
  228. : 'No replacement was suggested';
  229. $this->io->writeError(
  230. sprintf(
  231. "<warning>Package %s is abandoned, you should avoid using it. %s.</warning>",
  232. $package->getPrettyName(),
  233. $replacement
  234. )
  235. );
  236. }
  237. // write lock
  238. if ($this->update && $this->writeLock) {
  239. $localRepo->reload();
  240. $platformReqs = $this->extractPlatformRequirements($this->package->getRequires());
  241. $platformDevReqs = $this->extractPlatformRequirements($this->package->getDevRequires());
  242. $updatedLock = $this->locker->setLockData(
  243. array_diff($localRepo->getCanonicalPackages(), $devPackages),
  244. $devPackages,
  245. $platformReqs,
  246. $platformDevReqs,
  247. $aliases,
  248. $this->package->getMinimumStability(),
  249. $this->package->getStabilityFlags(),
  250. $this->preferStable || $this->package->getPreferStable(),
  251. $this->preferLowest,
  252. $this->config->get('platform') ?: array()
  253. );
  254. if ($updatedLock) {
  255. $this->io->writeError('<info>Writing lock file</info>');
  256. }
  257. }
  258. if ($this->dumpAutoloader) {
  259. // write autoloader
  260. if ($this->optimizeAutoloader) {
  261. $this->io->writeError('<info>Generating optimized autoload files</info>');
  262. } else {
  263. $this->io->writeError('<info>Generating autoload files</info>');
  264. }
  265. $this->autoloadGenerator->setDevMode($this->devMode);
  266. $this->autoloadGenerator->setClassMapAuthoritative($this->classMapAuthoritative);
  267. $this->autoloadGenerator->setApcu($this->apcuAutoloader);
  268. $this->autoloadGenerator->setRunScripts($this->runScripts);
  269. $this->autoloadGenerator->dump($this->config, $localRepo, $this->package, $this->installationManager, 'composer', $this->optimizeAutoloader);
  270. }
  271. if ($this->executeOperations) {
  272. // force binaries re-generation in case they are missing
  273. foreach ($localRepo->getPackages() as $package) {
  274. $this->installationManager->ensureBinariesPresence($package);
  275. }
  276. }
  277. $fundingCount = 0;
  278. foreach ($localRepo->getPackages() as $package) {
  279. if ($package instanceof CompletePackageInterface && !$package instanceof AliasPackage && $package->getFunding()) {
  280. $fundingCount++;
  281. }
  282. }
  283. if ($fundingCount) {
  284. $this->io->writeError(array(
  285. sprintf(
  286. "<info>%d package%s you are using %s looking for funding.</info>",
  287. $fundingCount,
  288. 1 === $fundingCount ? '' : 's',
  289. 1 === $fundingCount ? 'is' : 'are'
  290. ),
  291. '<info>Use the `composer fund` command to find out more!</info>',
  292. ));
  293. }
  294. if ($this->runScripts) {
  295. // dispatch post event
  296. $eventName = $this->update ? ScriptEvents::POST_UPDATE_CMD : ScriptEvents::POST_INSTALL_CMD;
  297. $this->eventDispatcher->dispatchScript($eventName, $this->devMode);
  298. }
  299. // re-enable GC except on HHVM which triggers a warning here
  300. if (!defined('HHVM_VERSION')) {
  301. gc_enable();
  302. }
  303. return 0;
  304. }
  305. /**
  306. * @param RepositoryInterface $localRepo
  307. * @param RepositoryInterface $installedRepo
  308. * @param PlatformRepository $platformRepo
  309. * @param array $aliases
  310. * @return array [int, PackageInterfaces[]|null] with the exit code and an array of dev packages on update, or null on install
  311. */
  312. protected function doInstall($localRepo, $installedRepo, $platformRepo, $aliases)
  313. {
  314. // init vars
  315. $lockedRepository = null;
  316. $repositories = null;
  317. // initialize locked repo if we are installing from lock or in a partial update
  318. // and a lock file is present as we need to force install non-whitelisted lock file
  319. // packages in that case
  320. if (!$this->update || (!empty($this->updateWhitelist) && $this->locker->isLocked())) {
  321. try {
  322. $lockedRepository = $this->locker->getLockedRepository($this->devMode);
  323. } catch (\RuntimeException $e) {
  324. // if there are dev requires, then we really can not install
  325. if ($this->package->getDevRequires()) {
  326. throw $e;
  327. }
  328. // no require-dev in composer.json and the lock file was created with no dev info, so skip them
  329. $lockedRepository = $this->locker->getLockedRepository();
  330. }
  331. }
  332. $this->whitelistUpdateDependencies(
  333. $lockedRepository ?: $localRepo,
  334. $this->package->getRequires(),
  335. $this->package->getDevRequires()
  336. );
  337. $this->io->writeError('<info>Loading composer repositories with package information</info>');
  338. // creating repository pool
  339. $policy = $this->createPolicy();
  340. $pool = $this->createPool($this->update ? null : $lockedRepository);
  341. $pool->addRepository($installedRepo, $aliases);
  342. if ($this->update) {
  343. $repositories = $this->repositoryManager->getRepositories();
  344. foreach ($repositories as $repository) {
  345. $pool->addRepository($repository, $aliases);
  346. }
  347. }
  348. // Add the locked repository after the others in case we are doing a
  349. // partial update so missing packages can be found there still.
  350. // For installs from lock it's the only one added so it is first
  351. if ($lockedRepository) {
  352. $pool->addRepository($lockedRepository, $aliases);
  353. }
  354. // creating requirements request
  355. $request = $this->createRequest($this->package, $platformRepo);
  356. if ($this->update) {
  357. // remove unstable packages from the localRepo if they don't match the current stability settings
  358. $removedUnstablePackages = array();
  359. foreach ($localRepo->getPackages() as $package) {
  360. if (
  361. !$pool->isPackageAcceptable($package->getNames(), $package->getStability())
  362. && $this->installationManager->isPackageInstalled($localRepo, $package)
  363. ) {
  364. $removedUnstablePackages[$package->getName()] = true;
  365. $request->remove($package->getName(), new Constraint('=', $package->getVersion()));
  366. }
  367. }
  368. $this->io->writeError('<info>Updating dependencies'.($this->devMode ? ' (including require-dev)' : '').'</info>');
  369. $request->updateAll();
  370. $links = array_merge($this->package->getRequires(), $this->package->getDevRequires());
  371. foreach ($links as $link) {
  372. $request->install($link->getTarget(), $link->getConstraint());
  373. }
  374. // if the updateWhitelist is enabled, packages not in it are also fixed
  375. // to the version specified in the lock, or their currently installed version
  376. if ($this->updateWhitelist) {
  377. $currentPackages = $this->getCurrentPackages($installedRepo);
  378. // collect packages to fixate from root requirements as well as installed packages
  379. $candidates = array();
  380. foreach ($links as $link) {
  381. $candidates[$link->getTarget()] = true;
  382. $rootRequires[$link->getTarget()] = $link;
  383. }
  384. foreach ($currentPackages as $package) {
  385. $candidates[$package->getName()] = true;
  386. }
  387. // fix them to the version in lock (or currently installed) if they are not updateable
  388. foreach ($candidates as $candidate => $dummy) {
  389. foreach ($currentPackages as $curPackage) {
  390. if ($curPackage->getName() === $candidate) {
  391. if (!$this->isUpdateable($curPackage) && !isset($removedUnstablePackages[$curPackage->getName()])) {
  392. $constraint = new Constraint('=', $curPackage->getVersion());
  393. $description = $this->locker->isLocked() ? '(locked at' : '(installed at';
  394. $requiredAt = isset($rootRequires[$candidate]) ? ', required as ' . $rootRequires[$candidate]->getPrettyConstraint() : '';
  395. $constraint->setPrettyString($description . ' ' . $curPackage->getPrettyVersion() . $requiredAt . ')');
  396. $request->install($curPackage->getName(), $constraint);
  397. }
  398. break;
  399. }
  400. }
  401. }
  402. }
  403. } else {
  404. $this->io->writeError('<info>Installing dependencies'.($this->devMode ? ' (including require-dev)' : '').' from lock file</info>');
  405. if (!$this->locker->isFresh()) {
  406. $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);
  407. }
  408. foreach ($lockedRepository->getPackages() as $package) {
  409. $version = $package->getVersion();
  410. if (isset($aliases[$package->getName()][$version])) {
  411. $version = $aliases[$package->getName()][$version]['alias_normalized'];
  412. }
  413. $constraint = new Constraint('=', $version);
  414. $constraint->setPrettyString($package->getPrettyVersion());
  415. $request->install($package->getName(), $constraint);
  416. }
  417. foreach ($this->locker->getPlatformRequirements($this->devMode) as $link) {
  418. $request->install($link->getTarget(), $link->getConstraint());
  419. }
  420. }
  421. // force dev packages to have the latest links if we update or install from a (potentially new) lock
  422. $this->processDevPackages($localRepo, $pool, $policy, $repositories, $installedRepo, $lockedRepository, 'force-links');
  423. // solve dependencies
  424. $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::PRE_DEPENDENCIES_SOLVING, $this->devMode, $policy, $pool, $installedRepo, $request);
  425. $solver = new Solver($policy, $pool, $installedRepo, $this->io);
  426. try {
  427. $operations = $solver->solve($request, $this->ignorePlatformReqs);
  428. $ruleSetSize = $solver->getRuleSetSize();
  429. $solver = null;
  430. } catch (SolverProblemsException $e) {
  431. $this->io->writeError('<error>Your requirements could not be resolved to an installable set of packages.</error>', true, IOInterface::QUIET);
  432. $this->io->writeError($e->getMessage());
  433. if ($this->update && !$this->devMode) {
  434. $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);
  435. }
  436. return array(max(1, $e->getCode()), array());
  437. }
  438. // force dev packages to be updated if we update or install from a (potentially new) lock
  439. $operations = $this->processDevPackages($localRepo, $pool, $policy, $repositories, $installedRepo, $lockedRepository, 'force-updates', $operations);
  440. $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::POST_DEPENDENCIES_SOLVING, $this->devMode, $policy, $pool, $installedRepo, $request, $operations);
  441. $this->io->writeError("Analyzed ".count($pool)." packages to resolve dependencies", true, IOInterface::VERBOSE);
  442. $this->io->writeError("Analyzed ".$ruleSetSize." rules to resolve dependencies", true, IOInterface::VERBOSE);
  443. // execute operations
  444. if (!$operations) {
  445. $this->io->writeError('Nothing to install or update');
  446. }
  447. $operations = $this->movePluginsToFront($operations);
  448. $operations = $this->moveUninstallsToFront($operations);
  449. // extract dev packages and mark them to be skipped if it's a --no-dev install or update
  450. // we also force them to be uninstalled if they are present in the local repo
  451. if ($this->update) {
  452. $devPackages = $this->extractDevPackages($operations, $localRepo, $platformRepo, $aliases);
  453. if (!$this->devMode) {
  454. $operations = $this->filterDevPackageOperations($devPackages, $operations, $localRepo);
  455. }
  456. } else {
  457. $devPackages = null;
  458. }
  459. if ($operations) {
  460. $installs = $updates = $uninstalls = array();
  461. foreach ($operations as $operation) {
  462. if ($operation instanceof InstallOperation) {
  463. $installs[] = $operation->getPackage()->getPrettyName().':'.$operation->getPackage()->getFullPrettyVersion();
  464. } elseif ($operation instanceof UpdateOperation) {
  465. $updates[] = $operation->getTargetPackage()->getPrettyName().':'.$operation->getTargetPackage()->getFullPrettyVersion();
  466. } elseif ($operation instanceof UninstallOperation) {
  467. $uninstalls[] = $operation->getPackage()->getPrettyName();
  468. }
  469. }
  470. $this->io->writeError(sprintf(
  471. "<info>Package operations: %d install%s, %d update%s, %d removal%s</info>",
  472. count($installs),
  473. 1 === count($installs) ? '' : 's',
  474. count($updates),
  475. 1 === count($updates) ? '' : 's',
  476. count($uninstalls),
  477. 1 === count($uninstalls) ? '' : 's'
  478. ));
  479. if ($installs) {
  480. $this->io->writeError("Installs: ".implode(', ', $installs), true, IOInterface::VERBOSE);
  481. }
  482. if ($updates) {
  483. $this->io->writeError("Updates: ".implode(', ', $updates), true, IOInterface::VERBOSE);
  484. }
  485. if ($uninstalls) {
  486. $this->io->writeError("Removals: ".implode(', ', $uninstalls), true, IOInterface::VERBOSE);
  487. }
  488. }
  489. foreach ($operations as $operation) {
  490. // collect suggestions
  491. $jobType = $operation->getJobType();
  492. if ('install' === $jobType) {
  493. $this->suggestedPackagesReporter->addSuggestionsFromPackage($operation->getPackage());
  494. }
  495. // updating, force dev packages' references if they're in root package refs
  496. if ($this->update) {
  497. $package = null;
  498. if ('update' === $jobType) {
  499. $package = $operation->getTargetPackage();
  500. } elseif ('install' === $jobType) {
  501. $package = $operation->getPackage();
  502. }
  503. if ($package && $package->isDev()) {
  504. $references = $this->package->getReferences();
  505. if (isset($references[$package->getName()])) {
  506. $this->updateInstallReferences($package, $references[$package->getName()]);
  507. }
  508. }
  509. if ('update' === $jobType) {
  510. $targetPackage = $operation->getTargetPackage();
  511. if ($targetPackage->isDev()) {
  512. $initialPackage = $operation->getInitialPackage();
  513. if ($targetPackage->getVersion() === $initialPackage->getVersion()
  514. && (!$targetPackage->getSourceReference() || $targetPackage->getSourceReference() === $initialPackage->getSourceReference())
  515. && (!$targetPackage->getDistReference() || $targetPackage->getDistReference() === $initialPackage->getDistReference())
  516. ) {
  517. $this->io->writeError(' - Skipping update of ' . $targetPackage->getPrettyName() . ' to the same reference-locked version', true, IOInterface::DEBUG);
  518. $this->io->writeError('', true, IOInterface::DEBUG);
  519. continue;
  520. }
  521. }
  522. }
  523. }
  524. $event = 'Composer\Installer\PackageEvents::PRE_PACKAGE_'.strtoupper($jobType);
  525. if (defined($event) && $this->runScripts) {
  526. $this->eventDispatcher->dispatchPackageEvent(constant($event), $this->devMode, $policy, $pool, $installedRepo, $request, $operations, $operation);
  527. }
  528. // output non-alias ops when not executing operations (i.e. dry run), output alias ops in debug verbosity
  529. if (!$this->executeOperations && false === strpos($operation->getJobType(), 'Alias')) {
  530. $this->io->writeError(' - ' . $operation);
  531. } elseif ($this->io->isDebug() && false !== strpos($operation->getJobType(), 'Alias')) {
  532. $this->io->writeError(' - ' . $operation);
  533. }
  534. $this->installationManager->execute($localRepo, $operation);
  535. // output reasons why the operation was ran, only for install/update operations
  536. if ($this->verbose && $this->io->isVeryVerbose() && in_array($jobType, array('install', 'update'))) {
  537. $reason = $operation->getReason();
  538. if ($reason instanceof Rule) {
  539. switch ($reason->getReason()) {
  540. case Rule::RULE_JOB_INSTALL:
  541. $this->io->writeError(' REASON: Required by the root package: '.$reason->getPrettyString($pool));
  542. $this->io->writeError('');
  543. break;
  544. case Rule::RULE_PACKAGE_REQUIRES:
  545. $this->io->writeError(' REASON: '.$reason->getPrettyString($pool));
  546. $this->io->writeError('');
  547. break;
  548. }
  549. }
  550. }
  551. if ($this->executeOperations || $this->writeLock) {
  552. $localRepo->write();
  553. }
  554. $event = 'Composer\Installer\PackageEvents::POST_PACKAGE_'.strtoupper($jobType);
  555. if (defined($event) && $this->runScripts) {
  556. $this->eventDispatcher->dispatchPackageEvent(constant($event), $this->devMode, $policy, $pool, $installedRepo, $request, $operations, $operation);
  557. }
  558. }
  559. if ($this->executeOperations) {
  560. // force source/dist urls to be updated for all packages
  561. $this->processPackageUrls($pool, $policy, $localRepo, $repositories);
  562. $localRepo->write();
  563. }
  564. // see https://github.com/composer/composer/issues/2764
  565. if ($operations) {
  566. $vendorDir = $this->config->get('vendor-dir');
  567. if (is_dir($vendorDir)) {
  568. // suppress errors as this fails sometimes on OSX for no apparent reason
  569. // see https://github.com/composer/composer/issues/4070#issuecomment-129792748
  570. @touch($vendorDir);
  571. }
  572. }
  573. return array(0, $devPackages);
  574. }
  575. /**
  576. * Extracts the dev packages out of the localRepo
  577. *
  578. * This works by faking the operations so we can see what the dev packages
  579. * would be at the end of the operation execution. This lets us then remove
  580. * the dev packages from the list of operations accordingly if we are in a
  581. * --no-dev install or update.
  582. *
  583. * @return array
  584. */
  585. private function extractDevPackages(array $operations, RepositoryInterface $localRepo, PlatformRepository $platformRepo, array $aliases)
  586. {
  587. if (!$this->package->getDevRequires()) {
  588. return array();
  589. }
  590. // fake-apply all operations to this clone of the local repo so we see the complete set of package we would end up with
  591. $tempLocalRepo = clone $localRepo;
  592. foreach ($operations as $operation) {
  593. switch ($operation->getJobType()) {
  594. case 'install':
  595. case 'markAliasInstalled':
  596. if (!$tempLocalRepo->hasPackage($operation->getPackage())) {
  597. $tempLocalRepo->addPackage(clone $operation->getPackage());
  598. }
  599. break;
  600. case 'uninstall':
  601. case 'markAliasUninstalled':
  602. $tempLocalRepo->removePackage($operation->getPackage());
  603. break;
  604. case 'update':
  605. $tempLocalRepo->removePackage($operation->getInitialPackage());
  606. if (!$tempLocalRepo->hasPackage($operation->getTargetPackage())) {
  607. $tempLocalRepo->addPackage(clone $operation->getTargetPackage());
  608. }
  609. break;
  610. default:
  611. throw new \LogicException('Unknown type: '.$operation->getJobType());
  612. }
  613. }
  614. // we have to reload the local repo to handle aliases properly
  615. // but as it is not persisted on disk we use a loader/dumper
  616. // to reload it in memory
  617. $localRepo = new InstalledArrayRepository(array());
  618. $loader = new ArrayLoader(null, true);
  619. $dumper = new ArrayDumper();
  620. foreach ($tempLocalRepo->getCanonicalPackages() as $pkg) {
  621. $localRepo->addPackage($loader->load($dumper->dump($pkg)));
  622. }
  623. unset($tempLocalRepo, $loader, $dumper);
  624. $policy = $this->createPolicy();
  625. $pool = $this->createPool();
  626. $installedRepo = $this->createInstalledRepo($localRepo, $platformRepo);
  627. $pool->addRepository($installedRepo, $aliases);
  628. // creating requirements request without dev requirements
  629. $request = $this->createRequest($this->package, $platformRepo);
  630. $request->updateAll();
  631. foreach ($this->package->getRequires() as $link) {
  632. $request->install($link->getTarget(), $link->getConstraint());
  633. }
  634. // solve deps to see which get removed
  635. $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::PRE_DEPENDENCIES_SOLVING, false, $policy, $pool, $installedRepo, $request);
  636. $solver = new Solver($policy, $pool, $installedRepo, $this->io);
  637. $ops = $solver->solve($request, $this->ignorePlatformReqs);
  638. $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::POST_DEPENDENCIES_SOLVING, false, $policy, $pool, $installedRepo, $request, $ops);
  639. $devPackages = array();
  640. foreach ($ops as $op) {
  641. if ($op->getJobType() === 'uninstall') {
  642. $devPackages[] = $op->getPackage();
  643. }
  644. }
  645. return $devPackages;
  646. }
  647. /**
  648. * @return OperationInterface[] filtered operations, dev packages are uninstalled and all operations on them ignored
  649. */
  650. private function filterDevPackageOperations(array $devPackages, array $operations, RepositoryInterface $localRepo)
  651. {
  652. $finalOps = array();
  653. $packagesToSkip = array();
  654. foreach ($devPackages as $pkg) {
  655. $packagesToSkip[$pkg->getName()] = true;
  656. if ($installedDevPkg = $localRepo->findPackage($pkg->getName(), '*')) {
  657. if ($installedDevPkg instanceof AliasPackage) {
  658. $finalOps[] = new MarkAliasUninstalledOperation($installedDevPkg, 'non-dev install removing it');
  659. $installedDevPkg = $installedDevPkg->getAliasOf();
  660. }
  661. $finalOps[] = new UninstallOperation($installedDevPkg, 'non-dev install removing it');
  662. }
  663. }
  664. // skip operations applied on dev packages
  665. foreach ($operations as $op) {
  666. $package = $op->getJobType() === 'update' ? $op->getTargetPackage() : $op->getPackage();
  667. if (isset($packagesToSkip[$package->getName()])) {
  668. continue;
  669. }
  670. $finalOps[] = $op;
  671. }
  672. return $finalOps;
  673. }
  674. /**
  675. * Workaround: if your packages depend on plugins, we must be sure
  676. * that those are installed / updated first; else it would lead to packages
  677. * being installed multiple times in different folders, when running Composer
  678. * twice.
  679. *
  680. * While this does not fix the root-causes of https://github.com/composer/composer/issues/1147,
  681. * it at least fixes the symptoms and makes usage of composer possible (again)
  682. * in such scenarios.
  683. *
  684. * @param OperationInterface[] $operations
  685. * @return OperationInterface[] reordered operation list
  686. */
  687. private function movePluginsToFront(array $operations)
  688. {
  689. $pluginsNoDeps = array();
  690. $pluginsWithDeps = array();
  691. $pluginRequires = array();
  692. foreach (array_reverse($operations, true) as $idx => $op) {
  693. if ($op instanceof InstallOperation) {
  694. $package = $op->getPackage();
  695. } elseif ($op instanceof UpdateOperation) {
  696. $package = $op->getTargetPackage();
  697. } else {
  698. continue;
  699. }
  700. // is this package a plugin?
  701. $isPlugin = $package->getType() === 'composer-plugin' || $package->getType() === 'composer-installer';
  702. // is this a plugin or a dependency of a plugin?
  703. if ($isPlugin || count(array_intersect($package->getNames(), $pluginRequires))) {
  704. // get the package's requires, but filter out any platform requirements or 'composer-plugin-api'
  705. $requires = array_filter(array_keys($package->getRequires()), function ($req) {
  706. return $req !== 'composer-plugin-api' && !preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $req);
  707. });
  708. // is this a plugin with no meaningful dependencies?
  709. if ($isPlugin && !count($requires)) {
  710. // plugins with no dependencies go to the very front
  711. array_unshift($pluginsNoDeps, $op);
  712. } else {
  713. // capture the requirements for this package so those packages will be moved up as well
  714. $pluginRequires = array_merge($pluginRequires, $requires);
  715. // move the operation to the front
  716. array_unshift($pluginsWithDeps, $op);
  717. }
  718. unset($operations[$idx]);
  719. }
  720. }
  721. return array_merge($pluginsNoDeps, $pluginsWithDeps, $operations);
  722. }
  723. /**
  724. * Removals of packages should be executed before installations in
  725. * case two packages resolve to the same path (due to custom installers)
  726. *
  727. * @param OperationInterface[] $operations
  728. * @return OperationInterface[] reordered operation list
  729. */
  730. private function moveUninstallsToFront(array $operations)
  731. {
  732. $uninstOps = array();
  733. foreach ($operations as $idx => $op) {
  734. if ($op instanceof UninstallOperation) {
  735. $uninstOps[] = $op;
  736. unset($operations[$idx]);
  737. }
  738. }
  739. return array_merge($uninstOps, $operations);
  740. }
  741. /**
  742. * @return RepositoryInterface
  743. */
  744. private function createInstalledRepo(RepositoryInterface $localRepo, PlatformRepository $platformRepo)
  745. {
  746. // clone root package to have one in the installed repo that does not require anything
  747. // we don't want it to be uninstallable, but its requirements should not conflict
  748. // with the lock file for example
  749. $installedRootPackage = clone $this->package;
  750. $installedRootPackage->setRequires(array());
  751. $installedRootPackage->setDevRequires(array());
  752. $repos = array(
  753. $localRepo,
  754. new InstalledArrayRepository(array($installedRootPackage)),
  755. $platformRepo,
  756. );
  757. $installedRepo = new CompositeRepository($repos);
  758. if ($this->additionalInstalledRepository) {
  759. $installedRepo->addRepository($this->additionalInstalledRepository);
  760. }
  761. return $installedRepo;
  762. }
  763. /**
  764. * @param RepositoryInterface|null $lockedRepository
  765. * @return Pool
  766. */
  767. private function createPool(RepositoryInterface $lockedRepository = null)
  768. {
  769. if ($this->update) {
  770. $minimumStability = $this->package->getMinimumStability();
  771. $stabilityFlags = $this->package->getStabilityFlags();
  772. $requires = array_merge($this->package->getRequires(), $this->package->getDevRequires());
  773. } else {
  774. $minimumStability = $this->locker->getMinimumStability();
  775. $stabilityFlags = $this->locker->getStabilityFlags();
  776. $requires = array();
  777. foreach ($lockedRepository->getPackages() as $package) {
  778. $constraint = new Constraint('=', $package->getVersion());
  779. $constraint->setPrettyString($package->getPrettyVersion());
  780. $requires[$package->getName()] = $constraint;
  781. }
  782. }
  783. $rootConstraints = array();
  784. foreach ($requires as $req => $constraint) {
  785. // skip platform requirements from the root package to avoid filtering out existing platform packages
  786. if ($this->ignorePlatformReqs && preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $req)) {
  787. continue;
  788. }
  789. if ($constraint instanceof Link) {
  790. $rootConstraints[$req] = $constraint->getConstraint();
  791. } else {
  792. $rootConstraints[$req] = $constraint;
  793. }
  794. }
  795. return new Pool($minimumStability, $stabilityFlags, $rootConstraints);
  796. }
  797. /**
  798. * @return DefaultPolicy
  799. */
  800. private function createPolicy()
  801. {
  802. $preferStable = null;
  803. $preferLowest = null;
  804. if (!$this->update) {
  805. $preferStable = $this->locker->getPreferStable();
  806. $preferLowest = $this->locker->getPreferLowest();
  807. }
  808. // old lock file without prefer stable/lowest will return null
  809. // so in this case we use the composer.json info
  810. if (null === $preferStable) {
  811. $preferStable = $this->preferStable || $this->package->getPreferStable();
  812. }
  813. if (null === $preferLowest) {
  814. $preferLowest = $this->preferLowest;
  815. }
  816. return new DefaultPolicy($preferStable, $preferLowest);
  817. }
  818. /**
  819. * @param RootPackageInterface $rootPackage
  820. * @param PlatformRepository $platformRepo
  821. * @return Request
  822. */
  823. private function createRequest(RootPackageInterface $rootPackage, PlatformRepository $platformRepo)
  824. {
  825. $request = new Request();
  826. $constraint = new Constraint('=', $rootPackage->getVersion());
  827. $constraint->setPrettyString($rootPackage->getPrettyVersion());
  828. $request->install($rootPackage->getName(), $constraint);
  829. $fixedPackages = $platformRepo->getPackages();
  830. if ($this->additionalInstalledRepository) {
  831. $additionalFixedPackages = $this->additionalInstalledRepository->getPackages();
  832. $fixedPackages = array_merge($fixedPackages, $additionalFixedPackages);
  833. }
  834. // fix the version of all platform packages + additionally installed packages
  835. // to prevent the solver trying to remove or update those
  836. $provided = $rootPackage->getProvides();
  837. foreach ($fixedPackages as $package) {
  838. $constraint = new Constraint('=', $package->getVersion());
  839. $constraint->setPrettyString($package->getPrettyVersion());
  840. // skip platform packages that are provided by the root package
  841. if ($package->getRepository() !== $platformRepo
  842. || !isset($provided[$package->getName()])
  843. || !$provided[$package->getName()]->getConstraint()->matches($constraint)
  844. ) {
  845. $request->fix($package->getName(), $constraint);
  846. }
  847. }
  848. return $request;
  849. }
  850. /**
  851. * @param WritableRepositoryInterface $localRepo
  852. * @param Pool $pool
  853. * @param PolicyInterface $policy
  854. * @param array $repositories
  855. * @param RepositoryInterface $installedRepo
  856. * @param RepositoryInterface $lockedRepository
  857. * @param string $task
  858. * @param array|null $operations
  859. * @return array
  860. */
  861. private function processDevPackages($localRepo, $pool, $policy, $repositories, $installedRepo, $lockedRepository, $task, array $operations = null)
  862. {
  863. if ($task === 'force-updates' && null === $operations) {
  864. throw new \InvalidArgumentException('Missing operations argument');
  865. }
  866. if ($task === 'force-links') {
  867. $operations = array();
  868. }
  869. if ($this->update && $this->updateWhitelist) {
  870. $currentPackages = $this->getCurrentPackages($installedRepo);
  871. }
  872. foreach ($localRepo->getCanonicalPackages() as $package) {
  873. // skip non-dev packages
  874. if (!$package->isDev()) {
  875. continue;
  876. }
  877. // skip packages that will be updated/uninstalled
  878. foreach ($operations as $operation) {
  879. if (('update' === $operation->getJobType() && $operation->getInitialPackage()->equals($package))
  880. || ('uninstall' === $operation->getJobType() && $operation->getPackage()->equals($package))
  881. ) {
  882. continue 2;
  883. }
  884. }
  885. if ($this->update) {
  886. // skip package if the whitelist is enabled and it is not in it
  887. if ($this->updateWhitelist && !$this->isUpdateable($package)) {
  888. // check if non-updateable packages are out of date compared to the lock file to ensure we don't corrupt it
  889. foreach ($currentPackages as $curPackage) {
  890. if ($curPackage->isDev() && $curPackage->getName() === $package->getName() && $curPackage->getVersion() === $package->getVersion()) {
  891. if ($task === 'force-links') {
  892. $package->setRequires($curPackage->getRequires());
  893. $package->setConflicts($curPackage->getConflicts());
  894. $package->setProvides($curPackage->getProvides());
  895. $package->setReplaces($curPackage->getReplaces());
  896. } elseif ($task === 'force-updates') {
  897. if (($curPackage->getSourceReference() && $curPackage->getSourceReference() !== $package->getSourceReference())
  898. || ($curPackage->getDistReference() && $curPackage->getDistReference() !== $package->getDistReference())
  899. ) {
  900. $operations[] = new UpdateOperation($package, $curPackage);
  901. }
  902. }
  903. break;
  904. }
  905. }
  906. continue;
  907. }
  908. // find similar packages (name/version) in all repositories
  909. $matches = $pool->whatProvides($package->getName(), new Constraint('=', $package->getVersion()));
  910. foreach ($matches as $index => $match) {
  911. // skip local packages
  912. if (!in_array($match->getRepository(), $repositories, true)) {
  913. unset($matches[$index]);
  914. continue;
  915. }
  916. // skip providers/replacers
  917. if ($match->getName() !== $package->getName()) {
  918. unset($matches[$index]);
  919. continue;
  920. }
  921. $matches[$index] = $match->getId();
  922. }
  923. // select preferred package according to policy rules
  924. if ($matches && $matches = $policy->selectPreferredPackages($pool, array(), $matches)) {
  925. $newPackage = $pool->literalToPackage($matches[0]);
  926. if ($task === 'force-links' && $newPackage) {
  927. $package->setRequires($newPackage->getRequires());
  928. $package->setConflicts($newPackage->getConflicts());
  929. $package->setProvides($newPackage->getProvides());
  930. $package->setReplaces($newPackage->getReplaces());
  931. }
  932. if (
  933. $task === 'force-updates'
  934. && $newPackage
  935. && (
  936. ($newPackage->getSourceReference() && $newPackage->getSourceReference() !== $package->getSourceReference())
  937. || ($newPackage->getDistReference() && $newPackage->getDistReference() !== $package->getDistReference())
  938. )
  939. ) {
  940. $operations[] = new UpdateOperation($package, $newPackage);
  941. continue;
  942. }
  943. }
  944. if ($task === 'force-updates') {
  945. // force installed package to update to referenced version in root package if it does not match the installed version
  946. $references = $this->package->getReferences();
  947. if (isset($references[$package->getName()]) && $references[$package->getName()] !== $package->getSourceReference()) {
  948. // changing the source ref to update to will be handled in the operations loop
  949. $operations[] = new UpdateOperation($package, clone $package);
  950. }
  951. }
  952. } else {
  953. // force update to locked version if it does not match the installed version
  954. foreach ($lockedRepository->findPackages($package->getName()) as $lockedPackage) {
  955. if ($lockedPackage->isDev() && $lockedPackage->getVersion() === $package->getVersion()) {
  956. if ($task === 'force-links') {
  957. $package->setRequires($lockedPackage->getRequires());
  958. $package->setConflicts($lockedPackage->getConflicts());
  959. $package->setProvides($lockedPackage->getProvides());
  960. $package->setReplaces($lockedPackage->getReplaces());
  961. } elseif ($task === 'force-updates') {
  962. if (($lockedPackage->getSourceReference() && $lockedPackage->getSourceReference() !== $package->getSourceReference())
  963. || ($lockedPackage->getDistReference() && $lockedPackage->getDistReference() !== $package->getDistReference())
  964. ) {
  965. $operations[] = new UpdateOperation($package, $lockedPackage);
  966. }
  967. }
  968. break;
  969. }
  970. }
  971. }
  972. }
  973. return $operations;
  974. }
  975. /**
  976. * Loads the most "current" list of packages that are installed meaning from lock ideally or from installed repo as fallback
  977. * @param RepositoryInterface $installedRepo
  978. * @return array
  979. */
  980. private function getCurrentPackages($installedRepo)
  981. {
  982. if ($this->locker->isLocked()) {
  983. try {
  984. return $this->locker->getLockedRepository(true)->getPackages();
  985. } catch (\RuntimeException $e) {
  986. // fetch only non-dev packages from lock if doing a dev update fails due to a previously incomplete lock file
  987. return $this->locker->getLockedRepository()->getPackages();
  988. }
  989. }
  990. return $installedRepo->getPackages();
  991. }
  992. /**
  993. * @return array
  994. */
  995. private function getRootAliases()
  996. {
  997. if ($this->update) {
  998. $aliases = $this->package->getAliases();
  999. } else {
  1000. $aliases = $this->locker->getAliases();
  1001. }
  1002. $normalizedAliases = array();
  1003. foreach ($aliases as $alias) {
  1004. $normalizedAliases[$alias['package']][$alias['version']] = array(
  1005. 'alias' => $alias['alias'],
  1006. 'alias_normalized' => $alias['alias_normalized'],
  1007. );
  1008. }
  1009. return $normalizedAliases;
  1010. }
  1011. /**
  1012. * @param Pool $pool
  1013. * @param PolicyInterface $policy
  1014. * @param WritableRepositoryInterface $localRepo
  1015. * @param array $repositories
  1016. */
  1017. private function processPackageUrls($pool, $policy, $localRepo, $repositories)
  1018. {
  1019. if (!$this->update) {
  1020. return;
  1021. }
  1022. $rootRefs = $this->package->getReferences();
  1023. foreach ($localRepo->getCanonicalPackages() as $package) {
  1024. // find similar packages (name/version) in all repositories
  1025. $matches = $pool->whatProvides($package->getName(), new Constraint('=', $package->getVersion()));
  1026. foreach ($matches as $index => $match) {
  1027. // skip local packages
  1028. if (!in_array($match->getRepository(), $repositories, true)) {
  1029. unset($matches[$index]);
  1030. continue;
  1031. }
  1032. // skip providers/replacers
  1033. if ($match->getName() !== $package->getName()) {
  1034. unset($matches[$index]);
  1035. continue;
  1036. }
  1037. $matches[$index] = $match->getId();
  1038. }
  1039. // select preferred package according to policy rules
  1040. if ($matches && $matches = $policy->selectPreferredPackages($pool, array(), $matches)) {
  1041. $newPackage = $pool->literalToPackage($matches[0]);
  1042. // update the dist and source URLs
  1043. $sourceUrl = $package->getSourceUrl();
  1044. $newSourceUrl = $newPackage->getSourceUrl();
  1045. $newReference = $newPackage->getSourceReference();
  1046. if ($package->isDev() && isset($rootRefs[$package->getName()]) && $package->getSourceReference() === $rootRefs[$package->getName()]) {
  1047. $newReference = $rootRefs[$package->getName()];
  1048. }
  1049. $this->updatePackageUrl($package, $newSourceUrl, $newPackage->getSourceType(), $newReference, $newPackage->getDistUrl(), $newPackage->getDistType(), $newPackage->getDistSha1Checksum());
  1050. if ($package instanceof CompletePackage && $newPackage instanceof CompletePackage) {
  1051. $package->setAbandoned($newPackage->getReplacementPackage() ?: $newPackage->isAbandoned());
  1052. }
  1053. $package->setDistMirrors($newPackage->getDistMirrors());
  1054. $package->setSourceMirrors($newPackage->getSourceMirrors());
  1055. $package->setTransportOptions($newPackage->getTransportOptions());
  1056. }
  1057. }
  1058. }
  1059. private function updatePackageUrl(PackageInterface $package, $sourceUrl, $sourceType, $sourceReference, $distUrl, $distType, $distShaSum)
  1060. {
  1061. $oldSourceRef = $package->getSourceReference();
  1062. if ($package->getSourceUrl() !== $sourceUrl) {
  1063. $package->setSourceType($sourceType);
  1064. $package->setSourceUrl($sourceUrl);
  1065. $package->setSourceReference($sourceReference);
  1066. }
  1067. // only update dist url for github/bitbucket/gitlab dists as they use a combination of dist url + dist reference to install
  1068. // but for other urls this is ambiguous and could result in bad outcomes
  1069. if (preg_match('{^https?://(?:(?:www\.)?bitbucket\.org|(api\.)?github\.com|(?:www\.)?gitlab\.com)/}i', $distUrl)) {
  1070. $package->setDistUrl($distUrl);
  1071. $package->setDistType($distType);
  1072. $package->setDistSha1Checksum($distShaSum);
  1073. $this->updateInstallReferences($package, $sourceReference);
  1074. }
  1075. if ($this->updateWhitelist && !$this->isUpdateable($package)) {
  1076. $this->updateInstallReferences($package, $oldSourceRef);
  1077. }
  1078. }
  1079. private function updateInstallReferences(PackageInterface $package, $reference)
  1080. {
  1081. if (!$reference) {
  1082. return;
  1083. }
  1084. $package->setSourceReference($reference);
  1085. if (preg_match('{^https?://(?:(?:www\.)?bitbucket\.org|(api\.)?github\.com|(?:www\.)?gitlab\.com)/}i', $package->getDistUrl())) {
  1086. $package->setDistReference($reference);
  1087. $package->setDistUrl(preg_replace('{(?<=/|sha=)[a-f0-9]{40}(?=/|$)}i', $reference, $package->getDistUrl()));
  1088. } elseif ($package->getDistReference()) { // update the dist reference if there was one, but if none was provided ignore it
  1089. $package->setDistReference($reference);
  1090. }
  1091. }
  1092. /**
  1093. * @param PlatformRepository $platformRepo
  1094. * @param array $aliases
  1095. */
  1096. private function aliasPlatformPackages(PlatformRepository $platformRepo, $aliases)
  1097. {
  1098. foreach ($aliases as $package => $versions) {
  1099. foreach ($versions as $version => $alias) {
  1100. $packages = $platformRepo->findPackages($package, $version);
  1101. foreach ($packages as $package) {
  1102. $aliasPackage = new AliasPackage($package, $alias['alias_normalized'], $alias['alias']);
  1103. $aliasPackage->setRootPackageAlias(true);
  1104. $platformRepo->addPackage($aliasPackage);
  1105. }
  1106. }
  1107. }
  1108. }
  1109. /**
  1110. * @param PackageInterface $package
  1111. * @return bool
  1112. */
  1113. private function isUpdateable(PackageInterface $package)
  1114. {
  1115. if (!$this->updateWhitelist) {
  1116. throw new \LogicException('isUpdateable should only be called when a whitelist is present');
  1117. }
  1118. foreach ($this->updateWhitelist as $whiteListedPattern => $void) {
  1119. $patternRegexp = BasePackage::packageNameToRegexp($whiteListedPattern);
  1120. if (preg_match($patternRegexp, $package->getName())) {
  1121. return true;
  1122. }
  1123. }
  1124. return false;
  1125. }
  1126. /**
  1127. * @param array $links
  1128. * @return array
  1129. */
  1130. private function extractPlatformRequirements($links)
  1131. {
  1132. $platformReqs = array();
  1133. foreach ($links as $link) {
  1134. if (preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $link->getTarget())) {
  1135. $platformReqs[$link->getTarget()] = $link->getPrettyConstraint();
  1136. }
  1137. }
  1138. return $platformReqs;
  1139. }
  1140. /**
  1141. * Adds all dependencies of the update whitelist to the whitelist, too.
  1142. *
  1143. * Packages which are listed as requirements in the root package will be
  1144. * skipped including their dependencies, unless they are listed in the
  1145. * update whitelist themselves or $whitelistAllDependencies is true.
  1146. *
  1147. * @param RepositoryInterface $localOrLockRepo Use the locked repo if available, otherwise installed repo will do
  1148. * As we want the most accurate package list to work with, and installed
  1149. * repo might be empty but locked repo will always be current.
  1150. * @param array $rootRequires An array of links to packages in require of the root package
  1151. * @param array $rootDevRequires An array of links to packages in require-dev of the root package
  1152. */
  1153. private function whitelistUpdateDependencies($localOrLockRepo, array $rootRequires, array $rootDevRequires)
  1154. {
  1155. if (!$this->updateWhitelist) {
  1156. return;
  1157. }
  1158. $rootRequires = array_merge($rootRequires, $rootDevRequires);
  1159. $skipPackages = array();
  1160. if (!$this->whitelistAllDependencies) {
  1161. foreach ($rootRequires as $require) {
  1162. $skipPackages[$require->getTarget()] = true;
  1163. }
  1164. }
  1165. $pool = new Pool('dev');
  1166. $pool->addRepository($localOrLockRepo);
  1167. $seen = array();
  1168. $rootRequiredPackageNames = array_keys($rootRequires);
  1169. foreach ($this->updateWhitelist as $packageName => $void) {
  1170. $packageQueue = new \SplQueue;
  1171. $nameMatchesRequiredPackage = false;
  1172. $depPackages = $pool->whatProvides($packageName);
  1173. $matchesByPattern = array();
  1174. // check if the name is a glob pattern that did not match directly
  1175. if (empty($depPackages)) {
  1176. // add any installed package matching the whitelisted name/pattern
  1177. $whitelistPatternSearchRegexp = BasePackage::packageNameToRegexp($packageName, '^%s$');
  1178. foreach ($localOrLockRepo->search($whitelistPatternSearchRegexp) as $installedPackage) {
  1179. $matchesByPattern[] = $pool->whatProvides($installedPackage['name']);
  1180. }
  1181. // add root requirements which match the whitelisted name/pattern
  1182. $whitelistPatternRegexp = BasePackage::packageNameToRegexp($packageName);
  1183. foreach ($rootRequiredPackageNames as $rootRequiredPackageName) {
  1184. if (preg_match($whitelistPatternRegexp, $rootRequiredPackageName)) {
  1185. $nameMatchesRequiredPackage = true;
  1186. break;
  1187. }
  1188. }
  1189. }
  1190. if (!empty($matchesByPattern)) {
  1191. $depPackages = array_merge($depPackages, call_user_func_array('array_merge', $matchesByPattern));
  1192. }
  1193. if (count($depPackages) == 0 && !$nameMatchesRequiredPackage && !in_array($packageName, array('nothing', 'lock', 'mirrors'))) {
  1194. $this->io->writeError('<warning>Package "' . $packageName . '" listed for update is not installed. Ignoring.</warning>');
  1195. }
  1196. foreach ($depPackages as $depPackage) {
  1197. $packageQueue->enqueue($depPackage);
  1198. }
  1199. while (!$packageQueue->isEmpty()) {
  1200. $package = $packageQueue->dequeue();
  1201. if (isset($seen[$package->getId()])) {
  1202. continue;
  1203. }
  1204. $seen[$package->getId()] = true;
  1205. $this->updateWhitelist[$package->getName()] = true;
  1206. if (!$this->whitelistDependencies && !$this->whitelistAllDependencies) {
  1207. continue;
  1208. }
  1209. $requires = $package->getRequires();
  1210. foreach ($requires as $require) {
  1211. $requirePackages = $pool->whatProvides($require->getTarget());
  1212. foreach ($requirePackages as $requirePackage) {
  1213. if (isset($this->updateWhitelist[$requirePackage->getName()])) {
  1214. continue;
  1215. }
  1216. if (isset($skipPackages[$requirePackage->getName()]) && !preg_match(BasePackage::packageNameToRegexp($packageName), $requirePackage->getName())) {
  1217. $this->io->writeError('<warning>Dependency "' . $requirePackage->getName() . '" is also a root requirement, but is not explicitly whitelisted. Ignoring.</warning>');
  1218. continue;
  1219. }
  1220. $packageQueue->enqueue($requirePackage);
  1221. }
  1222. }
  1223. }
  1224. }
  1225. }
  1226. /**
  1227. * Replace local repositories with InstalledArrayRepository instances
  1228. *
  1229. * This is to prevent any accidental modification of the existing repos on disk
  1230. *
  1231. * @param RepositoryManager $rm
  1232. */
  1233. private function mockLocalRepositories(RepositoryManager $rm)
  1234. {
  1235. $packages = array();
  1236. foreach ($rm->getLocalRepository()->getPackages() as $package) {
  1237. $packages[(string) $package] = clone $package;
  1238. }
  1239. foreach ($packages as $key => $package) {
  1240. if ($package instanceof AliasPackage) {
  1241. $alias = (string) $package->getAliasOf();
  1242. $packages[$key] = new AliasPackage($packages[$alias], $package->getVersion(), $package->getPrettyVersion());
  1243. }
  1244. }
  1245. $rm->setLocalRepository(
  1246. new InstalledArrayRepository($packages)
  1247. );
  1248. }
  1249. /**
  1250. * Create Installer
  1251. *
  1252. * @param IOInterface $io
  1253. * @param Composer $composer
  1254. * @return Installer
  1255. */
  1256. public static function create(IOInterface $io, Composer $composer)
  1257. {
  1258. return new static(
  1259. $io,
  1260. $composer->getConfig(),
  1261. $composer->getPackage(),
  1262. $composer->getDownloadManager(),
  1263. $composer->getRepositoryManager(),
  1264. $composer->getLocker(),
  1265. $composer->getInstallationManager(),
  1266. $composer->getEventDispatcher(),
  1267. $composer->getAutoloadGenerator()
  1268. );
  1269. }
  1270. /**
  1271. * @param RepositoryInterface $additionalInstalledRepository
  1272. * @return $this
  1273. */
  1274. public function setAdditionalInstalledRepository(RepositoryInterface $additionalInstalledRepository)
  1275. {
  1276. $this->additionalInstalledRepository = $additionalInstalledRepository;
  1277. return $this;
  1278. }
  1279. /**
  1280. * Whether to run in drymode or not
  1281. *
  1282. * @param bool $dryRun
  1283. * @return Installer
  1284. */
  1285. public function setDryRun($dryRun = true)
  1286. {
  1287. $this->dryRun = (bool) $dryRun;
  1288. return $this;
  1289. }
  1290. /**
  1291. * Checks, if this is a dry run (simulation mode).
  1292. *
  1293. * @return bool
  1294. */
  1295. public function isDryRun()
  1296. {
  1297. return $this->dryRun;
  1298. }
  1299. /**
  1300. * prefer source installation
  1301. *
  1302. * @param bool $preferSource
  1303. * @return Installer
  1304. */
  1305. public function setPreferSource($preferSource = true)
  1306. {
  1307. $this->preferSource = (bool) $preferSource;
  1308. return $this;
  1309. }
  1310. /**
  1311. * prefer dist installation
  1312. *
  1313. * @param bool $preferDist
  1314. * @return Installer
  1315. */
  1316. public function setPreferDist($preferDist = true)
  1317. {
  1318. $this->preferDist = (bool) $preferDist;
  1319. return $this;
  1320. }
  1321. /**
  1322. * Whether or not generated autoloader are optimized
  1323. *
  1324. * @param bool $optimizeAutoloader
  1325. * @return Installer
  1326. */
  1327. public function setOptimizeAutoloader($optimizeAutoloader = false)
  1328. {
  1329. $this->optimizeAutoloader = (bool) $optimizeAutoloader;
  1330. if (!$this->optimizeAutoloader) {
  1331. // Force classMapAuthoritative off when not optimizing the
  1332. // autoloader
  1333. $this->setClassMapAuthoritative(false);
  1334. }
  1335. return $this;
  1336. }
  1337. /**
  1338. * Whether or not generated autoloader considers the class map
  1339. * authoritative.
  1340. *
  1341. * @param bool $classMapAuthoritative
  1342. * @return Installer
  1343. */
  1344. public function setClassMapAuthoritative($classMapAuthoritative = false)
  1345. {
  1346. $this->classMapAuthoritative = (bool) $classMapAuthoritative;
  1347. if ($this->classMapAuthoritative) {
  1348. // Force optimizeAutoloader when classmap is authoritative
  1349. $this->setOptimizeAutoloader(true);
  1350. }
  1351. return $this;
  1352. }
  1353. /**
  1354. * Whether or not generated autoloader considers APCu caching.
  1355. *
  1356. * @param bool $apcuAutoloader
  1357. * @return Installer
  1358. */
  1359. public function setApcuAutoloader($apcuAutoloader = false)
  1360. {
  1361. $this->apcuAutoloader = (bool) $apcuAutoloader;
  1362. return $this;
  1363. }
  1364. /**
  1365. * update packages
  1366. *
  1367. * @param bool $update
  1368. * @return Installer
  1369. */
  1370. public function setUpdate($update = true)
  1371. {
  1372. $this->update = (bool) $update;
  1373. return $this;
  1374. }
  1375. /**
  1376. * enables dev packages
  1377. *
  1378. * @param bool $devMode
  1379. * @return Installer
  1380. */
  1381. public function setDevMode($devMode = true)
  1382. {
  1383. $this->devMode = (bool) $devMode;
  1384. return $this;
  1385. }
  1386. /**
  1387. * set whether to run autoloader or not
  1388. *
  1389. * This is disabled implicitly when enabling dryRun
  1390. *
  1391. * @param bool $dumpAutoloader
  1392. * @return Installer
  1393. */
  1394. public function setDumpAutoloader($dumpAutoloader = true)
  1395. {
  1396. $this->dumpAutoloader = (bool) $dumpAutoloader;
  1397. return $this;
  1398. }
  1399. /**
  1400. * set whether to run scripts or not
  1401. *
  1402. * This is disabled implicitly when enabling dryRun
  1403. *
  1404. * @param bool $runScripts
  1405. * @return Installer
  1406. */
  1407. public function setRunScripts($runScripts = true)
  1408. {
  1409. $this->runScripts = (bool) $runScripts;
  1410. return $this;
  1411. }
  1412. /**
  1413. * set the config instance
  1414. *
  1415. * @param Config $config
  1416. * @return Installer
  1417. */
  1418. public function setConfig(Config $config)
  1419. {
  1420. $this->config = $config;
  1421. return $this;
  1422. }
  1423. /**
  1424. * run in verbose mode
  1425. *
  1426. * @param bool $verbose
  1427. * @return Installer
  1428. */
  1429. public function setVerbose($verbose = true)
  1430. {
  1431. $this->verbose = (bool) $verbose;
  1432. return $this;
  1433. }
  1434. /**
  1435. * Checks, if running in verbose mode.
  1436. *
  1437. * @return bool
  1438. */
  1439. public function isVerbose()
  1440. {
  1441. return $this->verbose;
  1442. }
  1443. /**
  1444. * set ignore Platform Package requirements
  1445. *
  1446. * @param bool $ignorePlatformReqs
  1447. * @return Installer
  1448. */
  1449. public function setIgnorePlatformRequirements($ignorePlatformReqs = false)
  1450. {
  1451. $this->ignorePlatformReqs = (bool) $ignorePlatformReqs;
  1452. return $this;
  1453. }
  1454. /**
  1455. * restrict the update operation to a few packages, all other packages
  1456. * that are already installed will be kept at their current version
  1457. *
  1458. * @param array $packages
  1459. * @return Installer
  1460. */
  1461. public function setUpdateWhitelist(array $packages)
  1462. {
  1463. $this->updateWhitelist = array_flip(array_map('strtolower', $packages));
  1464. return $this;
  1465. }
  1466. /**
  1467. * @deprecated use setWhitelistTransitiveDependencies instead
  1468. */
  1469. public function setWhitelistDependencies($updateDependencies = true)
  1470. {
  1471. return $this->setWhitelistTransitiveDependencies($updateDependencies);
  1472. }
  1473. /**
  1474. * Should dependencies of whitelisted packages (but not direct dependencies) be updated?
  1475. *
  1476. * This will NOT whitelist any dependencies that are also directly defined
  1477. * in the root package.
  1478. *
  1479. * @param bool $updateTransitiveDependencies
  1480. * @return Installer
  1481. */
  1482. public function setWhitelistTransitiveDependencies($updateTransitiveDependencies = true)
  1483. {
  1484. $this->whitelistDependencies = (bool) $updateTransitiveDependencies;
  1485. return $this;
  1486. }
  1487. /**
  1488. * Should all dependencies of whitelisted packages be updated recursively?
  1489. *
  1490. * This will whitelist any dependencies of the whitelisted packages, including
  1491. * those defined in the root package.
  1492. *
  1493. * @param bool $updateAllDependencies
  1494. * @return Installer
  1495. */
  1496. public function setWhitelistAllDependencies($updateAllDependencies = true)
  1497. {
  1498. $this->whitelistAllDependencies = (bool) $updateAllDependencies;
  1499. return $this;
  1500. }
  1501. /**
  1502. * Should packages be preferred in a stable version when updating?
  1503. *
  1504. * @param bool $preferStable
  1505. * @return Installer
  1506. */
  1507. public function setPreferStable($preferStable = true)
  1508. {
  1509. $this->preferStable = (bool) $preferStable;
  1510. return $this;
  1511. }
  1512. /**
  1513. * Should packages be preferred in a lowest version when updating?
  1514. *
  1515. * @param bool $preferLowest
  1516. * @return Installer
  1517. */
  1518. public function setPreferLowest($preferLowest = true)
  1519. {
  1520. $this->preferLowest = (bool) $preferLowest;
  1521. return $this;
  1522. }
  1523. /**
  1524. * Should the lock file be updated when updating?
  1525. *
  1526. * This is disabled implicitly when enabling dryRun
  1527. *
  1528. * @param bool $writeLock
  1529. * @return Installer
  1530. */
  1531. public function setWriteLock($writeLock = true)
  1532. {
  1533. $this->writeLock = (bool) $writeLock;
  1534. return $this;
  1535. }
  1536. /**
  1537. * Should the operations (package install, update and removal) be executed on disk?
  1538. *
  1539. * This is disabled implicitly when enabling dryRun
  1540. *
  1541. * @param bool $executeOperations
  1542. * @return Installer
  1543. */
  1544. public function setExecuteOperations($executeOperations = true)
  1545. {
  1546. $this->executeOperations = (bool) $executeOperations;
  1547. return $this;
  1548. }
  1549. /**
  1550. * Should suggestions be skipped?
  1551. *
  1552. * @param bool $skipSuggest
  1553. * @return Installer
  1554. */
  1555. public function setSkipSuggest($skipSuggest = true)
  1556. {
  1557. $this->skipSuggest = (bool) $skipSuggest;
  1558. return $this;
  1559. }
  1560. /**
  1561. * Disables plugins.
  1562. *
  1563. * Call this if you want to ensure that third-party code never gets
  1564. * executed. The default is to automatically install, and execute
  1565. * custom third-party installers.
  1566. *
  1567. * @return Installer
  1568. */
  1569. public function disablePlugins()
  1570. {
  1571. $this->installationManager->disablePlugins();
  1572. return $this;
  1573. }
  1574. /**
  1575. * @param SuggestedPackagesReporter $suggestedPackagesReporter
  1576. * @return Installer
  1577. */
  1578. public function setSuggestedPackagesReporter(SuggestedPackagesReporter $suggestedPackagesReporter)
  1579. {
  1580. $this->suggestedPackagesReporter = $suggestedPackagesReporter;
  1581. return $this;
  1582. }
  1583. }