28
28
use CodeIgniter \Entity \Exceptions \CastException ;
29
29
use CodeIgniter \Exceptions \InvalidArgumentException ;
30
30
31
+ /**
32
+ * @template TCastHandlers of array<string, CastInterface|class-string|EntityCastInterface>
33
+ *
34
+ * @see CodeIgniter\DataCaster\DataCasterTest
35
+ * @see CodeIgniter\Entity\EntityTest
36
+ */
31
37
final class DataCaster
32
38
{
33
39
/**
@@ -38,9 +44,9 @@ final class DataCaster
38
44
private array $ types = [];
39
45
40
46
/**
41
- * Convert handlers
47
+ * Convert handlers.
42
48
*
43
- * @var array<string, class-string> [type => classname]
49
+ * @var TCastHandlers [type => classname]
44
50
*/
45
51
private array $ castHandlers = [
46
52
'array ' => ArrayCast::class,
@@ -59,18 +65,20 @@ final class DataCaster
59
65
];
60
66
61
67
/**
62
- * @param array<string, class-string> |null $castHandlers Custom convert handlers
63
- * @param array<string, string>|null $types [field => type]
64
- * @param object|null $helper Helper object.
65
- * @param bool $strict Strict mode? Set to false for casts for Entity.
68
+ * @param TCastHandlers |null $castHandlers Custom convert handlers
69
+ * @param array<string, string>|null $types [field => type]
70
+ * @param object|null $helper Helper object.
71
+ * @param bool $strict Strict mode? Set to false for casts for Entity.
66
72
*/
67
73
public function __construct (
68
74
?array $ castHandlers = null ,
69
75
?array $ types = null ,
70
76
private readonly ?object $ helper = null ,
71
77
private readonly bool $ strict = true ,
72
78
) {
73
- $ this ->castHandlers = array_merge ($ this ->castHandlers , $ castHandlers );
79
+ if ($ castHandlers !== null && $ castHandlers !== []) {
80
+ $ this ->castHandlers = array_merge ($ this ->castHandlers , $ castHandlers );
81
+ }
74
82
75
83
if ($ types !== null ) {
76
84
$ this ->setTypes ($ types );
@@ -119,6 +127,10 @@ public function setTypes(array $types): static
119
127
*/
120
128
public function castAs (mixed $ value , string $ field , string $ method = 'get ' ): mixed
121
129
{
130
+ if ($ method !== 'get ' && $ method !== 'set ' ) {
131
+ throw CastException::forInvalidMethod ($ method );
132
+ }
133
+
122
134
// If the type is not defined, return as it is.
123
135
if (! isset ($ this ->types [$ field ])) {
124
136
return $ value ;
0 commit comments