InjectConfig   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 57
Duplicated Lines 14.04 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 1
Metric Value
c 3
b 0
f 1
dl 8
loc 57
wmc 7
lcom 1
cbo 2
ccs 19
cts 19
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getValue() 8 8 2
B read() 0 24 5

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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