Passed
Push — master ( 9949af...cba09f )
by Alexander
11:36
created

Parameters::get()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 4
eloc 4
c 2
b 0
f 0
nc 4
nop 2
dl 0
loc 8
rs 10
1
<?php
2
3
namespace App;
4
5
use function array_key_exists;
6
use function strpos;
7
use function explode;
8
9
/**
10
 * Parameters provides a way to get application parameters defined in config/params.php
11
 *
12
 * In order to use in a handler or any other place supporting auto-wired injection:
13
 *
14
 * ```php
15
 * $params = [
16
 *      'admin' => [
17
 *          'email' => '[email protected]'
18
 *      ]
19
 * ];
20
 * ```
21
 *
22
 * ```php
23
 * public function actionIndex(Parameters $parameters)
24
 * {
25
 *     $adminEmail = $parameters->get('admin.email', '[email protected]'); // return [email protected] or [email protected] if search key not exists in parameters
26
 * }
27
 * ```
28
 */
29
class Parameters
30
{
31
    private array $parameters;
32
    private string $glue;
33
34
    public function __construct(array $data, string $glue = '.')
35
    {
36
        $this->parameters = $data;
37
        $this->glue = $glue;
38
    }
39
40
    public function get(string $key, $default = null)
41
    {
42
        if (strpos($key, $this->glue) !== false) {
43
            $keys = explode($this->glue, $key);
44
            return $this->hasNesting($keys) ? $this->getNesting($keys) : $default;
45
        }
46
47
        return $this->has($key) ? $this->parameters[$key] : $default;
48
    }
49
50
    public function has(string $key): bool
51
    {
52
        if (strpos($key, $this->glue) !== false) {
53
            return $this->hasNesting(explode($this->glue, $key));
54
        }
55
56
        return array_key_exists($key, $this->parameters);
57
    }
58
59
    public function getAll(): array
60
    {
61
        return $this->parameters;
62
    }
63
64
    private function hasNesting(array $keys): bool
65
    {
66
        $ref = $this->parameters;
67
        foreach ($keys as $key) {
68
            if (!array_key_exists($key, $ref)) {
69
                return false;
70
            }
71
            $ref = $ref[$key];
72
        }
73
74
        return true;
75
    }
76
77
    private function getNesting(array $keys)
78
    {
79
        $data = $this->parameters;
80
        foreach ($keys as $key) {
81
            if (!array_key_exists($key, $data)) {
82
                return null;
83
            }
84
            $data = $data[$key];
85
        }
86
87
        return $data;
88
    }
89
}
90