2
2
3
3
namespace GearboxSolutions \EloquentFileMaker \Database \Eloquent \Concerns ;
4
4
5
+ use DateTime ;
5
6
use Illuminate \Database \Eloquent \Concerns \HasAttributes ;
7
+ use Illuminate \Support \Arr ;
6
8
7
9
trait FMHasAttributes
8
10
{
9
- use HasAttributes;
10
11
11
12
/**
12
- * Determine whether a value is Date / DateTime castable for inbound manipulation .
13
+ * Set a given attribute on the model .
13
14
*
14
- * @param string $key
15
- * @return bool
15
+ * @param string $key
16
+ * @param mixed $value
17
+ * @return mixed
16
18
*/
17
- protected function isDateCastable ($ key )
19
+ public function setAttribute ($ key, $ value )
18
20
{
19
- // We need to also cast timestamps as
20
- return $ this ->hasCast ($ key , ['date ' , 'datetime ' , 'immutable_date ' , 'immutable_datetime ' , 'timestamp ' , 'custom_datetime ' ]);
21
+ parent ::setAttribute ($ key , $ value );
22
+
23
+ $ value = $ this ->attributes [$ key ];
24
+
25
+ // Check if we still have a DateTime object due to custom formatting and convert it to a string to write to FM.
26
+ // Normally the SQL grammar would handle converting DateTime objects and SQL doesn't care about extra time data,
27
+ // but FileMaker does, so we have to convert at this point and strip out times.
28
+ //
29
+ // We could convert the DateTime to a string at the time when we're preparing the API call, but at that point
30
+ // we won't be in the model and won't have access to the cast type to determine if we should strip out the
31
+ // time data.
32
+
33
+ if ($ value instanceof DateTime) {
34
+ $ value = $ value ->format ($ this ->dateFormat );
35
+ }
36
+ // When writing dates the regular datetime format won't work, so we have to get JUST the date value
37
+ // check the key's cast to see if it is cast to a date or custom date:format
38
+ $ castType = $ this ->getCasts ()[$ key ] ?? null ;
39
+ $ isDate = $ castType == "date " || str_starts_with ($ castType , 'date: ' );
40
+ if ($ isDate ) {
41
+ $ value = Arr::first (explode (' ' , $ value ));
42
+ }
43
+
44
+ // FileMaker can't handle true and false, so we need to change to 1 and 0
45
+ if (is_bool ($ value )) {
46
+ $ value = $ value ? 1 : 0 ;
47
+ }
48
+
49
+ // FileMaker can't handle null, so change it to ''
50
+ if (is_null ($ value )) {
51
+ $ value = '' ;
52
+ }
53
+
54
+ $ this ->attributes [$ key ] = $ value ;
55
+
56
+ return $ this ;
21
57
}
22
58
23
59
}
0 commit comments