1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace EdmondsCommerce\PHPQA; |
||
6 | |||
7 | use Composer\Autoload\ClassLoader; |
||
8 | use Exception; |
||
9 | use ReflectionClass; |
||
10 | use RuntimeException; |
||
11 | |||
12 | final class Helper |
||
13 | { |
||
14 | /** |
||
15 | * @var string |
||
16 | */ |
||
17 | private static $projectRootDirectory; |
||
18 | |||
19 | /** |
||
20 | * @throws Exception |
||
21 | * |
||
22 | * @return array[] |
||
23 | * @SuppressWarnings(PHPMD.StaticAccess) |
||
24 | */ |
||
25 | 5 | public static function getComposerJsonDecoded(string $path = null): array |
|
26 | { |
||
27 | 5 | $path = $path ?? self::getProjectRootDirectory() . '/composer.json'; |
|
28 | 5 | $contents = (string)\file_get_contents($path); |
|
29 | 5 | if ($contents === '') { |
|
30 | throw new RuntimeException('composer.json is empty'); |
||
31 | } |
||
32 | 5 | $decoded = \json_decode($contents, true); |
|
33 | 5 | if (\json_last_error() !== JSON_ERROR_NONE) { |
|
34 | 1 | throw new RuntimeException('Failed loading composer.json: ' . \json_last_error_msg()); |
|
35 | } |
||
36 | |||
37 | 4 | return $decoded; |
|
38 | } |
||
39 | |||
40 | /** |
||
41 | * Get the absolute path to the root of the current project. |
||
42 | * |
||
43 | * It does this by working from the Composer autoloader which we know will be in a certain place in `vendor` |
||
44 | * |
||
45 | * @throws Exception |
||
46 | */ |
||
47 | 2 | public static function getProjectRootDirectory(): string |
|
48 | { |
||
49 | 2 | if (self::$projectRootDirectory === null) { |
|
0 ignored issues
–
show
introduced
by
![]() |
|||
50 | 1 | $reflection = new ReflectionClass(ClassLoader::class); |
|
51 | 1 | self::$projectRootDirectory = \dirname((string)$reflection->getFileName(), 3); |
|
52 | } |
||
53 | |||
54 | 2 | return self::$projectRootDirectory; |
|
55 | } |
||
56 | } |
||
57 |