Response   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
wmc 12
eloc 29
c 1
b 1
f 0
dl 0
loc 67
rs 10

8 Methods

Rating   Name   Duplication   Size   Complexity  
A checkValidJson() 0 4 2
A checkRateLimit() 0 11 3
A getBody() 0 3 1
A handleResponse() 0 5 1
A getHeaders() 0 3 1
A __construct() 0 7 1
A checkForbidden() 0 5 2
A getHttpCode() 0 3 1
1
<?php
2
namespace exussum12\TripAdvisor;
3
4
use exussum12\TripAdvisor\Exceptions\InvalidCredentials;
5
use exussum12\TripAdvisor\Exceptions\RateLimit;
6
use exussum12\TripAdvisor\Exceptions\UnknownError;
7
8
class Response
9
{
10
    private $body;
11
    private $headers;
12
    private $httpCode;
13
    private $bodyJsonStatus;
14
15
    const FORBIDDEN = 403;
16
    const RATE_LIMIT = 429;
17
18
    public function __construct($httpCode, $headers, $body)
19
    {
20
        $this->httpCode = $httpCode;
21
        $this->headers = $headers;
22
        $this->body = json_decode($body);
23
        $this->bodyJsonStatus = json_last_error();
24
        $this->handleResponse();
25
    }
26
27
    public function getHttpCode()
28
    {
29
        return $this->httpCode;
30
    }
31
32
    public function getHeaders()
33
    {
34
        return $this->headers;
35
    }
36
37
    public function getBody()
38
    {
39
        return $this->body;
40
    }
41
42
    protected function handleResponse()
43
    {
44
        $this->checkRateLimit();
45
        $this->checkValidJson();
46
        $this->checkForbidden();
47
    }
48
49
    protected function checkForbidden()
50
    {
51
        if ($this->httpCode == self::FORBIDDEN) {
52
53
            throw new InvalidCredentials();
54
        }
55
    }
56
57
    protected function checkValidJson()
58
    {
59
        if ($this->bodyJsonStatus !== JSON_ERROR_NONE) {
60
            throw new UnknownError($this->getBody());
61
        }
62
    }
63
64
    private function checkRateLimit()
65
    {
66
        if ($this->httpCode == self::RATE_LIMIT) {
67
            $timeout = 60;
68
            if (isset($this->getHeaders()['Retry-After'])) {
69
                $timeout = $this->getHeaders()['Retry-After'];
70
            }
71
            $rateLimit = new RateLimit();
72
            $rateLimit->setTimeout($timeout);
73
74
            throw $rateLimit;
75
        }
76
    }
77
}
78