Passed
Push — main ( f7f95e...c4cb1e )
by Breno
02:19
created

GuardTrait::guardRule()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 4
dl 0
loc 8
rs 10
c 0
b 0
f 0
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
9
trait GuardTrait
10
{
11
    /**
12
     * @throws ValidationExceptionInterface
13
     */
14
    protected function guardRule(
15
        Rule $rule,
16
        mixed $input,
17
        array $context = [],
18
        ValidationExceptionInterface | string | null $validationException = null
19
    ): void {
20
        $result = $rule->validate($input, $context);
21
        $this->guardResult($result, $validationException);
22
    }
23
24
    /**
25
     * @throws ValidationExceptionInterface
26
     */
27
    protected function guardResult(
28
        Result $result,
29
        ValidationExceptionInterface | string | null $validationException = null
30
    ): void {
31
        if ($result->isOk()) {
32
            return;
33
        }
34
35
        $exception = $this->createValidationException($validationException);
36
        foreach ($result->getErrors() as $error) {
37
            $exception->addError($error->message(), $error->field());
38
        }
39
40
        throw $exception;
41
    }
42
43
    private function createValidationException(
44
        ValidationExceptionInterface | string | null $validationException = null
45
    ): ValidationExceptionInterface {
46
        return
47
            $validationException instanceof ValidationExceptionInterface ?
48
                $validationException :
49
                new ValidationException(is_string($validationException) ? $validationException : '');
50
    }
51
}
52