From f59a19cc8da0db14af971f8050a8d8819e13db55 Mon Sep 17 00:00:00 2001 From: Priyadi Iman Nurcahyo <1102197+priyadi@users.noreply.github.com> Date: Wed, 17 Jan 2024 14:29:31 +0700 Subject: [PATCH] perf: Optimize `guessTypeFromVariable` --- CHANGELOG.md | 1 + src/TypeResolver/TypeResolver.php | 33 +++++++++---------------------- 2 files changed, 10 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index effa751..256959e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## 0.5.15 * perf: Add caching for `TransformerRegistry`. +* perf: Optimize `guessTypeFromVariable` ## 0.5.14 diff --git a/src/TypeResolver/TypeResolver.php b/src/TypeResolver/TypeResolver.php index 79ad154..fafb25b 100644 --- a/src/TypeResolver/TypeResolver.php +++ b/src/TypeResolver/TypeResolver.php @@ -23,35 +23,20 @@ class TypeResolver implements TypeResolverInterface { public function guessTypeFromVariable(mixed $variable): Type { - if (is_object($variable)) { - return TypeFactory::objectOfClass($variable::class); - } - - if (is_null($variable)) { - return TypeFactory::null(); - } - - if (is_array($variable)) { - return TypeFactory::array(); - } - - if (is_bool($variable)) { - return TypeFactory::bool(); - } - - if (is_int($variable)) { - return TypeFactory::int(); - } + $type = get_debug_type($variable); - if (is_float($variable)) { - return TypeFactory::float(); + if (in_array($type, ['array', 'bool', 'int', 'float', 'string', 'null'])) { + return new Type($type); } - if (is_string($variable)) { - return TypeFactory::string(); + if (class_exists($type) || interface_exists($type) || \enum_exists($type)) { + return new Type( + builtinType: 'object', + class: $type, + ); } - if (is_resource($variable)) { + if (\str_starts_with($type, 'resource')) { return TypeFactory::resource(); }