Completed
Branch 2.0 (ba2d77)
by Anton
01:50
created

Environment::normalize()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 1
dl 0
loc 13
rs 9.8333
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
    const VALUE_MAP = [
14
        'true'    => true,
15
        '(true)'  => true,
16
        'false'   => false,
17
        '(false)' => false,
18
        'null'    => null,
19
        '(null)'  => null,
20
        'empty'   => ''
21
    ];
22
23
    /** @var string|null */
24
    private $id = null;
25
26
    /** @var array */
27
    private $values = [];
28
29
    /**
30
     * @param array $values
31
     */
32
    public function __construct(array $values = [])
33
    {
34
        $this->values = $values + $_ENV + $_SERVER;
35
    }
36
37
    /**
38
     * @inheritdoc
39
     */
40
    public function getID(): string
41
    {
42
        if (empty($this->id)) {
43
            $this->id = md5(serialize($this->values));
44
        }
45
46
        return $this->id;
47
    }
48
49
    /**
50
     * @inheritdoc
51
     */
52
    public function set(string $name, $value)
53
    {
54
        $this->values[$name] = $_ENV[$name] = $value;
55
        putenv("$name=$value");
56
57
        $this->id = null;
58
    }
59
60
    /**
61
     * @inheritdoc
62
     */
63
    public function get(string $name, $default = null)
64
    {
65
        if (isset($this->values[$name])) {
66
            return $this->normalize($this->values[$name]);
67
        }
68
69
        return $default;
70
    }
71
72
    /**
73
     * @param mixed $value
74
     * @return bool|null|string
75
     */
76
    protected function normalize($value): ?string
77
    {
78
        if (!is_string($value)) {
79
            return $value;
80
        }
81
82
        $alias = strtolower($value);
83
        if (isset(self::VALUE_MAP[$alias])) {
84
            return self::VALUE_MAP[$alias];
85
        }
86
87
        return $value;
88
    }
89
}