Completed
Branch 2.0 (63d421)
by Anton
05:39
created

Environment::normalize()   B

Complexity

Conditions 9
Paths 9

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
nc 9
nop 1
dl 0
loc 22
rs 8.0555
c 0
b 0
f 0
1
<?php
2
/**
3
 * Spiral Framework.
4
 *
5
 * @license   MIT
6
 * @author    Anton Titov (Wolfy-J)
7
 */
8
9
namespace Spiral\Framework;
10
11
final class Environment implements EnvironmentInterface
12
{
13
    /** @var string|null */
14
    private $id = null;
15
16
    /** @var array */
17
    private $values = [];
18
19
    /**
20
     * @param array $values
21
     */
22
    public function __construct(array $values = [])
23
    {
24
        $this->values = $values + $_ENV + $_SERVER;
25
    }
26
27
    /**
28
     * @inheritdoc
29
     */
30
    public function getID(): string
31
    {
32
        if (empty($this->id)) {
33
            $this->id = md5(serialize($this->values));
34
        }
35
36
        return $this->id;
37
    }
38
39
    /**
40
     * @inheritdoc
41
     */
42
    public function set(string $name, $value)
43
    {
44
        $this->values[$name] = $_ENV[$name] = $value;
45
        putenv("$name=$value");
46
47
        $this->id = null;
48
    }
49
50
    /**
51
     * @inheritdoc
52
     */
53
    public function get(string $name, $default = null)
54
    {
55
        if (array_key_exists($name, $this->values)) {
56
            return $this->normalize($this->values[$name]);
57
        }
58
59
        return $default;
60
    }
61
62
    /**
63
     * @param mixed $value
64
     * @return bool|null|string
65
     */
66
    protected function normalize($value)
67
    {
68
        switch (strtolower($value)) {
69
            case 'true':
70
            case '(true)':
71
                return true;
72
73
            case 'false':
74
            case '(false)':
75
                return false;
76
77
            case 'null':
78
            case '(null)':
79
                return null;
80
81
            case 'empty':
82
            case '(empty)':
83
                return '';
84
        }
85
86
        return $value;
87
    }
88
}