ParamResolver::resolve()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
3
namespace Devhelp\Piwik\Api\Param;
4
5
class ParamResolver
6
{
7
8
    private $defaultParams = array();
9
10
    private $mandatoryParams = array();
11
12
    /**
13
     * sets default parameters that will be returned on resolve unless overwritten by mandatory or runtime params
14
     *
15
     * @param array $params
16
     */
17
    public function setDefaults(array $params)
18
    {
19
        $this->defaultParams = $params;
20
    }
21
22
    /**
23
     * sets parameters that won't be overwritten by default or runtime parameters
24
     * and will be returned on resolve
25
     *
26
     * @param array $params
27
     */
28
    public function setMandatory(array $params)
29
    {
30
        $this->mandatoryParams = $params;
31
    }
32
33
    /**
34
     * resolves $params value by merging and getting end values from each array elements
35
     *
36
     * @param array $params
37
     * @return array
38
     */
39
    public function resolve(array $params)
40
    {
41
        $merged = $this->merge($params);
42
        $resolved = $this->read($merged);
43
44
        return $resolved;
45
    }
46
47
    private function merge(array $params)
48
    {
49
        $merged = array_merge($this->defaultParams, $params, $this->mandatoryParams);
50
51
        return $merged;
52
    }
53
54
    private function read(array $params)
55
    {
56
        $resolved = array();
57
58
        foreach ($params as $key => $value) {
59
            if ($value instanceof Param) {
60
                $value = $value->value();
61
            } elseif ($value instanceof \Closure) {
62
                $value = $value();
63
            }
64
65
            $param = array($key => $value);
66
67
            $resolved = array_merge($resolved, $param);
68
        }
69
70
        return $resolved;
71
    }
72
}
73