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

ErrorReporting   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 13
c 2
b 0
f 0
dl 0
loc 49
rs 10
wmc 9

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 3
A getErrors() 0 3 1
A isOk() 0 3 1
A addError() 0 3 1
A guard() 0 4 1
A add() 0 3 1
A success() 0 3 1
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