@@ -24,6 +24,8 @@ class DateTime
24
24
*/
25
25
public static function filter (?string $ value , array $ options = []): ?\DateTime
26
26
{
27
+ static ::convertConstants ($ options );
28
+
27
29
try {
28
30
if (($ options ['convertNullToNow ' ] ?? false ) && $ value === null ) {
29
31
return new \DateTime ();
@@ -38,7 +40,13 @@ public static function filter(?string $value, array $options = []): ?\DateTime
38
40
}
39
41
40
42
if (($ options ['createFromFormat ' ] ?? false ) && $ value !== null ) {
41
- return \DateTime::createFromFormat ($ options ['createFromFormat ' ], $ value );
43
+ $ result = \DateTime::createFromFormat ($ options ['createFromFormat ' ], $ value );
44
+
45
+ if (!$ result ) {
46
+ throw new Exception ();
47
+ }
48
+
49
+ return $ result ;
42
50
}
43
51
44
52
return $ value !== null ? new \DateTime ($ value ) : null ;
@@ -55,8 +63,24 @@ public static function filter(?string $value, array $options = []): ?\DateTime
55
63
*/
56
64
public static function serialize (?\DateTime $ value , array $ options = []): ?string
57
65
{
66
+ static ::convertConstants ($ options );
67
+
58
68
return ($ value instanceof \DateTime)
59
69
? $ value ->format ($ options ['outputFormat ' ] ?? $ options ['createFromFormat ' ] ?? DATE_ISO8601 )
60
70
: null ;
61
71
}
72
+
73
+ /**
74
+ * Make DATE constants available
75
+ *
76
+ * @param array $options
77
+ */
78
+ protected static function convertConstants (array &$ options ): void
79
+ {
80
+ foreach (['createFromFormat ' , 'outputFormat ' ] as $ format ) {
81
+ if (isset ($ options [$ format ]) && defined ("DATE_ {$ options [$ format ]}" )) {
82
+ $ options [$ format ] = constant ("DATE_ {$ options [$ format ]}" );
83
+ }
84
+ }
85
+ }
62
86
}
0 commit comments