Test Failed
Push — main ( 9ff78e...4dc0dd )
by Paul
08:02
created

Response   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 3
Bugs 0 Features 2
Metric Value
wmc 10
eloc 27
c 3
b 0
f 2
dl 0
loc 55
rs 10
ccs 0
cts 17
cp 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 2
A data() 0 5 1
A successful() 0 5 3
A body() 0 5 1
A shouldRetry() 0 4 2
A failed() 0 3 1
1
<?php
2
3
namespace GeminiLabs\SiteReviews;
4
5
use GeminiLabs\SiteReviews\Helpers\Arr;
6
use GeminiLabs\SiteReviews\Helpers\Cast;
7
8
class Response
9
{
10
    public array $body;
11
    public int $code;
12
    public bool $error = false;
13
    public string $message;
14
    public array $response;
15
16
    /**
17
     * @param array|\WP_Error $request
18
     */
19
    public function __construct($request = [])
20
    {
21
        $body = json_decode(wp_remote_retrieve_body($request), true);
22
        $this->body = Cast::toArray($body);
23
        $this->code = Cast::toInt(wp_remote_retrieve_response_code($request));
24
        $this->message = Arr::getAs('string', $body, 'message', wp_remote_retrieve_response_message($request));
25
        $this->response = Arr::getAs('array', $request, 'http_response');
26
        if (is_wp_error($request)) {
27
            $this->error = true;
28
            $this->message = $request->get_error_message();
29
            glsr_log()->error($this->message);
30
        }
31
    }
32
33
    public function body(): array
34
    {
35
        $body = Arr::consolidate($this->body);
36
        $body = array_map('maybe_unserialize', $body);
37
        return $body;
38
    }
39
40
    public function data(): array
41
    {
42
        $data = Arr::getAs('array', $this->body, 'data');
43
        $data = array_map('maybe_unserialize', $data);
44
        return $data;
45
    }
46
47
    public function failed(): bool
48
    {
49
        return !$this->successful();
50
    }
51
52
    public function shouldRetry(): bool
53
    {
54
        return 429 === $this->code // Too-Many-Requests
55
            || $this->code >= 500; // Internal errors
56
    }
57
58
    public function successful(): bool
59
    {
60
        return false === $this->error
61
            && $this->code >= 200
62
            && $this->code <= 299;
63
    }
64
}
65