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

ValidationExceptionFactory   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
dl 0
loc 30
rs 10
c 1
b 0
f 0
wmc 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
A defaultException() 0 8 3
A setDefault() 0 3 1
A __construct() 0 2 1
A create() 0 6 2
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