Completed
Pull Request — master (#103)
by Florian
21:59
created

ExtraPackage::mergeInto()   B

Complexity

Conditions 5
Paths 12

Size

Total Lines 36
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 5

Importance

Changes 10
Bugs 0 Features 3
Metric Value
c 10
b 0
f 3
dl 0
loc 36
ccs 21
cts 21
cp 1
rs 8.439
cc 5
eloc 22
nc 12
nop 2
crap 5
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 80
    /**
67
     * @param string $path Path to composer.json file
68 80
     * @param Composer $composer
69 80
     * @param Logger $logger
70 80
     */
71 80
    public function __construct($path, Composer $composer, Logger $logger)
72 80
    {
73 80
        $this->path = $path;
74
        $this->composer = $composer;
75
        $this->logger = $logger;
76
        $this->json = $this->readPackageJson($path);
77
        $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
        $this->versionParser = new VersionParser();
79
    }
80 75
81
    /**
82 75
     * Get list of additional packages to include if precessing recursively.
83 75
     *
84
     * @return array
85
     */
86
    public function getIncludes()
87
    {
88
        return isset($this->json['extra']['merge-plugin']['include']) ?
89
            $this->json['extra']['merge-plugin']['include'] : array();
90
    }
91 75
92
    /**
93 75
     * Get list of additional packages to require if precessing recursively.
94 75
     *
95
     * @return array
96
     */
97
    public function getRequires()
98
    {
99
        return isset($this->json['extra']['merge-plugin']['require']) ?
100
            $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 80
     * been provided in the file. This is consistent with the default root
109
     * package loading behavior of Composer.
110 80
     *
111 80
     * @param string $path
112 80
     * @return array
113 80
     */
114 80
    protected function readPackageJson($path)
115 80
    {
116 80
        $file = new JsonFile($path);
117 80
        $json = $file->read();
118 80
        if (!isset($json['name'])) {
119 80
            $json['name'] = 'merge-plugin/' .
120
                strtr($path, DIRECTORY_SEPARATOR, '-');
121
        }
122
        if (!isset($json['version'])) {
123
            $json['version'] = '1.0.0';
124
        }
125
        return $json;
126 80
    }
127
128 80
    /**
129 80
     * @param string $json
130
     * @return CompletePackage
131
     */
132
    protected function loadPackage($json)
133
    {
134
        $loader = new ArrayLoader();
135
        $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 80
            throw new UnexpectedValueException(
139
                'Expected instance of CompletePackage, got ' .
140
                get_class($package)
141
            );
142
        }
143
        // @codeCoverageIgnoreEnd
144
        return $package;
145
    }
146
147 80
    /**
148
     * Merge this package into a RootPackageInterface
149 80
     *
150
     * @param RootPackageInterface $root
151 80
     * @param PluginState $state
152 80
     */
153 75
    public function mergeInto(RootPackageInterface $root, PluginState $state)
154 75
    {
155
        $this->addRepositories($root);
156 80
157 80
        $this->mergeRequires('require', $root, $state);
158 80
        if ($state->isDevMode()) {
159
            $this->mergeRequires('require-dev', $root, $state);
160 80
        }
161
162 80
        $this->mergePackageLinks('conflict', $root);
163 80
        $this->mergePackageLinks('replace', $root);
164 75
        $this->mergePackageLinks('provide', $root);
165 75
166
        $this->mergeSuggests($root);
167 80
168 80
        $this->mergeAutoload('autoload', $root);
169
        if ($state->isDevMode()) {
170
            $this->mergeAutoload('devAutoload', $root);
171
        }
172
173
        $this->mergeExtra($root, $state);
174
175
        // Merge source reference information for merged packages.
176 80
        // @see RootPackageLoader::load
177
        $references = array();
178 80
        foreach (array('require', 'require-dev') as $linkType) {
179 75
            $linkInfo = BasePackage::$supportedLinkTypes[$linkType];
180
            $method = 'get'.ucfirst($linkInfo['method']);
181 5
            $links = array();
182 5
            foreach ($root->$method() as $link) {
183
                $links[$link->getTarget()] = $link->getConstraint()->getPrettyString();
184 5
            }
185 5
            $references = $this->extractReferences($links, $references);
186 5
        }
187
        $root->setReferences($references);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Composer\Package\RootPackageInterface as the method setReferences() does only exist in the following implementations of said interface: Composer\Package\RootPackage.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

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