Passed
Push — master ( e7e3c4...d0e289 )
by Rogier
01:26
created

DomainValidationData::getErrors()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 19
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
3
namespace Rogierw\RwAcme\DTO;
4
5
use Rogierw\RwAcme\Endpoints\DomainValidation;
6
use Rogierw\RwAcme\Http\Response;
7
use Rogierw\RwAcme\Support\Arr;
8
use Spatie\DataTransferObject\DataTransferObject;
9
10
class DomainValidationData extends DataTransferObject
11
{
12
    public $identifier;
13
    public $status;
14
    public $expires;
15
    public $file;
16
    public $dns;
17
    public $validationRecord;
18
19
    public static function fromResponse(Response $response): self
20
    {
21
        return new self([
22
            'identifier' => $response->getBody()['identifier'],
23
            'status' => $response->getBody()['status'],
24
            'expires' => $response->getBody()['expires'],
25
            'file' => self::getValidationByType($response->getBody()['challenges'], DomainValidation::TYPE_HTTP),
26
            'dns' => self::getValidationByType($response->getBody()['challenges'], DomainValidation::TYPE_DNS),
27
            'validationRecord' => Arr::get($response->getBody(), 'validationRecord', []),
28
        ]);
29
    }
30
31
    private static function getValidationByType(array $haystack, string $type): array
32
    {
33
        foreach ($haystack as $key => $data) {
34
            if ($data['type'] === $type) {
35
                return $haystack[$key];
36
            }
37
        }
38
39
        return [];
40
    }
41
42
    public function isPending(): bool
43
    {
44
        return $this->status === 'pending';
45
    }
46
47
    public function isValid(): bool
48
    {
49
        return $this->status === 'valid';
50
    }
51
52
    public function isInvalid(): bool
53
    {
54
        return $this->status === 'invalid';
55
    }
56
57
    public function hasErrors(): bool
58
    {
59
        if (array_key_exists('error', $this->file) && !empty($this->file['error'])) {
60
            return true;
61
        }
62
63
        if (array_key_exists('error', $this->dns) && !empty($this->dns['error'])) {
64
            return true;
65
        }
66
67
        return false;
68
    }
69
70
    public function getErrors(): array
71
    {
72
        if ($this->hasErrors()) {
73
            $data = [];
74
75
            $data[] = [
76
                'domainValidationType' => DomainValidation::TYPE_HTTP,
77
                'error' => Arr::get($this->file, 'error'),
78
            ];
79
80
            $data[] = [
81
                'domainValidationType' => DomainValidation::TYPE_DNS,
82
                'error' => Arr::get($this->dns, 'error'),
83
            ];
84
85
            return $data;
86
        }
87
88
        return [];
89
    }
90
}
91