Passed
Push — main ( 4724f2...e4f74b )
by Breno
01:53
created

ValidationExceptionFactory::defaultException()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 6
nc 2
nop 1
dl 0
loc 8
rs 10
c 1
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace BrenoRoosevelt\Validation\Exception;
5
6
use BrenoRoosevelt\Validation\Result;
7
8
final class ValidationExceptionFactory implements ValidationExceptionFactoryInterface
9
{
10
    private static ?ValidationExceptionFactoryInterface $userDefinedFactory = null;
11
12
    public function __construct(private ValidationExceptionInterface | string | null $exception = null)
13
    {
14
    }
15
16
    public static function setDefault(ValidationExceptionFactoryInterface $factory): void
17
    {
18
        self::$userDefinedFactory = $factory;
19
    }
20
21
    /** @inheritDoc */
22
    public function create(Result $result): ValidationExceptionInterface
23
    {
24
        return
25
            self::$userDefinedFactory instanceof ValidationExceptionFactoryInterface ?
26
                self::$userDefinedFactory->create($result) :
27
                $this->defaultException($result);
28
    }
29
30
    private function defaultException(Result $result): ValidationExceptionInterface
31
    {
32
        return
33
            $this->exception instanceof ValidationExceptionInterface ?
34
                $this->exception :
35
                new ValidationException(
36
                    $result->getErrors(),
37
                    is_string($this->exception) ? $this->exception : ''
38
                );
39
    }
40
}
41