From e8a3efe90d7d6c4a4eb8f357ec5a3818717e94d6 Mon Sep 17 00:00:00 2001 From: Oleg Zhulnev Date: Mon, 29 Jan 2024 18:13:07 +0300 Subject: [PATCH] Fix error occurred when not a string is passed into `ClassRegistry::init` method --- src/ClassRegistryInitExtension.php | 26 +++++++++------------- tests/Feature/data/class_registry_init.php | 4 +++- 2 files changed, 13 insertions(+), 17 deletions(-) diff --git a/src/ClassRegistryInitExtension.php b/src/ClassRegistryInitExtension.php index 409623f..97cbe8e 100644 --- a/src/ClassRegistryInitExtension.php +++ b/src/ClassRegistryInitExtension.php @@ -4,10 +4,12 @@ namespace PHPStanCakePHP2; +use PhpParser\Node\Expr; use PhpParser\Node\Expr\ClassConstFetch; use PhpParser\Node\Expr\Variable; use PhpParser\Node\Name; use PhpParser\Node\Scalar\String_; +use PHPStan\Type\Constant\ConstantStringType; use PHPStanCakePHP2\Service\SchemaService; use Inflector; use PhpParser\ConstExprEvaluator; @@ -48,27 +50,19 @@ public function isStaticMethodSupported(MethodReflection $methodReflection): boo public function getTypeFromStaticMethodCall(MethodReflection $methodReflection, StaticCall $methodCall, Scope $scope): ?Type { - $value = $methodCall->getArgs()[0]->value; + $argumentType = $scope->getType($methodCall->getArgs()[0]->value); - if ($value instanceof Variable) { - return new ObjectType('Model'); - } - - if ($value instanceof ClassConstFetch && $value->class instanceof Name\FullyQualified) { - $value = new String_($value->class->toString()); - } - - $arg1 = (new ConstExprEvaluator())->evaluateSilently($value); - - if (! is_string($arg1)) { + if (!$argumentType instanceof ConstantStringType) { return $this->getDefaultType(); } - if ($this->reflectionProvider->hasClass($arg1)) { - return new ObjectType($arg1); + $value = $argumentType->getValue(); + + if ($this->reflectionProvider->hasClass($value)) { + return new ObjectType($value); } - if ($this->schemaService->hasTable(Inflector::tableize($arg1))) { + if ($this->schemaService->hasTable(Inflector::tableize($value))) { return new ObjectType('Model'); } @@ -79,7 +73,7 @@ private function getDefaultType(): Type { return new UnionType([ new BooleanType(), - new ObjectWithoutClassType() + new ObjectWithoutClassType(), ]); } } diff --git a/tests/Feature/data/class_registry_init.php b/tests/Feature/data/class_registry_init.php index 54dcd20..57ca51c 100644 --- a/tests/Feature/data/class_registry_init.php +++ b/tests/Feature/data/class_registry_init.php @@ -18,4 +18,6 @@ $var = 'BasicModel'; -assertType('Model', ClassRegistry::init($var)); +assertType('BasicModel', ClassRegistry::init($var)); + +assertType('bool|object', ClassRegistry::init([123]));