2828use CodeIgniter \Entity \Exceptions \CastException ;
2929use CodeIgniter \Exceptions \InvalidArgumentException ;
3030
31+ /**
32+ * @phpstan-type cast_handlers array<string, class-string<EntityCastInterface|CastInterface>>
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 cast_handlers [type => classname]
4450 */
4551 private array $ castHandlers = [
4652 'array ' => ArrayCast::class,
@@ -59,18 +65,18 @@ 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 cast_handlers |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+ $ this ->castHandlers = array_merge ($ this ->castHandlers , $ castHandlers ?? [] );
7480
7581 if ($ types !== null ) {
7682 $ this ->setTypes ($ types );
@@ -113,12 +119,16 @@ public function setTypes(array $types): static
113119 * Add ? at the beginning of the type (i.e. ?string) to get `null`
114120 * instead of casting $value when $value is null.
115121 *
116- * @param mixed $value The value to convert
117- * @param string $field The field name
118- * @param 'get'|'set' $method Allowed to "get" and "set"
122+ * @param mixed $value The value to convert
123+ * @param string $field The field name
124+ * @param string $method Allowed to "get" and "set"
119125 */
120126 public function castAs (mixed $ value , string $ field , string $ method = 'get ' ): mixed
121127 {
128+ if ($ method !== 'get ' && $ method !== 'set ' ) {
129+ throw CastException::forInvalidMethod ($ method );
130+ }
131+
122132 // If the type is not defined, return as it is.
123133 if (! isset ($ this ->types [$ field ])) {
124134 return $ value ;
0 commit comments