Completed
Pull Request — master (#71)
by Ankit
02:08
created

Config::get()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 9
nc 4
nop 1
dl 0
loc 18
ccs 0
cts 10
cp 0
crap 20
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
namespace TusPhp;
4
5
class Config
6
{
7
    /** @const string */
8
    const DEFAULT_CONFIG_PATH = __DIR__ . '/Config/default.php';
9
10
    /** @var array */
11
    protected static $config = [];
12
13
    /**
14
     * Load default application configs.
15
     *
16
     * @param string|array $config
17
     * @param bool         $force
18
     *
19
     * @return void
20
     */
21
    public static function setConfig($config = null, bool $force = false)
22
    {
23
        if ( ! $force && ! empty(self::$config)) {
24
            return;
25
        }
26
27
        if (is_array($config)) {
28
            self::$config = $config;
29
        } else if (is_string($config)) {
30
            self::$config = require $config ?? self::DEFAULT_CONFIG_PATH;
31
        }
32
    }
33
34
    /**
35
     * Get config.
36
     *
37
     * @param string|null $key Key to extract.
38
     *
39
     * @return mixed
40
     */
41
    public static function get(string $key = null)
42
    {
43
        if (empty($key)) {
44
            return self::$config;
45
        }
46
47
        $keys  = explode('.', $key);
48
        $value = self::$config;
49
50
        foreach ($keys as $key) {
51
            if ( ! isset($value[$key])) {
52
                return null;
53
            }
54
55
            $value = $value[$key];
56
        }
57
58
        return $value;
59
    }
60
}
61