22
33namespace ProgrammatorDev \Validator \Exception ;
44
5+ use ProgrammatorDev \Validator \Exception \Util \MessageTrait ;
6+
57class ValidationException extends \Exception
68{
9+ use MessageTrait;
10+
711 public function __construct (string $ message , array $ parameters = [])
812 {
913 $ message = $ this ->formatMessage ($ message , $ parameters );
1014
1115 parent ::__construct ($ message );
1216 }
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- }
8617}
0 commit comments