ConfigValueGuesser   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 79
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
c 1
b 0
f 0
lcom 1
cbo 2
dl 0
loc 79
ccs 0
cts 33
cp 0
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A supports() 0 4 1
B guess() 0 27 5
A getConfigValues() 0 4 1
1
<?php
2
3
namespace TreeHouse\Model\Config;
4
5
use TreeHouse\Model\Config\Matcher\MatcherInterface;
6
7
class ConfigValueGuesser
8
{
9
    /**
10
     * @var Config
11
     */
12
    protected $config;
13
14
    /**
15
     * @var MatcherInterface
16
     */
17
    protected $matcher;
18
19
    /**
20
     * @param Config           $config
21
     * @param MatcherInterface $matcher
22
     */
23
    public function __construct(Config $config, MatcherInterface $matcher)
24
    {
25
        $this->config  = $config;
26
        $this->matcher = $matcher;
27
    }
28
29
    /**
30
     * @param string $type
31
     *
32
     * @return boolean
33
     */
34
    public function supports($type)
35
    {
36
        return $this->config->hasFieldConfig($type);
37
    }
38
39
    /**
40
     * @param string $field
41
     * @param mixed  $value
42
     *
43
     * @throws \OutOfBoundsException   When given a invalid numeric value
44
     * @throws \BadMethodCallException When field is not part of the config
45
     *
46
     * @return integer|null
47
     */
48
    public function guess($field, $value)
49
    {
50
        if (!$this->supports($field)) {
51
            throw new \BadMethodCallException(sprintf('Config field "%s" is not supported', $field));
52
        }
53
54
        $values = $this->getConfigValues($field);
55
56
        // already matched?
57
        if (is_numeric($value)) {
58
            $value = (int) $value;
59
            if (!array_key_exists($value, $values)) {
60
                throw new \OutOfBoundsException(
61
                    sprintf('Value "%d" for field "%s" already seems a key, but it is not a valid one', $value, $field)
62
                );
63
            }
64
65
            return $value;
66
        }
67
68
        // look for an exact match first
69
        if (false !== $key = array_search(mb_strtolower($value), $values)) {
70
            return $key;
71
        }
72
73
        return $this->matcher->match($field, $value);
74
    }
75
76
    /**
77
     * @param string $type
78
     *
79
     * @return array|null
80
     */
81
    protected function getConfigValues($type)
82
    {
83
        return $this->config->getFieldConfig($type);
84
    }
85
}
86