JsonResponse::getStatusCode()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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