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