Skip to content

Commit

Permalink
perf(TypeCheck): Improve isVariableInstanceOf.
Browse files Browse the repository at this point in the history
  • Loading branch information
priyadi committed Jan 17, 2024
1 parent 372f599 commit c8bc760
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 43 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
* perf: Use our `PropertyAccessLite` instead of Symfony's.
* fix(`CachingObjectMappingResolver`): Safeguard
* perf: Use flyweight pattern for `TypeFactory`
* perf(`TypeCheck`): Improve `isVariableInstanceOf`.

## 0.5.14

Expand Down
76 changes: 33 additions & 43 deletions src/Util/TypeCheck.php
Original file line number Diff line number Diff line change
Expand Up @@ -285,49 +285,39 @@ public static function isVariableInstanceOf(mixed $variable, Type|MixedType $typ
return true;
}

if (self::isObject($type)) {
$class = $type->getClassName();

if ($class !== null) {
return self::nameExists($class)
&& $variable instanceof $class;
}

return true;
}

if (self::isInt($type)) {
return is_int($variable);
}

if (self::isFloat($type)) {
return is_float($variable);
}

if (self::isString($type)) {
return is_string($variable);
}

if (self::isBool($type)) {
return is_bool($variable);
}

if (self::isArray($type)) {
return is_array($variable);
$builtinType = $type->getBuiltinType();

switch ($builtinType) {
case Type::BUILTIN_TYPE_INT:
return is_int($variable);
case Type::BUILTIN_TYPE_FLOAT:
return is_float($variable);
case Type::BUILTIN_TYPE_STRING:
return is_string($variable);
case Type::BUILTIN_TYPE_BOOL:
return is_bool($variable);
case Type::BUILTIN_TYPE_ARRAY:
return is_array($variable);
case Type::BUILTIN_TYPE_RESOURCE:
return is_resource($variable);
case Type::BUILTIN_TYPE_NULL:
return is_null($variable);
case Type::BUILTIN_TYPE_ITERABLE:
return is_iterable($variable);
case Type::BUILTIN_TYPE_OBJECT:
$class = $type->getClassName();

if ($class === null) {
return true;
}

if (!class_exists($class) && !interface_exists($class) && !enum_exists($class)) {
return false;
}

return $variable instanceof $class;
default:
throw new LogicException(sprintf('Unknown builtin type "%s"', $builtinType));
}

if (self::isResource($type)) {
return is_resource($variable);
}

if (self::isNull($type)) {
return is_null($variable);
}

if (self::isIterable($type)) {
return is_iterable($variable);
}

return false;
}
}

0 comments on commit c8bc760

Please sign in to comment.