@@ -37,25 +37,45 @@ public function __construct(\Magento\Framework\Stdlib\DateTime\TimezoneInterface
37
37
public function beforeSave ($ object )
38
38
{
39
39
$ attributeName = $ this ->getAttribute ()->getName ();
40
- $ pattern = '/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/ ' ;
41
- // format only date that was not formatted yet
42
- if ($ object ->hasData ($ attributeName ) && !preg_match ($ pattern , $ object ->getData ($ attributeName ))) {
43
- try {
44
- $ value = $ this ->formatDate ($ object ->getData ($ attributeName ));
45
- } catch (\Exception $ e ) {
46
- throw new \Magento \Framework \Exception \LocalizedException (__ ('Invalid date ' ));
47
- }
40
+ $ attributeValue = $ object ->getData ($ attributeName );
41
+ if ($ object ->hasData ($ attributeName )) {
42
+ // format only date that is not formatted yet
43
+ $ dateFormatted = $ this ->dateIsFormatted ($ attributeValue );
44
+ if (!$ dateFormatted ) {
45
+ try {
46
+ $ value = $ this ->formatDate ($ attributeValue );
47
+ } catch (\Exception $ e ) {
48
+ throw new \Magento \Framework \Exception \LocalizedException (__ ('Invalid date ' ));
49
+ }
48
50
49
- if (is_null ($ value )) {
50
- $ value = $ object -> getData ( $ attributeName ) ;
51
- }
51
+ if (is_null ($ value )) {
52
+ $ value = $ attributeValue ;
53
+ }
52
54
53
- $ object ->setData ($ attributeName , $ value );
55
+ $ object ->setData ($ attributeName , $ value );
56
+ }
54
57
}
55
58
56
59
return $ this ;
57
60
}
58
61
62
+ /**
63
+ * Check if date is formatted
64
+ *
65
+ * @param string|\DateTime $attributeValue
66
+ * @return bool
67
+ */
68
+ private function dateIsFormatted ($ attributeValue )
69
+ {
70
+ $ pattern = '/(\d{4})-(\d{2})-(\d{2})(\s(\d{2}):(\d{2}):(\d{2}))?/ ' ;
71
+ if ($ attributeValue instanceof \DateTime) {
72
+ return false ;
73
+ } elseif (preg_match ($ pattern , $ attributeValue )) {
74
+ return true ;
75
+ }
76
+ return false ;
77
+ }
78
+
59
79
/**
60
80
* Prepare date for save in DB
61
81
*
0 commit comments