Passed
Push — master ( b5614d...d40861 )
by Daniel
02:16 queued 13s
created

ValidationResult::addError()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
namespace App\Support\Validation;
4
5
final class ValidationResult
6
{
7
    private array $errors = [];
8
9 4
    public function __construct(array $errors = [])
10
    {
11 4
        $this->addErrors($errors);
12
    }
13
14 4
    private function addErrors(array $errors, string $path = ''): void
15
    {
16 4
        foreach ($errors as $field => $error) {
17 2
            $oldPath = $path;
18 2
            $path .= ($path === '' ? '' : '.') . $field;
19 2
            $this->addSubErrors($error, $path);
20 2
            $path = $oldPath;
21
        }
22
    }
23
24 2
    private function addSubErrors(array $error, string $path = ''): void
25
    {
26 2
        foreach ($error as $field2 => $errorMessage) {
27 2
            if (is_array($errorMessage)) {
28
                $this->addErrors([$field2 => $errorMessage], $path);
29
            } else {
30 2
                $this->addError($path, $errorMessage);
31
            }
32
        }
33
    }
34
35 2
    public function addError(string $field, string $message): void
36
    {
37 2
        $this->errors[$field] = $message;
38
    }
39
40 2
    public function getErrors(): array
41
    {
42 2
        return $this->errors;
43
    }
44
45 4
    public function success(): bool
46
    {
47 4
        return empty($this->errors);
48
    }
49
50 4
    public function fails(): bool
51
    {
52 4
        return !$this->success();
53
    }
54
}
55