|
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
|
|
|
parent::__construct($message ?? 'Input validation failed', $code, $previous); |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
/** @inheritDoc */ |
|
27
|
|
|
public function getErrors(): array |
|
28
|
|
|
{ |
|
29
|
|
|
return $this->errors; |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
public static function setFactory(?ValidationExceptionFactoryInterface $factory): void |
|
33
|
|
|
{ |
|
34
|
|
|
self::$userDefinedFactory = $factory; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
public static function hasFactory(): bool |
|
38
|
|
|
{ |
|
39
|
|
|
return self::$userDefinedFactory instanceof ValidationExceptionFactoryInterface; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
public static function getFactory(): ?ValidationExceptionFactoryInterface |
|
43
|
|
|
{ |
|
44
|
|
|
return self::$userDefinedFactory; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
public function toArray(): array |
|
48
|
|
|
{ |
|
49
|
|
|
return [ |
|
50
|
|
|
'message' => $this->message, |
|
51
|
|
|
'code' => $this->getCode(), |
|
52
|
|
|
'violations' => $this->errorsAsArray(), |
|
53
|
|
|
]; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
public function toString(): string |
|
57
|
|
|
{ |
|
58
|
|
|
return $this->message . PHP_EOL . $this->errorsAsString(); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
public function __toString() |
|
62
|
|
|
{ |
|
63
|
|
|
return $this->toString(); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
public function jsonSerialize(): array |
|
67
|
|
|
{ |
|
68
|
|
|
return $this->toArray(); |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|