Passed
Pull Request — master (#46)
by Théo
02:11
created

ConfigurationHelper::getName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the box project.
7
 *
8
 * (c) Kevin Herrera <[email protected]>
9
 *     Théo Fidry <[email protected]>
10
 *
11
 * This source file is subject to the MIT license that is bundled
12
 * with this source code in the file LICENSE.
13
 */
14
15
namespace KevinGH\Box\Console;
16
17
use KevinGH\Box\Configuration;
18
use KevinGH\Box\Json\Json;
19
use RuntimeException;
20
use Symfony\Component\Console\Helper\Helper;
21
use Webmozart\PathUtil\Path;
22
use function KevinGH\Box\is_absolute;
23
24
/*
25
 * The Box schema file path.
26
 *
27
 * @var string
28
 */
29
define('BOX_SCHEMA_FILE', BOX_PATH.'/res/schema.json');
30
31
final class ConfigurationHelper extends Helper
32
{
33
    private const FILE_NAME = 'box.json';
34
35
    private $json;
36
37
    public function __construct()
38
    {
39
        $this->json = new Json();
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    public function getName(): string
46
    {
47
        return 'config';
48
    }
49
50
    public function findDefaultPath(): string
51
    {
52
        if (false === file_exists(self::FILE_NAME)) {
53
            if (false === file_exists(self::FILE_NAME.'.dist')) {
54
                throw new RuntimeException(
55
                    sprintf('The configuration file could not be found.')
56
                );
57
            }
58
59
            return realpath(self::FILE_NAME.'.dist');
60
        }
61
62
        return realpath(self::FILE_NAME);
63
    }
64
65
    public function loadFile(?string $file): Configuration
66
    {
67
        if (null === $file) {
68
            $file = $this->findDefaultPath();
69
        }
70
71
        $json = $this->json->decodeFile($file);
72
73
        // Include imports
74
        if (isset($json->import)) {
75
            if (!is_absolute($json->import)) {
76
                $json->import = Path::join(
77
                    [
78
                        dirname($file),
79
                        $json->import,
80
                    ]
81
                );
82
            }
83
84
            $json = (object) array_merge(
85
                (array) $this->json->decodeFile($json->import),
86
                (array) $json
87
            );
88
        }
89
90
        $this->json->validate(
91
            $file,
92
            $json,
93
            $this->json->decodeFile(BOX_SCHEMA_FILE)
94
        );
95
96
        return Configuration::create($file, $json);
97
    }
98
}
99