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
|
|
|
|
34
|
|
|
public function __construct(Scoper $decoratedScoper) |
35
|
|
|
{ |
36
|
|
|
$this->decoratedScoper = $decoratedScoper; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
10 |
|
* Scopes PHP and JSON files related to Composer. |
41
|
|
|
*/ |
42
|
10 |
|
public function scope(string $filePath, string $contents, string $prefix, array $patchers, Whitelist $whitelist): string |
43
|
1 |
|
{ |
44
|
|
|
if (1 !== native_preg_match('/composer\.json$/', $filePath)) { |
45
|
|
|
return $this->decoratedScoper->scope($filePath, $contents, $prefix, $patchers, $whitelist); |
46
|
9 |
|
} |
47
|
|
|
|
48
|
9 |
|
$decodedJson = self::decodeContents($contents); |
49
|
|
|
|
50
|
|
|
$decodedJson = AutoloadPrefixer::prefixPackageAutoloadStatements($decodedJson, $prefix, $whitelist); |
51
|
|
|
|
52
|
|
|
return json_encode( |
53
|
|
|
$decodedJson, |
54
|
|
|
JSON_PRETTY_PRINT |
55
|
|
|
); |
56
|
|
|
} |
57
|
9 |
|
|
58
|
|
|
private static function decodeContents(string $contents): stdClass |
59
|
9 |
|
{ |
60
|
9 |
|
$decodedJson = json_decode($contents, false, 512, JSON_THROW_ON_ERROR); |
61
|
9 |
|
|
62
|
|
|
if ($decodedJson instanceof stdClass) { |
63
|
|
|
return $decodedJson; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
throw new InvalidArgumentException( |
67
|
|
|
sprintf( |
68
|
|
|
'Expected the decoded JSON to be an stdClass instance, got "%s" instead', |
69
|
|
|
gettype($decodedJson), |
70
|
|
|
) |
71
|
|
|
); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|