Passed
Pull Request — master (#555)
by Théo
02:17
created

JsonFileScoper::decodeContents()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 7
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 12
ccs 0
cts 0
cp 0
crap 6
rs 10
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 Humbug\PhpScoper\Whitelist;
19
use InvalidArgumentException;
20
use LogicException;
21
use stdClass;
22
use function gettype;
23
use function preg_match as native_preg_match;
24
use function Safe\json_decode;
25
use function Safe\json_encode;
26
use function Safe\sprintf;
27
use const JSON_PRETTY_PRINT;
28
use const JSON_THROW_ON_ERROR;
29
30 10
final class JsonFileScoper implements Scoper
31
{
32 10
    private Scoper $decoratedScoper;
33
    private AutoloadPrefixer $autoloadPrefixer;
34
35
    public function __construct(
36
        Scoper $decoratedScoper,
37
        AutoloadPrefixer $autoloadPrefixer
38
    ) {
39
        $this->decoratedScoper = $decoratedScoper;
40 10
        $this->autoloadPrefixer = $autoloadPrefixer;
41
    }
42 10
43 1
    /**
44
     * Scopes PHP and JSON files related to Composer.
45
     */
46 9
    public function scope(string $filePath, string $contents): string
47
    {
48 9
        if (1 !== native_preg_match('/composer\.json$/', $filePath)) {
49
            return $this->decoratedScoper->scope($filePath, $contents);
50
        }
51
52
        $decodedJson = self::decodeContents($contents);
53
54
        $decodedJson = $this->autoloadPrefixer->prefixPackageAutoloadStatements($decodedJson);
55
56
        return json_encode(
57 9
            $decodedJson,
58
            JSON_PRETTY_PRINT
59 9
        );
60 9
    }
61 9
62
    private static function decodeContents(string $contents): stdClass
63
    {
64
        $decodedJson = json_decode($contents, false, 512,  JSON_THROW_ON_ERROR);
65
66
        if ($decodedJson instanceof stdClass) {
67
            return $decodedJson;
68
        }
69
70
        throw new InvalidArgumentException(
71
            sprintf(
72
                'Expected the decoded JSON to be an stdClass instance, got "%s" instead',
73
                gettype($decodedJson),
74
            )
75
        );
76
    }
77
}
78