1 | <?php |
||
2 | |||
3 | namespace kalanis\Restful\Validation\Exceptions; |
||
4 | |||
5 | |||
6 | use Exception; |
||
7 | use kalanis\Restful\Exceptions\LogicException; |
||
8 | use kalanis\Restful\Validation\Rule; |
||
9 | use Nette\Utils\Strings; |
||
10 | |||
11 | |||
12 | /** |
||
13 | * ValidationException is thrown when validation problem appears |
||
14 | * @package kalanis\Restful\Validation\Exceptions |
||
15 | */ |
||
16 | 1 | class ValidationException extends LogicException |
|
17 | { |
||
18 | |||
19 | 1 | public function __construct( |
|
20 | protected string $field, |
||
21 | string $message = "", |
||
22 | int $code = 0, |
||
23 | Exception $previous = null, |
||
24 | ) |
||
25 | { |
||
26 | 1 | parent::__construct($message, $code, $previous); |
|
27 | 1 | } |
|
28 | |||
29 | /** |
||
30 | * Validation exception simple factory |
||
31 | */ |
||
32 | public static function createFromRule( |
||
33 | Rule $rule, |
||
34 | mixed $value = null, |
||
35 | ): self |
||
36 | { |
||
37 | 1 | $arg = $rule->getArgument(); |
|
38 | 1 | $printable = match (true) { |
|
39 | 1 | is_object($arg) => [get_class($arg)], |
|
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
40 | 1 | is_callable($arg) => [get_debug_type($arg)], |
|
41 | 1 | default => (array) $arg, |
|
42 | }; |
||
43 | |||
44 | 1 | return new self( |
|
45 | 1 | $rule->getField(), |
|
46 | ( |
||
47 | 1 | $value |
|
48 | 1 | ? "'" . Strings::truncate(strval($value), 60) . "' is invalid value: " |
|
49 | 1 | : '' |
|
50 | 1 | ) . vsprintf($rule->getMessage(), $printable), |
|
51 | 1 | $rule->getCode(), |
|
52 | ); |
||
53 | } |
||
54 | |||
55 | /** |
||
56 | * Get validation field name |
||
57 | */ |
||
58 | public function getField(): string |
||
59 | { |
||
60 | 1 | return $this->field; |
|
61 | } |
||
62 | } |
||
63 |