JsonResponse::isAuthorized()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Marek\OpenWeatherMap\Http\Response;
6
7
final class JsonResponse implements ResponseInterface
8
{
9
    /**
10
     * @var array|string
11
     */
12
    private $data;
13
14
    /**
15
     * @var int
16
     */
17
    private $httpCode;
18
19
    /**
20
     * Response constructor.
21
     *
22
     * @param string $data
23
     * @param int $httpCode
24
     */
25
    public function __construct(string $data, int $httpCode)
26
    {
27
        if ($this->isValidJson($data)) {
28
            $data = json_decode($data, true, 512, JSON_THROW_ON_ERROR);
29
        }
30
        $this->data = $data;
31
32
        if (is_array($data) && array_key_exists('cod', $data)) {
33
            $this->httpCode = (int) $data['cod'];
34
        } else {
35
            $this->httpCode = $httpCode;
36
        }
37
    }
38
39
    /**
40
     * Returns data represented as string.
41
     *
42
     * @return string
43
     */
44
    public function __toString(): string
45
    {
46
        if (is_array($this->data)) {
47
            return json_encode($this->data, JSON_THROW_ON_ERROR);
48
        }
49
50
        return $this->data;
51
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56
    public function getStatusCode(): int
57
    {
58
        return $this->httpCode;
59
    }
60
61
    /**
62
     * {@inheritdoc}
63
     */
64
    public function getData(): array
65
    {
66
        return $this->data;
67
    }
68
69
    /**
70
     * {@inheritdoc}
71
     */
72
    public function isOk(): bool
73
    {
74
        if ($this->httpCode === 200) {
75
            return true;
76
        }
77
78
        return false;
79
    }
80
81
    /**
82
     * {@inheritdoc}
83
     */
84
    public function isAuthorized(): bool
85
    {
86
        if ($this->httpCode !== 401) {
87
            return true;
88
        }
89
90
        return false;
91
    }
92
93
    /**
94
     * {@inheritdoc}
95
     */
96
    public function getMessage(): string
97
    {
98
        if (is_array($this->data) && array_key_exists('message', $this->data)) {
99
            return (string) $this->data['message'];
100
        }
101
102
        return '';
103
    }
104
105
    /**
106
     * Checks if given string is valid json.
107
     *
108
     * @param string $string
109
     *
110
     * @return bool
111
     */
112
    private function isValidJson($string): bool
113
    {
114
        if (!is_string($string)) {
115
            return false;
116
        }
117
118
        json_decode($string, false, 512, JSON_THROW_ON_ERROR);
119
120
        return json_last_error() === JSON_ERROR_NONE;
121
    }
122
}
123