|
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
|
|
|
|