|
1
|
|
|
<?php |
|
2
|
|
|
namespace mxdiModule\Annotation; |
|
3
|
|
|
|
|
4
|
|
|
use Zend\ServiceManager\ServiceLocatorInterface; |
|
5
|
|
|
use mxdiModule\Exception\CannotGetValue; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* @Annotation |
|
9
|
|
|
* @Target({"PROPERTY", "ANNOTATION", "METHOD"}) |
|
10
|
|
|
*/ |
|
11
|
|
|
final class InjectConfig implements AnnotationInterface |
|
12
|
|
|
{ |
|
13
|
|
|
/** @var string */ |
|
14
|
|
|
public $value; |
|
15
|
|
|
|
|
16
|
|
|
/** @var string */ |
|
17
|
|
|
public $splitter = '-!splitter-'; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* Get the value. |
|
21
|
|
|
* |
|
22
|
|
|
* @param ServiceLocatorInterface $sm |
|
23
|
|
|
* @return mixed |
|
24
|
|
|
* |
|
25
|
|
|
* @throws CannotGetValue |
|
26
|
|
|
*/ |
|
27
|
9 |
View Code Duplication |
public function getValue(ServiceLocatorInterface $sm) |
|
28
|
|
|
{ |
|
29
|
|
|
try { |
|
30
|
9 |
|
return $this->read($sm->get('config'), $this->value); |
|
31
|
3 |
|
} catch (\InvalidArgumentException $e) { |
|
32
|
3 |
|
throw CannotGetValue::of($this->value, $e); |
|
33
|
|
|
} |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* Convert dotted notation to config value. |
|
38
|
|
|
* |
|
39
|
|
|
* @param array $config |
|
40
|
|
|
* @param string $configKey |
|
41
|
|
|
* @return mixed |
|
42
|
|
|
*/ |
|
43
|
9 |
|
protected function read(array $config, $configKey) |
|
44
|
|
|
{ |
|
45
|
9 |
|
if (array_key_exists($configKey, $config)) { |
|
46
|
|
|
// value found |
|
47
|
6 |
|
return $config[$configKey]; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
8 |
|
$splitter = $this->splitter; |
|
51
|
|
|
$keys = array_map(function ($item) use ($splitter) { |
|
52
|
8 |
|
return str_replace($splitter, '.', $item); |
|
53
|
8 |
|
}, explode('.', str_replace('\.', $splitter, $configKey))); |
|
54
|
|
|
|
|
55
|
8 |
|
foreach ($keys as $key) { |
|
56
|
8 |
|
if (isset($config[$key]) && is_array($config[$key])) { |
|
57
|
7 |
|
array_shift($keys); |
|
58
|
7 |
|
$input = implode('.', array_map(function ($item) { |
|
59
|
7 |
|
return str_replace('.', '\.', $item); |
|
60
|
7 |
|
}, $keys)); |
|
61
|
7 |
|
return $this->read($config[$key], $input); |
|
62
|
|
|
} |
|
63
|
3 |
|
} |
|
64
|
|
|
|
|
65
|
3 |
|
throw new \InvalidArgumentException('Key not found'); |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|