|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* This file is part of Dimtrovich/Validation. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) 2023 Dimitri Sitchet Tomkeu <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* For the full copyright and license information, please view |
|
9
|
|
|
* the LICENSE file that was distributed with this source code. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace Dimtrovich\Validation\Exceptions; |
|
13
|
|
|
|
|
14
|
|
|
use Dimtrovich\Validation\ErrorBag; |
|
15
|
|
|
use Dimtrovich\Validation\Validation; |
|
16
|
|
|
use Exception; |
|
17
|
|
|
|
|
18
|
|
|
class ValidationException extends Exception |
|
19
|
|
|
{ |
|
20
|
|
|
/** |
|
21
|
|
|
* Validation errors list |
|
22
|
|
|
*/ |
|
23
|
|
|
protected ?ErrorBag $errors = null; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* Error code |
|
27
|
|
|
* |
|
28
|
|
|
* @var int |
|
29
|
|
|
*/ |
|
30
|
|
|
protected $code = 400; |
|
31
|
|
|
|
|
32
|
|
|
public function __construct(string $message = '', ?Validation $validator = null) |
|
33
|
|
|
{ |
|
34
|
|
|
if ($validator) { |
|
35
|
|
|
$message = self::summarize($validator); |
|
36
|
|
|
$this->errors = $validator->errors(); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
parent::__construct($message); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* Get errors |
|
44
|
|
|
*/ |
|
45
|
|
|
public function getErrors(): ?ErrorBag |
|
46
|
|
|
{ |
|
47
|
|
|
return $this->errors; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* Set errors |
|
52
|
|
|
*/ |
|
53
|
|
|
public function setErrors(?ErrorBag $errors): self |
|
54
|
|
|
{ |
|
55
|
|
|
$this->errors = $errors; |
|
56
|
|
|
|
|
57
|
|
|
return $this; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
/** |
|
61
|
|
|
* Create an error message summary from the validation errors. |
|
62
|
|
|
*/ |
|
63
|
|
|
public static function summarize(Validation $validator): string |
|
64
|
|
|
{ |
|
65
|
|
|
$messages = $validator->errors()->all(); |
|
66
|
|
|
|
|
67
|
|
|
if (! count($messages) || ! is_string($messages[0])) { |
|
68
|
|
|
return $validator->getValidator()->getTranslation('The given data was invalid.'); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
$message = array_shift($messages); |
|
72
|
|
|
|
|
73
|
|
|
if ($count = count($messages)) { |
|
74
|
|
|
$pluralized = $count === 1 ? 'error' : 'errors'; |
|
75
|
|
|
|
|
76
|
|
|
$message .= ' ' . $validator->getValidator()->getTranslation("(and {$count} more {$pluralized})"); |
|
77
|
|
|
} |
|
78
|
|
|
|
|
79
|
|
|
return $message; |
|
80
|
|
|
} |
|
81
|
|
|
|
|
82
|
|
|
public static function ruleNotFound(?string $rule = null) |
|
83
|
|
|
{ |
|
84
|
|
|
return new self($rule . ' is not a valid rule.'); |
|
85
|
|
|
} |
|
86
|
|
|
} |
|
87
|
|
|
|