2
2
3
3
namespace ProgrammatorDev \Validator \Exception ;
4
4
5
+ use ProgrammatorDev \Validator \Exception \Util \MessageTrait ;
6
+
5
7
class ValidationException extends \Exception
6
8
{
9
+ use MessageTrait;
10
+
7
11
public function __construct (string $ message , array $ parameters = [])
8
12
{
9
13
$ message = $ this ->formatMessage ($ message , $ parameters );
10
14
11
15
parent ::__construct ($ message );
12
16
}
13
-
14
- private function formatMessage (string $ message , array $ parameters = []): string
15
- {
16
- // If a name was not given, remove it from the message template but keep it intuitive
17
- if (empty ($ parameters ['name ' ])) {
18
- $ message = \str_replace (' {{ name }} ' , ' ' , $ message );
19
- unset($ parameters ['name ' ]);
20
- }
21
-
22
- foreach ($ parameters as $ parameter => $ value ) {
23
- // Format values (with some exceptions [name, message] to avoid adding unnecessary quotation marks)
24
- $ message = \str_replace (
25
- \sprintf ('{{ %s }} ' , $ parameter ),
26
- (\in_array ($ parameter , ['name ' , 'message ' ])) ? $ value : $ this ->formatValue ($ value ),
27
- $ message
28
- );
29
- }
30
-
31
- return $ message ;
32
- }
33
-
34
- private function formatValue (mixed $ value ): string
35
- {
36
- if ($ value instanceof \DateTimeInterface) {
37
- return $ value ->format ('Y-m-d H:i:s ' );
38
- }
39
-
40
- if (\is_object ($ value )) {
41
- if ($ value instanceof \Stringable) {
42
- return $ value ->__toString ();
43
- }
44
-
45
- return 'object ' ;
46
- }
47
-
48
- if (\is_array ($ value )) {
49
- return $ this ->formatValues ($ value );
50
- }
51
-
52
- if (\is_string ($ value )) {
53
- // Replace line breaks and tabs with single space
54
- $ value = \str_replace (["\n" , "\r" , "\t" , "\v" , "\x00" ], ' ' , $ value );
55
-
56
- return \sprintf ('"%s" ' , $ value );
57
- }
58
-
59
- if (\is_resource ($ value )) {
60
- return 'resource ' ;
61
- }
62
-
63
- if ($ value === null ) {
64
- return 'null ' ;
65
- }
66
-
67
- if ($ value === false ) {
68
- return 'false ' ;
69
- }
70
-
71
- if ($ value === true ) {
72
- return 'true ' ;
73
- }
74
-
75
- return (string ) $ value ;
76
- }
77
-
78
- private function formatValues (array $ values ): string
79
- {
80
- foreach ($ values as $ key => $ value ) {
81
- $ values [$ key ] = $ this ->formatValue ($ value );
82
- }
83
-
84
- return \sprintf ('[%s] ' , \implode (', ' , $ values ));
85
- }
86
17
}
0 commit comments