Passed
Push — master ( 3eb4db...99d5ff )
by Kirill
03:12
created

Environment::get()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 7
rs 10
cc 2
nc 2
nop 2
1
<?php
2
3
/**
4
 * Spiral Framework.
5
 *
6
 * @license   MIT
7
 * @author    Anton Titov (Wolfy-J)
8
 */
9
10
declare(strict_types=1);
11
12
namespace Spiral\Boot;
13
14
final class Environment implements EnvironmentInterface
15
{
16
    private const VALUE_MAP = [
17
        'true'    => true,
18
        '(true)'  => true,
19
        'false'   => false,
20
        '(false)' => false,
21
        'null'    => null,
22
        '(null)'  => null,
23
        'empty'   => ''
24
    ];
25
26
    /** @var string|null */
27
    private $id = null;
28
29
    /** @var array */
30
    private $values = [];
31
32
    /**
33
     * @param array $values
34
     */
35
    public function __construct(array $values = [])
36
    {
37
        $this->values = $values + $_ENV + $_SERVER;
38
    }
39
40
    /**
41
     * @inheritdoc
42
     */
43
    public function getID(): string
44
    {
45
        if (empty($this->id)) {
46
            $this->id = md5(serialize($this->values));
47
        }
48
49
        return $this->id;
50
    }
51
52
    /**
53
     * @inheritdoc
54
     */
55
    public function set(string $name, $value): void
56
    {
57
        $this->values[$name] = $_ENV[$name] = $value;
58
        putenv("$name=$value");
59
60
        $this->id = null;
61
    }
62
63
    /**
64
     * @inheritdoc
65
     */
66
    public function get(string $name, $default = null)
67
    {
68
        if (isset($this->values[$name])) {
69
            return $this->normalize($this->values[$name]);
70
        }
71
72
        return $default;
73
    }
74
75
    /**
76
     * Get all environment values.
77
     *
78
     * @return array
79
     */
80
    public function getAll(): array
81
    {
82
        $result = [];
83
84
        foreach ($this->values as $key => $value) {
85
            $result[$key] = $this->normalize($value);
86
        }
87
88
        return $result;
89
    }
90
91
    /**
92
     * @param mixed $value
93
     * @return mixed
94
     */
95
    protected function normalize($value)
96
    {
97
        if (!is_string($value)) {
98
            return $value;
99
        }
100
101
        $alias = strtolower($value);
102
        if (isset(self::VALUE_MAP[$alias])) {
103
            return self::VALUE_MAP[$alias];
104
        }
105
106
        return $value;
107
    }
108
}
109