Passed
Push — master ( 8ac202...00ebcb )
by Hong
01:41
created

Config::getTree()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 1
c 1
b 0
f 1
nc 1
nop 0
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\Tree\TreeAwareTrait;
17
use Phoole\Base\Tree\TreeAwareInterface;
18
use Phoole\Base\Reference\ReferenceTrait;
19
use Phoole\Base\Reference\ReferenceInterface;
20
21
/**
22
 * Config
23
 *
24
 * @package Phoole\Config
25
 */
26
class Config implements ConfigInterface, ReferenceInterface, TreeAwareInterface
27
{
28
    use ReferenceTrait;
29
    use TreeAwareTrait;
30
31
    /**
32
     * Constructor
33
     *
34
     * ```php
35
     * # load from files
36
     * $conf = new Config('/my/app/conf', 'product/host1');
37
     *
38
     * # load from array
39
     * $conf = new Config(['db.user'=> 'root']);
40
     * ```
41
     *
42
     * @param  string|array $dirOrConfData
43
     * @param  string       $environment
44
     */
45
    public function __construct(
46
        $dirOrConfData,
47
        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
            if (0 === strpos($id, 'ENV.')) {
67
                return getenv(substr($id, 4));
68
            } else {
69
                return $this->tree->get($id);
70
            }
71
        } catch (\Exception $e) {
72
            throw new \RuntimeException($e->getMessage());
73
        }
74
    }
75
76
    /**
77
     * {@inheritDoc}
78
     */
79
    public function has(string $id): bool
80
    {
81
        if (0 === strpos($id, 'ENV.')) {
82
            return FALSE !== getenv(substr($id, 4));
83
        } else {
84
            return $this->tree->has($id);
85
        }
86
    }
87
88
    /**
89
     * {@inheritDoc}
90
     */
91
    protected function getReference(string $name)
92
    {
93
        return $this->get($name);
94
    }
95
}