Passed
Push — main ( 074ebe...9be93f )
by Breno
01:36
created

ValidationException::toArray()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 0
dl 0
loc 6
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\Error;
7
use Exception;
8
use JsonSerializable;
9
use Throwable;
10
11
class ValidationException extends Exception implements ValidationExceptionInterface, JsonSerializable
12
{
13
    use ParseErrorsTrait;
14
15
    private static ?ValidationExceptionFactoryInterface $userDefinedFactory = null;
16
17
    /** @var Error[] */
18
    private array $errors;
19
20
    public function __construct(array $errors, ?string $message = "", int $code = 400, ?Throwable $previous = null)
21
    {
22
        $this->errors = array_filter($errors, fn($e) => $e instanceof Error);
23
        $message = $message ?? 'Input validation failed' . PHP_EOL . $this->errorsAsString();
24
        parent::__construct($message, $code, $previous);
25
    }
26
27
    /** @inheritDoc */
28
    public function getErrors(): array
29
    {
30
        return $this->errors;
31
    }
32
33
    public static function setFactory(?ValidationExceptionFactoryInterface $factory): void
34
    {
35
        self::$userDefinedFactory = $factory;
36
    }
37
38
    public static function hasFactory(): bool
39
    {
40
        return self::$userDefinedFactory instanceof ValidationExceptionFactoryInterface;
41
    }
42
43
    public static function getFactory(): ?ValidationExceptionFactoryInterface
44
    {
45
        return self::$userDefinedFactory;
46
    }
47
48
    public function toArray(): array
49
    {
50
        return [
51
            'message' => $this->message ?? 'Input validation failed',
52
            'code' => $this->getCode(),
53
            'violations' => $this->errorsAsArray(),
54
        ];
55
    }
56
57
    public function jsonSerialize(): array
58
    {
59
        return $this->toArray();
60
    }
61
}
62