Completed
Push — master ( 3888fe...7b95f2 )
by Carlos
02:54
created

Config::jsonSerialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Overtrue\Socialite;
4
5
use ArrayAccess;
6
use InvalidArgumentException;
7
8
class Config implements ArrayAccess, \JsonSerializable
9
{
10
    /**
11
     * @var array
12
     */
13
    protected $config;
14
15
    /**
16
     * @param array $config
17
     */
18
    public function __construct(array $config)
19
    {
20
        $this->config = $config;
21
    }
22
23
    /**
24
     * @param string $key
25
     * @param mixed  $default
26
     *
27
     * @return mixed
28
     */
29
    public function get(string $key, $default = null)
30
    {
31
        $config = $this->config;
32
33
        if (is_null($key)) {
34
            return $config;
35
        }
36
37
        if (isset($config[$key])) {
38
            return $config[$key];
39
        }
40
41
        foreach (explode('.', $key) as $segment) {
42
            if (!is_array($config) || !array_key_exists($segment, $config)) {
43
                return $default;
44
            }
45
            $config = $config[$segment];
46
        }
47
48
        return $config;
49
    }
50
51
    /**
52
     * @param string $key
53
     * @param mixed  $value
54
     *
55
     * @return array
56
     */
57
    public function set(string $key, $value)
58
    {
59
        if (is_null($key)) {
60
            throw new InvalidArgumentException('Invalid config key.');
61
        }
62
63
        $keys = explode('.', $key);
64
        $config = &$this->config;
65
66
        while (count($keys) > 1) {
67
            $key = array_shift($keys);
68
            if (!isset($config[$key]) || !is_array($config[$key])) {
69
                $config[$key] = [];
70
            }
71
            $config = &$config[$key];
72
        }
73
74
        $config[array_shift($keys)] = $value;
75
76
        return $config;
77
    }
78
79
    /**
80
     * @param string $key
81
     *
82
     * @return bool
83
     */
84
    public function has(string $key): bool
85
    {
86
        return (bool) $this->get($key);
87
    }
88
89
    public function offsetExists($offset)
90
    {
91
        return array_key_exists($offset, $this->config);
92
    }
93
94
    public function offsetGet($offset)
95
    {
96
        return $this->get($offset);
97
    }
98
99
    public function offsetSet($offset, $value)
100
    {
101
        $this->set($offset, $value);
102
    }
103
104
    public function offsetUnset($offset)
105
    {
106
        $this->set($offset, null);
107
    }
108
109
    public function jsonSerialize()
110
    {
111
        return $this->config;
112
    }
113
114
    public function __toString()
115
    {
116
        return \json_encode($this, \JSON_UNESCAPED_UNICODE);
117
    }
118
}
119