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.

DeviceAtlasCom::hydrateDevice()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
c 0
b 0
f 0
ccs 4
cts 4
cp 1
rs 9.4285
cc 2
eloc 3
nc 2
nop 2
crap 2
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
 * Abstraction of deviceatlas.com
12
 *
13
 * @author Martin Keckeis <[email protected]>
14
 * @license MIT
15
 * @see https://deviceatlas.com/resources/enterprise-api-documentation
16
 */
17
class DeviceAtlasCom extends AbstractHttpProvider
18
{
19
    /**
20
     * Name of the provider
21
     *
22
     * @var string
23
     */
24
    protected $name = 'DeviceAtlasCom';
25
26
    /**
27
     * Homepage of the provider
28
     *
29
     * @var string
30
     */
31
    protected $homepage = 'https://deviceatlas.com/';
32
33
    protected $detectionCapabilities = [
34
35
        'browser' => [
36
            'name'    => true,
37
            'version' => true,
38
        ],
39
40
        'renderingEngine' => [
41
            'name'    => true,
42
            'version' => false,
43
        ],
44
45
        'operatingSystem' => [
46
            'name'    => true,
47
            'version' => true,
48
        ],
49
50
        'device' => [
51
            'model'    => false,
52
            'brand'    => false,
53
            'type'     => true,
54
            'isMobile' => false,
55
            'isTouch'  => false,
56
        ],
57
58
        'bot' => [
59
            'isBot' => false,
60
            'name'  => false,
61
            'type'  => false,
62
        ],
63
    ];
64
65
    private static $uri = 'http://region0.deviceatlascloud.com/v1/detect/properties';
66
67
    private $apiKey;
68
69 18
    public function __construct(Client $client, $apiKey)
70
    {
71 18
        parent::__construct($client);
72
73 18
        $this->apiKey = $apiKey;
74 18
    }
75
76 11
    protected function getResult($userAgent, array $headers)
77
    {
78
        /*
79
         * an empty UserAgent makes no sense
80
         */
81 11
        if ($userAgent == '') {
82 1
            throw new Exception\NoResultFoundException('No result found for user agent: ' . $userAgent);
83
        }
84
85 10
        $parameters = '?licencekey=' . rawurlencode($this->apiKey);
86 10
        $parameters .= '&useragent=' . rawurlencode($userAgent);
87
88 10
        $uri = self::$uri . $parameters;
89
90
        // key to lower
91 10
        $headers = array_change_key_case($headers);
92
93 10
        $newHeaders = [];
94 10
        foreach ($headers as $key => $value) {
95 1
            $newHeaders['X-DA-' . $key] = $value;
96
        }
97
98 10
        $newHeaders['User-Agent'] = 'ThaDafinser/UserAgentParser:v1.4';
99
100 10
        $request = new Request('GET', $uri, $newHeaders);
101
102
        try {
103 10
            $response = $this->getResponse($request);
104 2
        } catch (Exception\RequestException $ex) {
105
            /* @var $prevEx \GuzzleHttp\Exception\ClientException */
106 2
            $prevEx = $ex->getPrevious();
107
108 2
            if ($prevEx->hasResponse() === true && $prevEx->getResponse()->getStatusCode() === 403) {
109 1
                throw new Exception\InvalidCredentialsException('Your API key "' . $this->apiKey . '" is not valid for ' . $this->getName(), null, $ex);
110
            }
111
112 1
            throw $ex;
113
        }
114
115
        /*
116
         * no json returned?
117
         */
118 8
        $contentType = $response->getHeader('Content-Type');
119 8
        if (! isset($contentType[0]) || $contentType[0] != 'application/json; charset=UTF-8') {
120 1
            throw new Exception\RequestException('Could not get valid "application/json" response from "' . $request->getUri() . '". Response is "' . $response->getBody()->getContents() . '"');
121
        }
122
123 7
        $content = json_decode($response->getBody()->getContents());
124
125 7
        if (! $content instanceof stdClass || ! isset($content->properties)) {
126 1
            throw new Exception\RequestException('Could not get valid response from "' . $request->getUri() . '". Response is "' . $response->getBody()->getContents() . '"');
127
        }
128
129
        /*
130
         * No result found?
131
         */
132 6
        if (! $content->properties instanceof stdClass || count((array) $content->properties) === 0) {
133 1
            throw new Exception\NoResultFoundException('No result found for user agent: ' . $userAgent);
134
        }
135
136 5
        return $content->properties;
137
    }
138
139
    /**
140
     *
141
     * @param Model\Browser $browser
142
     * @param stdClass      $resultRaw
143
     */
144 5
    private function hydrateBrowser(Model\Browser $browser, stdClass $resultRaw)
145
    {
146 5
        if (isset($resultRaw->browserName)) {
147 2
            $browser->setName($this->getRealResult($resultRaw->browserName, 'browser', 'name'));
148
        }
149
150 5
        if (isset($resultRaw->browserVersion)) {
151 2
            $browser->getVersion()->setComplete($this->getRealResult($resultRaw->browserVersion, 'browser', 'version'));
152
        }
153 5
    }
154
155
    /**
156
     *
157
     * @param Model\RenderingEngine $engine
158
     * @param stdClass              $resultRaw
159
     */
160 5
    private function hydrateRenderingEngine(Model\RenderingEngine $engine, stdClass $resultRaw)
161
    {
162 5
        if (isset($resultRaw->browserRenderingEngine)) {
163 1
            $engine->setName($this->getRealResult($resultRaw->browserRenderingEngine));
164
        }
165 5
    }
166
167
    /**
168
     *
169
     * @param Model\OperatingSystem $os
170
     * @param stdClass              $resultRaw
171
     */
172 5
    private function hydrateOperatingSystem(Model\OperatingSystem $os, stdClass $resultRaw)
173
    {
174 5
        if (isset($resultRaw->osName)) {
175 1
            $os->setName($this->getRealResult($resultRaw->osName));
176
        }
177
178 5
        if (isset($resultRaw->osVersion)) {
179 1
            $os->getVersion()->setComplete($this->getRealResult($resultRaw->osVersion));
180
        }
181 5
    }
182
183
    /**
184
     *
185
     * @param Model\UserAgent $device
186
     * @param stdClass        $resultRaw
187
     */
188 5
    private function hydrateDevice(Model\Device $device, stdClass $resultRaw)
189
    {
190 5
        if (isset($resultRaw->primaryHardwareType)) {
191 1
            $device->setType($this->getRealResult($resultRaw->primaryHardwareType));
192
        }
193 5
    }
194
195 11
    public function parse($userAgent, array $headers = [])
196
    {
197 11
        $resultRaw = $this->getResult($userAgent, $headers);
198
199
        /*
200
         * Hydrate the model
201
         */
202 5
        $result = new Model\UserAgent($this->getName(), $this->getVersion());
203 5
        $result->setProviderResultRaw($resultRaw);
204
205
        /*
206
         * hydrate the result
207
         */
208 5
        $this->hydrateBrowser($result->getBrowser(), $resultRaw);
209 5
        $this->hydrateRenderingEngine($result->getRenderingEngine(), $resultRaw);
210 5
        $this->hydrateOperatingSystem($result->getOperatingSystem(), $resultRaw);
211 5
        $this->hydrateDevice($result->getDevice(), $resultRaw);
212
213 5
        return $result;
214
    }
215
}
216