Response::handleResponse()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 3
c 1
b 1
f 0
dl 0
loc 5
rs 10
cc 1
nc 1
nop 0
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