Last active
January 14, 2022 11:53
-
-
Save dhrrgn/11271702 to your computer and use it in GitHub Desktop.
PHP Type Check Function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Checks the type of the given value against an array of valid types. | |
* | |
* If the value is a valid type, `true` is returned, if not, an | |
* InvalidArgumentException is thrown. | |
* | |
* // Throws: Invalid type: string, Expected type(s): array, ArrayAccess | |
* checktype('foo', ['array', 'ArrayAccess']); | |
* | |
* @param mixed $value | |
* @param array $validTypes | |
* @return bool | |
* @throws \InvalidArgumentException | |
*/ | |
function checktype($value, array $validTypes) | |
{ | |
$nativeTypes = [ | |
'array' => 'is_array', | |
'bool' => 'is_bool', | |
'callable' => 'is_callable', | |
'double' => 'is_double', | |
'float' => 'is_float', | |
'int' => 'is_int', | |
'integer' => 'is_integer', | |
'long' => 'is_long', | |
'null' => 'is_null', | |
'numeric' => 'is_numeric', | |
'object' => 'is_object', | |
'real' => 'is_real', | |
'resource' => 'is_resource', | |
'scalar' => 'is_scalar', | |
'string' => 'is_string', | |
]; | |
$valid = false; | |
foreach ($validTypes as $type) { | |
if (isset($nativeTypes[$type])) { | |
$valid = call_user_func($nativeTypes[$type], $value); | |
} else { | |
$valid = $value instanceof $type; | |
} | |
if ($valid) { | |
break; | |
} | |
} | |
if (!$valid) { | |
$type = gettype($value); | |
if (gettype($value) === 'object') { | |
$type = get_class($value); | |
} | |
throw new InvalidArgumentException('Invalid type: '.$type.', Expected type(s): '.implode(', ', $validTypes)); | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you are curious as to why I went with
checktype
as the name, it is so it was consistent with the nativegettype
function.