1+ <?php
2+
3+ namespace Ssntpl \DataFields \Casts ;
4+
5+ use Illuminate \Contracts \Database \Eloquent \CastsAttributes ;
6+ use Ssntpl \DataFields \Enums \FieldType ;
7+ use Ssntpl \LaravelFiles \Models \File ;
8+
9+ class FieldValueCast implements CastsAttributes
10+ {
11+ public function get ($ model , string $ key , $ value , array $ attributes )
12+ {
13+ if (is_null ($ value )) return null ;
14+
15+ return match ($ attributes ['type ' ] ?? FieldType::TEXT ) {
16+ FieldType::NUMBER => (float ) $ value ,
17+ FieldType::BOOLEAN , FieldType::CHECK => (bool ) $ value ,
18+ FieldType::MULTIPLE , FieldType::ARRAY => json_decode ($ value , true ),
19+ FieldType::JSON => json_decode ($ value , true ),
20+ FieldType::FILE => $ this ->getFileFromJson ($ value ),
21+ default => (string ) $ value
22+ };
23+ }
24+
25+ public function set ($ model , string $ key , $ value , array $ attributes )
26+ {
27+ if (is_null ($ value )) return null ;
28+
29+ return match ($ attributes ['type ' ] ?? FieldType::TEXT ) {
30+ FieldType::MULTIPLE , FieldType::ARRAY , FieldType::JSON => json_encode ($ value ),
31+ FieldType::BOOLEAN , FieldType::CHECK => $ value ? '1 ' : '0 ' ,
32+ FieldType::FILE => $ this ->setFileAsJson ($ value ),
33+ default => (string ) $ value
34+ };
35+ }
36+
37+ private function getFileFromJson ($ value )
38+ {
39+ $ data = json_decode ($ value , true );
40+
41+ if (!is_array ($ data ) || !isset ($ data ['model_type ' ], $ data ['model_id ' ])) {
42+ return $ value ;
43+ }
44+
45+ return $ data ['model_type ' ]::find ($ data ['model_id ' ]);
46+ }
47+
48+ private function setFileAsJson ($ value )
49+ {
50+ if ($ value instanceof File) {
51+ return json_encode ([
52+ 'model_type ' => get_class ($ value ),
53+ 'model_id ' => $ value ->id
54+ ]);
55+ }
56+
57+ if (is_numeric ($ value )) {
58+ return json_encode ([
59+ 'model_type ' => File::class,
60+ 'model_id ' => (int ) $ value
61+ ]);
62+ }
63+
64+ return (string ) $ value ;
65+ }
66+ }
0 commit comments