33namespace DivineOmega \DatesTimezoneConversion \Traits ;
44
55use Carbon \Carbon ;
6+ use DemeterChain \C ;
67use Illuminate \Database \Eloquent \Model ;
78use Illuminate \Support \Facades \Auth ;
89
@@ -44,7 +45,16 @@ public function getAttributeValue($key)
4445 */
4546 public function setAttribute ($ key , $ value )
4647 {
47- if ($ this ->isDateObject ($ key , $ value )) {
48+ if (in_array ($ key , $ this ->getDates ())) {
49+ $ value = $ this ->convertToDateObject ($ value );
50+
51+ /** @var Model $user */
52+ $ user = Auth::user ();
53+
54+ if ($ user ) {
55+ $ value = Carbon::parse ($ value , $ user ->getAttributeValue ('timezone ' ));
56+ }
57+
4858 $ value ->setTimezone (config ('app.timezone ' ));
4959 }
5060
@@ -63,7 +73,30 @@ private function isDateObject($key, $value)
6373 {
6474 return in_array ($ key , $ this ->getDates ()) &&
6575 is_object ($ value ) &&
66- get_class ($ value ) === Carbon::class;
76+ $ value instanceof Carbon;
77+ }
78+
79+ /**
80+ * Converts a value to a Carbon date object if needed.
81+ *
82+ * @param $value
83+ * @return Carbon
84+ */
85+ private function convertToDateObject ($ value )
86+ {
87+ if (is_object ($ value ) && $ value instanceof Carbon) {
88+ return $ value ;
89+ }
90+
91+ if (is_string ($ value )) {
92+ return Carbon::parse ($ value );
93+ }
94+
95+ if (is_integer ($ value )) {
96+ return Carbon::createFromTimestamp ($ value );
97+ }
98+
99+ throw new \Exception ('Unable to convert value to Carbon date object. ' );
67100 }
68101
69- }
102+ }
0 commit comments