Passed
Push — master ( a2e26c...517afa )
by Théo
03:09
created

InstalledPackagesScoper::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.5

Importance

Changes 0
Metric Value
cc 2
eloc 7
nc 2
nop 1
dl 0
loc 12
ccs 4
cts 8
cp 0.5
crap 2.5
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the humbug/php-scoper package.
7
 *
8
 * Copyright (c) 2017 Théo FIDRY <[email protected]>,
9
 *                    Pádraic Brady <[email protected]>
10
 *
11
 * For the full copyright and license information, please view the LICENSE
12
 * file that was distributed with this source code.
13
 */
14
15
namespace Humbug\PhpScoper\Scoper\Composer;
16
17
use Humbug\PhpScoper\Scoper;
18
use LogicException;
19
20
final class InstalledPackagesScoper implements Scoper
21
{
22
    /**
23
     * @var string
24
     */
25
    private static $filePattern;
26
27
    private $decoratedScoper;
28
29 2
    public function __construct(Scoper $decoratedScoper)
30
    {
31 2
        if (null === self::$filePattern) {
32
            self::$filePattern = str_replace(
33
                '/',
34
                DIRECTORY_SEPARATOR,
35
                '~composer/installed\.json~'
36
            );
37
        }
38
39 2
        $this->decoratedScoper = $decoratedScoper;
40 2
    }
41
42
    /**
43
     * Scopes PHP and JSON files related to Composer.
44
     *
45
     * {@inheritdoc}
46
     */
47 2
    public function scope(string $filePath, string $prefix): string
48
    {
49 2
        if (null === self::$filePattern) {
50
            throw new LogicException('Cannot be used without being initialised first.');
51
        }
52
53 2
        if (1 !== preg_match(self::$filePattern, $filePath)) {
54 1
            return $this->decoratedScoper->scope($filePath, $prefix);
55
        }
56
57 1
        $decodedJson = json_decode(
58
            file_get_contents($filePath),
59 1
            true
60
        );
61
62 1
        $decodedJson = $this->prefixLockPackages($decodedJson, $prefix);
63
64 1
        return json_encode(
65
            $decodedJson,
66 1
            JSON_PRETTY_PRINT
67
        );
68
    }
69
70 1
    private function prefixLockPackages(array $packages, string $prefix): array
71
    {
72 1
        foreach ($packages as $index => $package) {
73 1
            $packages[$index] = AutoloadPrefixer::prefixPackageAutoloads($package, $prefix);
74
        }
75
76 1
        return $packages;
77
    }
78
}
79