1717use ReflectionClass ;
1818
1919/**
20- * Maps an entity class to the table of the model that returns it, discovered by reflecting every
21- * model found under the registered `Models/` namespaces.
20+ * Maps an entity class to the table and `$casts`/`$castHandlers` of the model that returns it,
21+ * discovered by reflecting every model found under the registered `Models/` namespaces.
2222 */
2323final class ModelTableMapProvider
2424{
2525 /**
26- * @var array<class-string, string>|null
26+ * @var array<class-string, array{table: string, casts: array<string, string>, handlers: array<string, string>} >|null
2727 */
2828 private ?array $ map = null ;
2929
3030 public function getTableForEntity (string $ entityClass ): ?string
3131 {
32- return $ this ->map ()[$ entityClass ] ?? null ;
32+ return $ this ->map ()[$ entityClass ][ ' table ' ] ?? null ;
3333 }
3434
3535 /**
36- * @return array<class-string, string>
36+ * The `$casts` of the model returning this entity. CodeIgniter applies them before hydrating the
37+ * entity, so they describe the stored value of a property the entity itself does not cast.
38+ *
39+ * @return array<string, string>
40+ */
41+ public function getModelCastsForEntity (string $ entityClass ): array
42+ {
43+ return $ this ->map ()[$ entityClass ]['casts ' ] ?? [];
44+ }
45+
46+ /**
47+ * @return array<string, string>
48+ */
49+ public function getModelCastHandlersForEntity (string $ entityClass ): array
50+ {
51+ return $ this ->map ()[$ entityClass ]['handlers ' ] ?? [];
52+ }
53+
54+ /**
55+ * @return array<class-string, array{table: string, casts: array<string, string>, handlers: array<string, string>}>
3756 */
3857 private function map (): array
3958 {
@@ -52,14 +71,38 @@ private function map(): array
5271 continue ;
5372 }
5473
55- $ map [$ returnType ] = $ table ;
74+ $ map [$ returnType ] = [
75+ 'table ' => $ table ,
76+ 'casts ' => $ this ->stringMap ($ defaults ['casts ' ] ?? null ),
77+ 'handlers ' => $ this ->stringMap ($ defaults ['castHandlers ' ] ?? null ),
78+ ];
5679 }
5780
5881 $ this ->map = $ map ;
5982
6083 return $ this ->map ;
6184 }
6285
86+ /**
87+ * @return array<string, string>
88+ */
89+ private function stringMap (mixed $ value ): array
90+ {
91+ if (! is_array ($ value )) {
92+ return [];
93+ }
94+
95+ $ map = [];
96+
97+ foreach ($ value as $ key => $ cast ) {
98+ if (is_string ($ key ) && is_string ($ cast )) {
99+ $ map [$ key ] = $ cast ;
100+ }
101+ }
102+
103+ return $ map ;
104+ }
105+
63106 /**
64107 * @return list<class-string<Model>>
65108 */
0 commit comments