Passed
Push — master ( b93774...524bd5 )
by Bruno
03:46
created

Options::setSectionDefaults()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 8
ccs 0
cts 5
cp 0
crap 6
rs 10
1
<?php declare(strict_types=1);
2
3
namespace Modelarium;
4
5
use ArrayAccess;
6
7
use function Safe\file_get_contents;
8
use function Safe\getcwd;
9
use function Safe\json_decode;
10
use function Safe\substr;
11
12
class Options
13
{
14
    /**
15
     * @var string
16
     */
17
    public $basePath = null;
18
19
    /**
20
     *
21
     * @var array
22
     */
23
    public $options = [];
24
25
    public function __construct(string $basePath = null)
26
    {
27
        $this->basePath = $basePath;
28
        $this->options = $this->loadOptions();
29
    }
30
31
    /**
32
     * Gets a value
33
     *
34
     * @param string $section
35
     * @param string $key
36
     * @param mixed $default
37
     * @return mixed
38
     */
39
    public function getOption(string $section, string $key, $default = null)
40
    {
41
        return $this->options[$section][$key] ?? $default;
42
    }
43
44
    public function getSection(string $section): array
45
    {
46
        return $this->options[$section] ?? [];
47
    }
48
49
    public function setSectionDefaults(string $section, array $defaults): self
50
    {
51
        if (!array_key_exists($section, $this->options)) {
52
            $this->options[$section] = $defaults;
53
        } else {
54
            $this->options[$section] = array_merge($defaults, $this->options[$section]);
55
        }
56
        return $this;
57
    }
58
59
    /**
60
     * Returns the base path where we expect to find the options
61
     *
62
     * @return string
63
     */
64
    protected function getBasePath(): string
65
    {
66
        if ($this->basePath) {
67
            return $this->basePath;
68
        }
69
        // assume we're in vendor/
70
        $path = __DIR__;
71
        $start = mb_strpos('/vendor/', $path);
72
        if ($start !== false) {
73
            return substr($path, $start);
74
        }
75
        return getcwd();
76
    }
77
78
    protected function loadOptions(): array
79
    {
80
        $filename = $this->getBasePath() . '/modelarium.json';
81
        if (!file_exists($filename)) {
82
            return [];
83
        }
84
        return json_decode(file_get_contents($filename), true);
85
    }
86
}
87