Client::getParser()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 13
ccs 8
cts 8
cp 1
rs 9.4285
cc 3
eloc 6
nc 3
nop 1
crap 3
1
<?php
2
namespace Thunder\SimilarWebApi;
3
4
use Thunder\SimilarWebApi\Parser\JsonParser;
5
use Thunder\SimilarWebApi\Parser\XmlParser;
6
7
/**
8
 * @author Tomasz Kowalczyk <[email protected]>
9
 */
10
class Client
11
    {
12
    private $token;
13
    private $format;
14
    private $cache;
15
16
    /**
17
     * Yep, it's a constructor.
18
     *
19
     * @param string $token User key (API token)
20
     * @param string $format Raw response text format (JSON or XML)
21
     *
22
     * @throws \InvalidArgumentException When unsupported format is given
23
     */
24 38
    public function __construct($token, $format)
25 1
        {
26 38
        $format = strtoupper($format);
27 38
        $allowedFormats = array('XML', 'JSON');
28 38
        if(!in_array($format, $allowedFormats))
29 38
            {
30 1
            $message = 'Invalid response format: %s, allowed: %s!';
31 1
            throw new \InvalidArgumentException(sprintf($message, $format, implode(', ', $allowedFormats)));
32
            }
33
34 37
        $this->token = $token;
35 37
        $this->format = $format;
36 37
        $this->clearCache();
37 37
        }
38
39 37
    public function clearCache()
40
        {
41 37
        $this->cache = array();
42 37
        }
43
44
    /**
45
     * Execute given API call on specified domain
46
     *
47
     * @param AbstractRequest $request Call name as in URL path, eg. v1/traffic
48
     *
49
     * @return AbstractResponse Value object with interface to fetch results
50
     */
51 36
    public function getResponse(AbstractRequest $request)
52
        {
53 36
        $url = $request->getCallUrl($this->format, $this->token);
54 36
        if(isset($this->cache['url'][$url]))
55 36
            {
56 32
            return $this->cache['url'][$url];
57
            }
58
59 36
        $parser = $this->getParser($request);
60 35
        $content = $this->executeCall($url);
61 35
        $response = $parser->getResponse($content);
62 32
        $this->cache['url'][$url] = $response;
63
64 32
        return $response;
65
        }
66
67
    /**
68
     * Returns endpoint (API call handler) for given call name
69
     *
70
     * @param AbstractRequest $request Request object
71
     *
72
     * @return ParserInterface
73
     *
74
     * @throws \InvalidArgumentException When given endpoint does not exist
75
     */
76 36
    private function getParser(AbstractRequest $request)
77
        {
78 36
        if('JSON' == $this->format)
79 36
            {
80 34
            return new JsonParser($request->getName(), $request->getMapping());
81
            }
82 34
        else if('XML' == $this->format)
83 34
            {
84 33
            return new XmlParser($request->getName(), $request->getMapping());
85
            }
86
87 1
        throw new \RuntimeException(sprintf('Failed to find parser for format %s!', $this->format));
88
        }
89
90
    /**
91
     * Utility function to execute API call and get raw response text
92
     *
93
     * @codeCoverageIgnore
94
     *
95
     * @param string $url Call name as in URL path, eg. v1/traffic
96
     *
97
     * @return string Response text and status code
98
     *
99
     * @throws \RuntimeException If request failed (code outside 2xx range)
100
     */
101
    public function executeCall($url)
102
        {
103
        $curl = curl_init($url);
104
        curl_setopt_array($curl, array(
105
            CURLOPT_RETURNTRANSFER => 1,
106
            CURLOPT_FOLLOWLOCATION => 1,
107
            ));
108
        $response = curl_exec($curl);
109
        $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
110
        curl_close($curl);
111
112
        if($code < 200 || $code >= 400)
113
            {
114
            $message = '%s request %s failed with code %s!';
115
            $url = str_replace($this->token, 'SECRET_TOKEN_IS_SECRET', $url);
116
            throw new \RuntimeException(sprintf($message, $this->format, $url, $code), $code);
117
            }
118
119
        return $response;
120
        }
121
    }
122