InjectConfig::getValue()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 8
Ratio 100 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 8
loc 8
ccs 4
cts 4
cp 1
rs 9.4285
cc 2
eloc 5
nc 2
nop 1
crap 2
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