Passed
Push — main ( 6afe0c...47aea4 )
by Breno
01:54
created

Guard::guardResult()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 22
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 10
nc 5
nop 2
dl 0
loc 22
rs 9.6111
c 1
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace BrenoRoosevelt\Validation\Exception;
5
6
use BrenoRoosevelt\Validation\Contracts\Result;
7
use BrenoRoosevelt\Validation\Contracts\Rule;
8
9
trait Guard
10
{
11
    /**
12
     * @throws ValidationExceptionInterface
13
     */
14
    protected function guardRule(
15
        Rule $rule,
16
        mixed $input,
17
        array $context = [],
18
        ValidationExceptionFactoryInterface | 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
        ValidationExceptionFactoryInterface | ValidationExceptionInterface | string | null $validationException = null
30
    ): void {
31
        if ($result->isOk()) {
32
            return;
33
        }
34
35
        if ($validationException instanceof ValidationExceptionInterface) {
36
            throw $validationException;
37
        }
38
39
        if ($validationException instanceof ValidationExceptionFactoryInterface) {
40
            throw $validationException->create($result);
41
        }
42
43
        $exceptionMessage = $validationException;
44
        if (ValidationException::hasFactory()) {
45
            throw ValidationException::getFactory()->create($result, $exceptionMessage);
46
        }
47
48
        throw new ValidationException($result->getErrors(), $exceptionMessage);
49
    }
50
}
51