Method::initResolver()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 0
1
<?php
2
3
namespace Devhelp\Piwik\Api\Method;
4
5
use Devhelp\Piwik\Api\Client\PiwikClient;
6
use Devhelp\Piwik\Api\Param\ParamResolver;
7
use Psr\Http\Message\ResponseInterface;
8
9
/**
10
 * Provides encapsulated method call to piwik api
11
 */
12
class Method
13
{
14
15
    /**
16
     * @var PiwikClient
17
     */
18
    private $piwikClient;
19
20
    /**
21
     * @var string piwik api endpoint
22
     */
23
    private $url;
24
25
    /**
26
     * @var string piwik method name (equals to 'method' parameter in reporting api)
27
     */
28
    private $name;
29
30
    /**
31
     * @var string return format of piwik api response (equals to 'format' parameter in reporting api)
32
     */
33
    private $format;
34
35
    /**
36
     * @var ParamResolver
37
     */
38
    private $resolver;
39
40
    /**
41
     * @var array
42
     */
43
    private $defaultParams = array();
44
45
    public function __construct(PiwikClient $piwikClient, $url, $name, $format = 'json')
46
    {
47
        $this->piwikClient = $piwikClient;
48
        $this->url = $url;
49
        $this->name = $name;
50
        $this->format = $format;
51
    }
52
53
    public function name()
54
    {
55
        return $this->name;
56
    }
57
58
    public function url()
59
    {
60
        return $this->url;
61
    }
62
63
    public function setDefaultParams(array $params)
64
    {
65
        $this->defaultParams = $params;
66
    }
67
68
    public function getDefaultParams()
69
    {
70
        return $this->defaultParams;
71
    }
72
73
    /**
74
     * calls piwik api
75
     *
76
     * @param array $params
77
     * @return ResponseInterface
78
     */
79
    public function call(array $params)
80
    {
81
        $this->initResolver();
82
83
        /**
84
         * makes sure that 'format' is passed and that 'API' and 'method'
85
         * parameters are not overwritten by defaults nor by call parameters
86
         */
87
        $defaults = array_merge(array('format' => $this->format), $this->defaultParams);
88
        $this->resolver->setDefaults($defaults);
89
        $this->resolver->setMandatory(array(
90
            'module' => 'API',
91
            'method' => $this->name()
92
        ));
93
94
        return $this->piwikClient->call($this->url(), $this->resolver->resolve($params));
95
    }
96
97
    private function initResolver()
98
    {
99
        if (!$this->resolver instanceof ParamResolver) {
100
            $this->resolver = new ParamResolver();
101
        }
102
    }
103
}
104