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

Guard::guardResult()   B

Complexity

Conditions 7
Paths 13

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 11
c 1
b 0
f 0
nc 13
nop 2
dl 0
loc 21
rs 8.8333
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