Passed
Push — main ( 7af829...98157c )
by Breno
02:12
created

ErrorReporting::guard()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 4
rs 10
c 1
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace BrenoRoosevelt\Validation;
5
6
use BrenoRoosevelt\Validation\Exception\GuardTrait;
7
use BrenoRoosevelt\Validation\Exception\ValidationExceptionFactoryInterface;
8
use BrenoRoosevelt\Validation\Exception\ValidationExceptionInterface;
9
10
class ErrorReporting implements Result
11
{
12
    use GuardTrait;
13
14
    /** @var Error[] */
15
    private array $errors = [];
16
17
    final public function __construct(Error | Result ...$errors)
18
    {
19
        foreach ($errors as $errorOrResult) {
20
            array_push(
21
                $this->errors,
22
                ...($errorOrResult instanceof Error ? [$errorOrResult] : $errorOrResult->getErrors())
23
            );
24
        }
25
    }
26
27
    public static function success(): self
28
    {
29
        return new self;
30
    }
31
32
    public function add(Error | Result ...$errors): self
33
    {
34
        return new self(...$this->errors, ...$errors);
35
    }
36
37
    public function addError(string $message, Rule $rule, ?string $field = null): self
38
    {
39
        return $this->add(new ErrorMessage($message, $rule, $field));
40
    }
41
42
    /** @inheritDoc */
43
    public function isOk(): bool
44
    {
45
        return empty($this->errors);
46
    }
47
48
    /** @inheritDoc */
49
    public function getErrors(): array
50
    {
51
        return $this->errors;
52
    }
53
54
    /** @throws ValidationExceptionInterface */
55
    public function guard(
56
        ValidationExceptionFactoryInterface | ValidationExceptionInterface | string | null  $validationException = null
57
    ): void {
58
        $this->guardResult($this, $validationException);
59
    }
60
}
61