Completed
Pull Request — master (#120)
by
unknown
39:17 queued 14:20
created

ExtraPackage::extractReferences()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 16
ccs 0
cts 0
cp 0
rs 9.2
cc 4
eloc 10
nc 3
nop 2
crap 20
1
<?php
2
/**
3
 * This file is part of the Composer Merge plugin.
4
 *
5
 * Copyright (C) 2015 Bryan Davis, Wikimedia Foundation, and contributors
6
 *
7
 * This software may be modified and distributed under the terms of the MIT
8
 * license. See the LICENSE file for details.
9
 */
10
11
namespace Wikimedia\Composer\Merge;
12
13
use Wikimedia\Composer\Logger;
14
15
use Composer\Composer;
16
use Composer\Json\JsonFile;
17
use Composer\Package\BasePackage;
18
use Composer\Package\CompletePackage;
19
use Composer\Package\Link;
20
use Composer\Package\Loader\ArrayLoader;
21
use Composer\Package\RootAliasPackage;
22
use Composer\Package\RootPackage;
23
use Composer\Package\RootPackageInterface;
24
use Composer\Package\Version\VersionParser;
25
use UnexpectedValueException;
26
27
/**
28
 * Processing for a composer.json file that will be merged into
29
 * a RootPackageInterface
30
 *
31
 * @author Bryan Davis <[email protected]>
32
 */
33
class ExtraPackage
34
{
35
36
    /**
37
     * @var Composer $composer
38
     */
39
    protected $composer;
40
41
    /**
42
     * @var Logger $logger
43
     */
44
    protected $logger;
45
46
    /**
47
     * @var string $path
48
     */
49
    protected $path;
50
51
    /**
52
     * @var array $json
53
     */
54
    protected $json;
55
56
    /**
57
     * @var CompletePackage $package
58
     */
59
    protected $package;
60
61
    /**
62
     * @var VersionParser $versionParser
63
     */
64
    protected $versionParser;
65
66
    /**
67
     * @param string $path Path to composer.json file
68
     * @param Composer $composer
69
     * @param Logger $logger
70
     */
71 95
    public function __construct($path, Composer $composer, Logger $logger)
72
    {
73 95
        $this->path = $path;
74 95
        $this->composer = $composer;
75 95
        $this->logger = $logger;
76 95
        $this->json = $this->readPackageJson($path);
77 95
        $this->package = $this->loadPackage($this->json);
0 ignored issues
show
Documentation introduced by
$this->json is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
78 95
        $this->versionParser = new VersionParser();
79 95
    }
80
81
    /**
82
     * Get list of additional packages to include if precessing recursively.
83
     *
84
     * @return array
85
     */
86 90
    public function getIncludes()
87
    {
88 90
        return isset($this->json['extra']['merge-plugin']['include']) ?
89 90
            $this->json['extra']['merge-plugin']['include'] : array();
90
    }
91
92
    /**
93
     * Get list of additional packages to require if precessing recursively.
94
     *
95
     * @return array
96
     */
97 90
    public function getRequires()
98
    {
99 90
        return isset($this->json['extra']['merge-plugin']['require']) ?
100 90
            $this->json['extra']['merge-plugin']['require'] : array();
101
    }
102
103
    /**
104
     * Read the contents of a composer.json style file into an array.
105
     *
106
     * The package contents are fixed up to be usable to create a Package
107
     * object by providing dummy "name" and "version" values if they have not
108
     * been provided in the file. This is consistent with the default root
109
     * package loading behavior of Composer.
110
     *
111
     * @param string $path
112
     * @return array
113
     */
114 95
    protected function readPackageJson($path)
115
    {
116 95
        $file = new JsonFile($path);
117 95
        $json = $file->read();
118 95
        if (!isset($json['name'])) {
119 90
            $json['name'] = 'merge-plugin/' .
120 90
                strtr($path, DIRECTORY_SEPARATOR, '-');
121 90
        }
122 95
        if (!isset($json['version'])) {
123 95
            $json['version'] = '1.0.0';
124 95
        }
125 95
        return $json;
126
    }
127
128
    /**
129
     * @param string $json
130
     * @return CompletePackage
131
     */
132 95
    protected function loadPackage($json)
133
    {
134 95
        $loader = new ArrayLoader();
135 95
        $package = $loader->load($json);
0 ignored issues
show
Documentation introduced by
$json is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
136
        // @codeCoverageIgnoreStart
137
        if (!$package instanceof CompletePackage) {
138
            throw new UnexpectedValueException(
139
                'Expected instance of CompletePackage, got ' .
140
                get_class($package)
141
            );
142
        }
143
        // @codeCoverageIgnoreEnd
144 95
        return $package;
145
    }
146
147
    /**
148
     * Merge this package into a RootPackageInterface
149
     *
150
     * @param RootPackageInterface $root
151
     * @param PluginState $state
152
     */
153 95
    public function mergeInto(RootPackageInterface $root, PluginState $state)
154
    {
155 95
        $this->addRepositories($root, $state->shouldPrependRepositories());
156
157 95
        $this->mergeRequires('require', $root, $state);
158 95
        if ($state->isDevMode()) {
159 90
            $this->mergeRequires('require-dev', $root, $state);
160 90
        }
161
162 95
        $this->mergePackageLinks('conflict', $root);
163 95
        $this->mergePackageLinks('replace', $root);
164 95
        $this->mergePackageLinks('provide', $root);
165
166 95
        $this->mergeSuggests($root);
167
168 95
        $this->mergeAutoload('autoload', $root);
169 95
        if ($state->isDevMode()) {
170 90
            $this->mergeAutoload('devAutoload', $root);
171 90
        }
172
173 95
        $this->mergeExtra($root, $state);
174 95
        $this->mergeReferences($root);
175 95
    }
176
177
    /**
178
     * Add a collection of repositories described by the given configuration
179
     * to the given package and the global repository manager.
180
     *
181
     * @param RootPackageInterface $root
182
     * @param bool $prepend Should repositories be prepended to repository manager.
183 95
     */
184
    protected function addRepositories(RootPackageInterface $root, $prepend)
185 95
    {
186 85
        if (!isset($this->json['repositories'])) {
187
            return;
188 10
        }
189 10
        $repoManager = $this->composer->getRepositoryManager();
190
        $newRepos = array();
191 10
192 10
        foreach ($this->json['repositories'] as $repoJson) {
193 10
            if (!isset($repoJson['type'])) {
194
                continue;
195 10
            }
196 10
            if ($prepend) {
197 10
                $this->logger->info("Adding {$repoJson['type']} repository");
198
            } else {
199 10
                $this->logger->info("Prepending {$repoJson['type']} repository");
200 10
            }
201 10
            $repo = $repoManager->createRepository(
202 10
                $repoJson['type'],
203
                $repoJson
204 10
            );
205 10
            if ($prepend) {
206 10
                $repoManager->prependRepository($repo);
207 10
            } else {
208 10
                $repoManager->addRepository($repo);
209 10
            }
210
            $newRepos[] = $repo;
211
        }
212
213
        $unwrapped = self::unwrapIfNeeded($root, 'setRepositories');
214
        if ($prepend) {
215
            $unwrapped->setRepositories(array_merge(
216
                $newRepos,
217
                $root->getRepositories()
218 95
            ));
219
        } else {
220
            $unwrapped->setRepositories(array_merge(
221
                $root->getRepositories(),
222
                $newRepos
223 95
            ));
224 95
        }
225 95
    }
226
227 95
    /**
228 95
     * Merge require or require-dev into a RootPackageInterface
229 75
     *
230
     * @param string $type 'require' or 'require-dev'
231
     * @param RootPackageInterface $root
232 65
     * @param PluginState $state
233
     */
234 65
    protected function mergeRequires(
235 65
        $type,
236 65
        RootPackageInterface $root,
237
        PluginState $state
238 65
    ) {
239
        $linkType = BasePackage::$supportedLinkTypes[$type];
240 65
        $getter = 'get' . ucfirst($linkType['method']);
241 65
        $setter = 'set' . ucfirst($linkType['method']);
242 65
243 65
        $requires = $this->package->{$getter}();
244
        if (empty($requires)) {
245 65
            return;
246 65
        }
247
248
        $this->mergeStabilityFlags($root, $requires);
249
250
        $requires = $this->replaceSelfVersionDependencies(
251
            $type,
252
            $requires,
253
            $root
254
        );
255
256
        $root->{$setter}($this->mergeOrDefer(
257
            $type,
258 65
            $root->{$getter}(),
259
            $requires,
260
            $state
261
        ));
262
    }
263
264 65
    /**
265 65
     * Merge two collections of package links and collect duplicates for
266 65
     * subsequent processing.
267 65
     *
268 65
     * @param string $type 'require' or 'require-dev'
269 65
     * @param array $origin Primary collection
270
     * @param array $merge Additional collection
271 15
     * @param PluginState $state
272 15
     * @return array Merged collection
273 15
     */
274 15
    protected function mergeOrDefer(
275
        $type,
276 65
        array $origin,
277 65
        array $merge,
278 65
        $state
279
    ) {
280
        $dups = array();
281
        foreach ($merge as $name => $link) {
282
            if (!isset($origin[$name]) || $state->replaceDuplicateLinks()) {
283
                $this->logger->info("Merging <comment>{$name}</comment>");
284
                $origin[$name] = $link;
285
            } else {
286
                // Defer to solver.
287 95
                $this->logger->info(
288
                    "Deferring duplicate <comment>{$name}</comment>"
289 95
                );
290 95
                $dups[] = $link;
291
            }
292 95
        }
293 95
        $state->addDuplicateLinks($type, $dups);
294 90
        return $origin;
295
    }
296
297 10
    /**
298 10
     * Merge autoload or autoload-dev into a RootPackageInterface
299 10
     *
300 10
     * @param string $type 'autoload' or 'devAutoload'
301 10
     * @param RootPackageInterface $root
302 10
     */
303
    protected function mergeAutoload($type, RootPackageInterface $root)
304
    {
305
        $getter = 'get' . ucfirst($type);
306
        $setter = 'set' . ucfirst($type);
307
308
        $autoload = $this->package->{$getter}();
309
        if (empty($autoload)) {
310
            return;
311 10
        }
312
313 10
        $unwrapped = self::unwrapIfNeeded($root, $setter);
314 10
        $unwrapped->{$setter}(array_merge_recursive(
315
            $root->{$getter}(),
316 10
            $this->fixRelativePaths($autoload)
317 10
        ));
318
    }
319 10
320 10
    /**
321 10
     * Fix a collection of paths that are relative to this package to be
322 10
     * relative to the base package.
323
     *
324
     * @param array $paths
325
     * @return array
326
     */
327
    protected function fixRelativePaths(array $paths)
328
    {
329
        $base = dirname($this->path);
330
        $base = ($base === '.') ? '' : "{$base}/";
331
332 65
        array_walk_recursive(
333
            $paths,
334
            function (&$path) use ($base) {
335
                $path = "{$base}{$path}";
336 65
            }
337 65
        );
338
        return $paths;
339 65
    }
340 65
341 65
    /**
342 65
     * Extract and merge stability flags from the given collection of
343 65
     * requires and merge them into a RootPackageInterface
344 65
     *
345
     * @param RootPackageInterface $root
346
     * @param array $requires
347
     */
348
    protected function mergeStabilityFlags(
349
        RootPackageInterface $root,
350
        array $requires
351
    ) {
352 95
        $flags = $root->getStabilityFlags();
353
        $sf = new StabilityFlags($flags, $root->getMinimumStability());
354 95
355 95
        $unwrapped = self::unwrapIfNeeded($root, 'setStabilityFlags');
356 95
        $unwrapped->setStabilityFlags(array_merge(
357
            $flags,
358 95
            $sf->extractAll($requires)
359 95
        ));
360 20
    }
361
362
    /**
363
     * Merge package links of the given type  into a RootPackageInterface
364
     *
365
     * @param string $type 'conflict', 'replace' or 'provide'
366
     * @param RootPackageInterface $root
367
     */
368
    protected function mergePackageLinks($type, RootPackageInterface $root)
369 20
    {
370 20
        $linkType = BasePackage::$supportedLinkTypes[$type];
371 20
        $getter = 'get' . ucfirst($linkType['method']);
372 20
        $setter = 'set' . ucfirst($linkType['method']);
373 20
374 95
        $links = $this->package->{$getter}();
375
        if (!empty($links)) {
376
            $unwrapped = self::unwrapIfNeeded($root, $setter);
377
            // @codeCoverageIgnoreStart
378
            if ($root !== $unwrapped) {
379
                $this->logger->warning(
380
                    'This Composer version does not support ' .
381 95
                    "'{$type}' merging for aliased packages."
382
                );
383 95
            }
384 95
            // @codeCoverageIgnoreEnd
385 10
            $unwrapped->{$setter}(array_merge(
386 10
                $root->{$getter}(),
387 10
                $this->replaceSelfVersionDependencies($type, $links, $root)
388
            ));
389 10
        }
390 10
    }
391 95
392
    /**
393
     * Merge suggested packages into a RootPackageInterface
394
     *
395
     * @param RootPackageInterface $root
396
     */
397
    protected function mergeSuggests(RootPackageInterface $root)
398
    {
399 95
        $suggests = $this->package->getSuggests();
400
        if (!empty($suggests)) {
401 95
            $unwrapped = self::unwrapIfNeeded($root, 'setSuggests');
402 95
            $unwrapped->setSuggests(array_merge(
403 95
                $root->getSuggests(),
404 80
                $suggests
405
            ));
406
        }
407 15
    }
408 15
409
    /**
410 15
     * Merge extra config into a RootPackageInterface
411 5
     *
412 5
     * @param RootPackageInterface $root
413 5
     * @param PluginState $state
414
     */
415 5
    public function mergeExtra(RootPackageInterface $root, PluginState $state)
416 10
    {
417 10
        $extra = $this->package->getExtra();
418 10
        unset($extra['merge-plugin']);
419 10
        if (!$state->shouldMergeExtra() || empty($extra)) {
420 5
            return;
421 5
        }
422 5
423 5
        $rootExtra = $root->getExtra();
424 10
        $unwrapped = self::unwrapIfNeeded($root, 'setExtra');
425 10
426 10
        if ($state->replaceDuplicateLinks()) {
427 10
            $unwrapped->setExtra(
428
                array_merge($rootExtra, $extra)
429 15
            );
430
431
        } else {
432
            foreach (array_intersect(
433
                array_keys($extra),
434
                array_keys($rootExtra)
435
            ) as $key) {
436
                $this->logger->info(
437
                    "Ignoring duplicate <comment>{$key}</comment> in ".
438
                    "<comment>{$this->path}</comment> extra config."
439
                );
440 75
            }
441
            $unwrapped->setExtra(
442
                array_merge($extra, $rootExtra)
443
            );
444
        }
445 75
    }
446 75
447 75
    /**
448 75
     * Update Links with a 'self.version' constraint with the root package's
449
     * version.
450 75
     *
451 75
     * @param string $type Link type
452
     * @param array $links
453 75
     * @param RootPackageInterface $root
454 75
     * @return array
455 75
     */
456 10
    protected function replaceSelfVersionDependencies(
457
        $type,
458 5
        array $links,
459 5
        RootPackageInterface $root
460 5
    ) {
461 5
        $linkType = BasePackage::$supportedLinkTypes[$type];
462 5
        $version = $root->getVersion();
463 5
        $prettyVersion = $root->getPrettyVersion();
464 5
        $vp = $this->versionParser;
465 5
466
        $method = 'get' . ucfirst($linkType['method']);
467
        $packages = $root->$method();
468 5
469 5
        return array_map(
470 5
            function ($link) use ($linkType, $version, $prettyVersion, $vp, $packages) {
471 5
                if ('self.version' === $link->getPrettyConstraint()) {
472 5
                    if (isset($packages[$link->getSource()])) {
473
                        /** @var Link $package */
474 5
                        $package = $packages[$link->getSource()];
475
                        return new Link(
476 75
                            $link->getSource(),
477 75
                            $link->getTarget(),
478
                            $vp->parseConstraints($package->getConstraint()->getPrettyString()),
479 75
                            $linkType['description'],
480
                            $package->getPrettyConstraint()
481
                        );
482
                    }
483
484
                    return new Link(
485
                        $link->getSource(),
486
                        $link->getTarget(),
487
                        $vp->parseConstraints($version),
488
                        $linkType['description'],
489
                        $prettyVersion
490
                    );
491
                }
492
                return $link;
493
            },
494
            $links
495
        );
496
    }
497
498
    /**
499 95
     * Get a full featured Package from a RootPackageInterface.
500
     *
501
     * In Composer versions before 599ad77 the RootPackageInterface only
502
     * defines a sub-set of operations needed by composer-merge-plugin and
503
     * RootAliasPackage only implemented those methods defined by the
504
     * interface. Most of the unimplemented methods in RootAliasPackage can be
505
     * worked around because the getter methods that are implemented proxy to
506
     * the aliased package which we can modify by unwrapping. The exception
507
     * being modifying the 'conflicts', 'provides' and 'replaces' collections.
508
     * We have no way to actually modify those collections unfortunately in
509
     * older versions of Composer.
510
     *
511 95
     * @param RootPackageInterface $root
512
     * @param string $method Method needed
513
     * @return RootPackageInterface|RootPackage
514
     */
515
    public static function unwrapIfNeeded(
516
        RootPackageInterface $root,
517
        $method = 'setExtra'
518
    ) {
519 95
        // @codeCoverageIgnoreStart
520
        if ($root instanceof RootAliasPackage &&
521
            !method_exists($root, $method)
522
        ) {
523 95
            // Unwrap and return the aliased RootPackage.
524 95
            $root = $root->getAliasOf();
525 95
        }
526 95
        // @codeCoverageIgnoreEnd
527 95
        return $root;
528 95
    }
529 95
530 35
    /**
531 95
     * Update the root packages reference information.
532 95
     *
533 95
     * @param RootPackageInterface $root
534 95
     */
535 95
    protected function mergeReferences(RootPackageInterface $root)
536
    {
537
        // Merge source reference information for merged packages.
538
        // @see RootPackageLoader::load
539
        $references = array();
540
        $unwrapped = $this->unwrapIfNeeded($root, 'setReferences');
541
        foreach (array('require', 'require-dev') as $linkType) {
542
            $linkInfo = BasePackage::$supportedLinkTypes[$linkType];
543
            $method = 'get'.ucfirst($linkInfo['method']);
544
            $links = array();
545 95
            foreach ($unwrapped->$method() as $link) {
546
                $links[$link->getTarget()] = $link->getConstraint()->getPrettyString();
547 95
            }
548 35
            $references = $this->extractReferences($links, $references);
549 35
        }
550
        $unwrapped->setReferences($references);
551 35
    }
552
553 35
    /**
554 5
     * Extract vcs revision from version constraint (dev-master#abc123.
555 5
     *
556 5
     * @param array $requires
557 95
     * @param array $references
558
     * @return array
559 95
     * @see RootPackageLoader::extractReferences()
560
     */
561
    protected function extractReferences(array $requires, array $references)
562
    {
563
        foreach ($requires as $reqName => $reqVersion) {
564
            $reqVersion = preg_replace('{^([^,\s@]+) as .+$}', '$1', $reqVersion);
565
            $stabilityName = VersionParser::parseStability($reqVersion);
566
            if (
567
                preg_match('{^[^,\s@]+?#([a-f0-9]+)$}', $reqVersion, $match) &&
568
                $stabilityName === 'dev'
569
            ) {
570
                $name = strtolower($reqName);
571
                $references[$name] = $match[1];
572
            }
573
        }
574
575
        return $references;
576
    }
577
}
578
// vim:sw=4:ts=4:sts=4:et:
579