Passed
Push — main ( 878501...a59213 )
by Breno
03:08
created

Guard   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 39
rs 10
wmc 8

2 Methods

Rating   Name   Duplication   Size   Complexity  
A guardRule() 0 8 1
B guardResult() 0 21 7
1
<?php
2
declare(strict_types=1);
3
4
namespace BrenoRoosevelt\Validation\Exception;
5
6
use BrenoRoosevelt\Validation\Result;
7
use BrenoRoosevelt\Validation\Rule;
8
use BrenoRoosevelt\Validation\ValidationResultSet;
9
10
trait Guard
11
{
12
    /**
13
     * @throws ValidationExceptionInterface
14
     */
15
    protected function guardRule(
16
        Rule $rule,
17
        mixed $input,
18
        array $context = [],
19
        ?ValidationExceptionInterface $validationException = null
20
    ): void {
21
        $result = $rule->validate($input, $context);
22
        $this->guardResult($result, $validationException);
23
    }
24
25
    /**
26
     * @throws ValidationExceptionInterface
27
     */
28
    protected function guardResult(
29
        Result | ValidationResultSet $guardResult,
30
        ValidationExceptionInterface | string | null $validationException = null
31
    ): void {
32
        if ($guardResult->isOk()) {
33
            return;
34
        }
35
36
        $exception =
37
            $validationException instanceof ValidationExceptionInterface ?
38
                $validationException :
39
                new ValidationException(is_string($validationException) ? $validationException : '');
40
41
        $results = $guardResult instanceof Result ? [$guardResult] : $guardResult->validationResults();
42
        foreach ($results as $result) {
43
            foreach ($result->getErrors() as $error) {
44
                $exception->addError($error, $result->getField());
45
            }
46
        }
47
48
        throw $exception;
49
    }
50
}
51