@@ -117,34 +117,60 @@ public function asObject():object {
117117 * @param array<mixed> $array
118118 * @return array<mixed>
119119 */
120- private function checkArrayType (array $ array , string $ type ):array {
121- $ errorMessage = "" ;
120+ private function checkArrayType (array $ array , string $ type ): array {
121+ $ this -> validateTypeExists ( $ type ) ;
122122
123- foreach ($ array as $ i => $ value ) {
124- $ actualType = is_scalar ($ value ) ? gettype ($ value ) : get_class ($ value );
123+ foreach ($ array as $ i => $ value ) {
124+ $ array [$ i ] = $ this ->processValue ($ value , $ type , $ i );
125+ }
125126
126- if (class_exists ($ type ) || interface_exists ($ type )) {
127- if (!is_a ($ value , $ type )) {
128- $ errorMessage = "Array index $ i must be of type $ type, $ actualType given " ;
129- }
130- }
131- elseif (function_exists ("is_ $ type " )) {
132- $ castedValue = match ($ type ) {
133- "int " => (int )$ value ,
134- "bool " => (bool )$ value ,
135- "string " => (string )$ value ,
136- "float " , "double " => (float )$ value ,
137- "array " => (array )$ value ,
138- default => null ,
139- };
140- $ array [$ i ] = $ castedValue ;
141- }
127+ return $ array ;
128+ }
129+
130+ private function validateTypeExists (string $ type ): void {
131+ if (!class_exists ($ type )
132+ && !interface_exists ($ type )
133+ && !function_exists ("is_ $ type " )) {
134+ throw new TypeError ("Invalid type: $ type does not exist. " );
142135 }
136+ }
143137
144- if ($ errorMessage ) {
145- throw new TypeError ($ errorMessage );
138+ private function processValue (
139+ mixed $ value ,
140+ string $ type ,
141+ int $ index ,
142+ ): mixed {
143+ if (class_exists ($ type ) || interface_exists ($ type )) {
144+ $ this ->assertInstanceOfType ($ value , $ type , $ index );
145+ } elseif (function_exists ("is_ $ type " )) {
146+ return $ this ->castValue ($ value , $ type );
146147 }
147148
148- return $ array ;
149+ return $ value ;
150+ }
151+
152+ private function assertInstanceOfType (
153+ mixed $ value ,
154+ string $ type ,
155+ int $ index ,
156+ ): void {
157+ if (!is_a ($ value , $ type )) {
158+ $ actualType = is_scalar ($ value )
159+ ? gettype ($ value )
160+ : get_class ($ value );
161+ throw new TypeError ("Array index $ index "
162+ . " must be of type $ type, $ actualType given " );
163+ }
164+ }
165+
166+ private function castValue (mixed $ value , string $ type ): mixed {
167+ return match ($ type ) {
168+ "int " => (int )$ value ,
169+ "bool " => (bool )$ value ,
170+ "string " => (string )$ value ,
171+ "float " , "double " => (float )$ value ,
172+ "array " => (array )$ value ,
173+ default => null ,
174+ };
149175 }
150176}
0 commit comments