Passed
Push — master ( a58ad3...cb98e4 )
by Ehsan
02:50
created

AbstractConfig::get()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4.432

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 7
cts 10
cp 0.7
rs 9.2
c 0
b 0
f 0
cc 4
eloc 12
nc 5
nop 3
crap 4.432
1
<?php
2
3
namespace Botonomous;
4
5
use Botonomous\utility\ArrayUtility;
6
use Botonomous\utility\StringUtility;
7
8
/**
9
 * Class AbstractConfig.
10
 */
11
abstract class AbstractConfig
12
{
13
    protected static $configs;
14
15
    /**
16
     * @param       $key
17
     * @param array $replacements
18
     *
19
     * @throws \Exception
20
     *
21
     * @return mixed
22
     */
23 105
    public function get($key, $replacements = [], $plugin = null)
24
    {
25 105
        if ($plugin !== null) {
26
            try {
27
                $configs = $this->getPluginConfigs($plugin);
28
            } catch (\Exception $e) {
29
                throw $e;
30
            }
31
        } else {
32 105
            $configs = static::$configs;
33
        }
34
35 105
        if (!array_key_exists($key, $configs)) {
36 1
            throw new \Exception("Key: '{$key}' does not exist in configs");
37
        }
38
39 104
        $found = $configs[$key];
40
41 104
        return (new StringUtility())->applyReplacements($found, $replacements);
42
    }
43
44
    public function getPluginConfigs($plugin)
45
    {
46
        $pluginConfigClass = __NAMESPACE__."\\components\\".strtolower($plugin)
47
            .'\\'.ucfirst($plugin).'Config';
48
49
        if (!class_exists($pluginConfigClass)) {
50
            throw new \Exception("Config file: '{$pluginConfigClass}.php' does not exist");
51
        }
52
53
        $pluginConfigObject = new $pluginConfigClass();
54
        if (!$pluginConfigObject instanceof self) {
55
            throw new \Exception("Class: '{$pluginConfigClass}' must extend BaseConfig");
56
        }
57
58
        return $pluginConfigObject->getConfigs();
59
    }
60
61
    public function getConfigs()
62
    {
63
        return static::$configs;
64
    }
65
66
    /**
67
     * @param $key
68
     * @param $value
69
     */
70 37
    public function set($key, $value)
71
    {
72 37
        is_array($key) ? (new ArrayUtility())->setNestedArrayValue(static::$configs, $key, $value)
73 20
            : static::$configs[$key] = $value;
74 37
    }
75
}
76