Passed
Push — master ( 5c3284...d8a693 )
by Hong
01:52
created

Config::getReference()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
/**
4
 * Phoole (PHP7.2+)
5
 *
6
 * @category  Library
7
 * @package   Phoole\Config
8
 * @copyright Copyright (c) 2019 Hong Zhang
9
 */
10
declare(strict_types=1);
11
12
namespace Phoole\Config;
13
14
use Phoole\Base\Tree\Tree;
15
use Phoole\Config\Util\Loader;
16
use Phoole\Base\Reference\ReferenceTrait;
17
use Phoole\Base\Reference\ReferenceInterface;
18
19
/**
20
 * Config
21
 *
22
 * @package Phoole\Config
23
 */
24
class Config implements ConfigInterface, ReferenceInterface
25
{
26
    use ReferenceTrait;
27
28
    /**
29
     * @var    \Phoole\Base\Tree\Tree
30
     */
31
    protected $tree;
32
33
    /**
34
     * Constructor
35
     *
36
     * ```php
37
     * # load from files
38
     * $conf = new Config('/my/app/conf', 'product/host1');
39
     *
40
     * # load from array
41
     * $conf = new Config(['db.user'=> 'root']);
42
     * ```
43
     *
44
     * @param  string|array $dirOrConfData
45
     * @param  string $environment
46
     */
47
    public function __construct($dirOrConfData, string $environment = '')
48
    {
49
        if (is_string($dirOrConfData)) {
50
            $this->tree = (new Loader($dirOrConfData, $environment))->load()->getTree();
51
        } else {
52
            $this->tree = new Tree($dirOrConfData);
53
        }
54
55
        // do dereferencing
56
        $conf = &$this->tree->get('');
57
        $this->deReference($conf);
58
    }
59
60
    /**
61
     * {@inheritDoc}
62
     */
63
    public function get(string $id)
64
    {
65
        try {
66
            return $this->tree->get($id);
67
        } catch (\Exception $e) {
68
            throw new \RuntimeException($e->getMessage());
69
        }
70
    }
71
72
    /**
73
     * {@inheritDoc}
74
     */
75
    public function has(string $id): bool
76
    {
77
        return $this->tree->has($id);
78
    }
79
80
    /**
81
     * {@inheritDoc}
82
     */
83
    public function with(string $id, $value): ConfigInterface
84
    {
85
        $new = clone $this;
86
        $new->tree->add($id, $value);
87
        return $new;
88
    }
89
90
    /**
91
     * Get the tree object
92
     * @return Tree
93
     */
94
    public function getTree(): Tree
95
    {
96
        return $this->tree;
97
    }
98
99
    /**
100
     * {@inheritDoc}
101
     */
102
    protected function getReference(string $name)
103
    {
104
        return $this->get($name);
105
    }
106
107
    public function __clone()
108
    {
109
        $this->tree = clone $this->tree;
110
    }
111
}
112