Response::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Rinvex\Authy;
6
7
use Psr\Http\Message\ResponseInterface;
8
9
class Response
10
{
11
    /**
12
     * The Aythy response body content as array.
13
     *
14
     * @var array
15
     */
16
    protected $body;
17
18
    /**
19
     * The Aythy response status code.
20
     *
21
     * @var int
22
     */
23
    protected $status;
24
25
    /**
26
     * Create a new Authy response instance.
27
     *
28
     * @param \Psr\Http\Message\ResponseInterface $httpResponse
29
     */
30
    public function __construct(ResponseInterface $httpResponse)
31
    {
32
        $this->status = $httpResponse->getStatusCode();
33
        $this->body = ($body = (string) $httpResponse->getBody()) ? json_decode($body, true) : null;
34
    }
35
36
    /**
37
     * Get Authy response status code.
38
     *
39
     * @return int
40
     */
41
    public function statusCode(): int
42
    {
43
        return $this->status;
44
    }
45
46
    /**
47
     * Get Authy response body item.
48
     *
49
     * @param string $var
50
     *
51
     * @return mixed
52
     */
53
    public function get($var)
54
    {
55
        return $this->body[$var] ?? null;
56
    }
57
58
    /**
59
     * Get Authy response body message.
60
     *
61
     * @return string
62
     */
63
    public function message(): string
64
    {
65
        return $this->get('message');
66
    }
67
68
    /**
69
     * Determine if the Authy response succeed.
70
     *
71
     * @return bool
72
     */
73
    public function succeed(): bool
74
    {
75
        return $this->statusCode() === 200 && $this->isSuccess($this->get('success'));
76
    }
77
78
    /**
79
     * Determine if the Authy response failed.
80
     *
81
     * @return bool
82
     */
83
    public function failed(): bool
84
    {
85
        return ! $this->succeed();
86
    }
87
88
    /**
89
     * Get Authy response errors.
90
     *
91
     * @return array
92
     */
93
    public function errors(): array
94
    {
95
        $errors = $this->get('errors') ?: [];
96
97
        return $this->failed() && ! empty($errors) ? $errors : [];
98
    }
99
100
    /**
101
     * Determine if the given result is success.
102
     *
103
     * @param mixed $result
104
     *
105
     * @return bool
106
     */
107
    protected function isSuccess($result): bool
108
    {
109
        return ! is_null($result) ? (is_string($result) && $result === 'true') || (is_bool($result) && $result) : false;
110
    }
111
}
112