2828use CodeIgniter \Entity \Exceptions \CastException ;
2929use CodeIgniter \Exceptions \InvalidArgumentException ;
3030
31+ /**
32+ * @template TCastHandlers of array<string, CastInterface|class-string|EntityCastInterface>
33+ *
34+ * @see CodeIgniter\DataCaster\DataCasterTest
35+ * @see CodeIgniter\Entity\EntityTest
36+ */
3137final class DataCaster
3238{
3339 /**
@@ -38,9 +44,9 @@ final class DataCaster
3844 private array $ types = [];
3945
4046 /**
41- * Convert handlers
47+ * Convert handlers.
4248 *
43- * @var array<string, class-string> [type => classname]
49+ * @var TCastHandlers [type => classname]
4450 */
4551 private array $ castHandlers = [
4652 'array ' => ArrayCast::class,
@@ -59,18 +65,20 @@ final class DataCaster
5965 ];
6066
6167 /**
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.
6672 */
6773 public function __construct (
6874 ?array $ castHandlers = null ,
6975 ?array $ types = null ,
7076 private readonly ?object $ helper = null ,
7177 private readonly bool $ strict = true ,
7278 ) {
73- $ this ->castHandlers = array_merge ($ this ->castHandlers , $ castHandlers );
79+ if ($ castHandlers !== null && $ castHandlers !== []) {
80+ $ this ->castHandlers = array_merge ($ this ->castHandlers , $ castHandlers );
81+ }
7482
7583 if ($ types !== null ) {
7684 $ this ->setTypes ($ types );
@@ -119,6 +127,10 @@ public function setTypes(array $types): static
119127 */
120128 public function castAs (mixed $ value , string $ field , string $ method = 'get ' ): mixed
121129 {
130+ if ($ method !== 'get ' && $ method !== 'set ' ) {
131+ throw CastException::forInvalidMethod ($ method );
132+ }
133+
122134 // If the type is not defined, return as it is.
123135 if (! isset ($ this ->types [$ field ])) {
124136 return $ value ;
0 commit comments