GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — master (#43)
by Martin
06:34
created

UserAgentApiCom::hydrateBrowser()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 8.8571
cc 5
eloc 5
nc 4
nop 2
crap 5
1
<?php
2
namespace UserAgentParser\Provider\Http;
3
4
use GuzzleHttp\Client;
5
use GuzzleHttp\Psr7\Request;
6
use stdClass;
7
use UserAgentParser\Exception;
8
use UserAgentParser\Model;
9
10
/**
11
 *
12
 * @see https://useragentapi.com/docs
13
 *
14
 */
15
class UserAgentApiCom extends AbstractHttpProvider
16
{
17
    protected $detectionCapabilities = [
18
19
        'browser' => [
20
            'name'    => true,
21
            'version' => true,
22
        ],
23
24
        'renderingEngine' => [
25
            'name'    => true,
26
            'version' => true,
27
        ],
28
29
        'operatingSystem' => [
30
            'name'    => false,
31
            'version' => false,
32
        ],
33
34
        'device' => [
35
            'model'    => false,
36
            'brand'    => false,
37
            'type'     => true,
38
            'isMobile' => false,
39
            'isTouch'  => false,
40
        ],
41
42
        'bot' => [
43
            'isBot' => true,
44
            'name'  => true,
45
            'type'  => false,
46
        ],
47
    ];
48
49
    private static $uri = 'https://useragentapi.com/api/v3/json';
50
51
    private $apiKey;
52
53 15
    public function __construct(Client $client, $apiKey)
54
    {
55 15
        parent::__construct($client);
56
57 15
        $this->apiKey = $apiKey;
58 15
    }
59
60 2
    public function getName()
61
    {
62 2
        return 'UserAgentApiCom';
63
    }
64
65 1
    public function getComposerPackageName()
66
    {
67 1
        return;
68
    }
69
70 1
    public function getVersion()
71
    {
72 1
        return;
73
    }
74
75
    /**
76
     *
77
     * @param  string                     $userAgent
78
     * @param  array                      $headers
79
     * @return stdClass
80
     * @throws Exception\RequestException
81
     */
82 11
    protected function getResult($userAgent, array $headers)
0 ignored issues
show
Unused Code introduced by
The parameter $headers is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
83
    {
84
        /*
85
         * an empty UserAgent makes no sense
86
         */
87 11
        if ($userAgent == '') {
88 1
            throw new Exception\NoResultFoundException('No result found for user agent: ' . $userAgent);
89
        }
90
91 10
        $parameters = '/' . $this->apiKey;
92 10
        $parameters .= '/' . urlencode($userAgent);
93
94 10
        $uri = self::$uri . $parameters;
95
96 10
        $request = new Request('GET', $uri);
97
98
        try {
99 10
            $response = $this->getResponse($request);
100 10
        } catch (Exception\RequestException $ex) {
101
            /* @var $prevEx \GuzzleHttp\Exception\ClientException */
102 3
            $prevEx = $ex->getPrevious();
103
104 3
            if ($prevEx->hasResponse() === true && $prevEx->getResponse()->getStatusCode() === 400) {
105 2
                $content = $prevEx->getResponse()
106 2
                    ->getBody()
107 2
                    ->getContents();
108 2
                $content = json_decode($content);
109
110
                /*
111
                 * Error
112
                 */
113 2
                if (isset($content->error->code) && $content->error->code == 'key_invalid') {
114 1
                    throw new Exception\InvalidCredentialsException('Your API key "' . $this->apiKey . '" is not valid for ' . $this->getName(), null, $ex);
115
                }
116
117 1
                if (isset($content->error->code) && $content->error->code == 'useragent_invalid') {
118 1
                    throw new Exception\RequestException('User agent is invalid ' . $userAgent);
119
                }
120
            }
121
122 1
            throw $ex;
123
        }
124
125
        /*
126
         * no json returned?
127
         */
128 7
        $contentType = $response->getHeader('Content-Type');
129 7 View Code Duplication
        if (! isset($contentType[0]) || $contentType[0] != 'application/json') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
130 1
            throw new Exception\RequestException('Could not get valid "application/json" response from "' . $request->getUri() . '". Response is "' . $response->getBody()->getContents() . '"');
131
        }
132
133 6
        $content = json_decode($response->getBody()->getContents());
134
135
        /*
136
         * No result
137
         */
138 6
        if (isset($content->error->code) && $content->error->code == 'useragent_not_found') {
139 1
            throw new Exception\NoResultFoundException('No result found for user agent: ' . $userAgent);
140
        }
141
142
        /*
143
         * Missing data?
144
         */
145 5 View Code Duplication
        if (! $content instanceof stdClass || ! isset($content->data)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
146 1
            throw new Exception\RequestException('Could not get valid response from "' . $request->getUri() . '". Data is missing "' . $response->getBody()->getContents() . '"');
147
        }
148
149 4
        return $content->data;
150
    }
151
152
    /**
153
     *
154
     * @param  stdClass $resultRaw
155
     * @return boolean
156
     */
157 4
    private function isBot(stdClass $resultRaw)
158
    {
159 4
        if (isset($resultRaw->platform_type) && $resultRaw->platform_type === 'Bot') {
160 1
            return true;
161
        }
162
163 3
        return false;
164
    }
165
166
    /**
167
     *
168
     * @param Model\Bot $bot
169
     * @param stdClass  $resultRaw
170
     */
171 1 View Code Duplication
    private function hydrateBot(Model\Bot $bot, stdClass $resultRaw)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
172
    {
173 1
        $bot->setIsBot(true);
174
175 1
        if (isset($resultRaw->platform_name) && $this->isRealResult($resultRaw->platform_name) === true) {
176 1
            $bot->setName($resultRaw->platform_name);
177
        }
178 1
    }
179
180
    /**
181
     *
182
     * @param Model\Browser $browser
183
     * @param stdClass      $resultRaw
184
     */
185 3
    private function hydrateBrowser(Model\Browser $browser, stdClass $resultRaw)
186
    {
187 3
        if (isset($resultRaw->browser_name) && $this->isRealResult($resultRaw->browser_name) === true) {
188 1
            $browser->setName($resultRaw->browser_name);
189
        }
190
191 3
        if (isset($resultRaw->browser_version) && $this->isRealResult($resultRaw->browser_version) === true) {
192 1
            $browser->getVersion()->setComplete($resultRaw->browser_version);
193
        }
194 3
    }
195
196
    /**
197
     *
198
     * @param Model\RenderingEngine $engine
199
     * @param stdClass              $resultRaw
200
     */
201 3
    private function hydrateRenderingEngine(Model\RenderingEngine $engine, stdClass $resultRaw)
202
    {
203 3
        if (isset($resultRaw->engine_name) && $this->isRealResult($resultRaw->engine_name) === true) {
204 1
            $engine->setName($resultRaw->engine_name);
205
        }
206
207 3
        if (isset($resultRaw->engine_version) && $this->isRealResult($resultRaw->engine_version) === true) {
208 1
            $engine->getVersion()->setComplete($resultRaw->engine_version);
209
        }
210 3
    }
211
212
    /**
213
     *
214
     * @param Model\UserAgent $device
215
     * @param stdClass        $resultRaw
216
     */
217 3
    private function hydrateDevice(Model\Device $device, stdClass $resultRaw)
218
    {
219 3
        if (isset($resultRaw->platform_type) && $this->isRealResult($resultRaw->platform_type) === true) {
220 1
            $device->setType($resultRaw->platform_type);
221
        }
222 3
    }
223
224 11
    public function parse($userAgent, array $headers = [])
225
    {
226 11
        $resultRaw = $this->getResult($userAgent, $headers);
227
228
        /*
229
         * Hydrate the model
230
         */
231 4
        $result = new Model\UserAgent();
232 4
        $result->setProviderResultRaw($resultRaw);
233
234
        /*
235
         * Bot detection
236
         */
237 4
        if ($this->isBot($resultRaw) === true) {
238 1
            $this->hydrateBot($result->getBot(), $resultRaw);
239
240 1
            return $result;
241
        }
242
243
        /*
244
         * hydrate the result
245
         */
246 3
        $this->hydrateBrowser($result->getBrowser(), $resultRaw);
247 3
        $this->hydrateRenderingEngine($result->getRenderingEngine(), $resultRaw);
248 3
        $this->hydrateDevice($result->getDevice(), $resultRaw);
249
250 3
        return $result;
251
    }
252
}
253