Skip to content

Commit

Permalink
Mark as Default type if variable is passed into ClassRegistr::init
Browse files Browse the repository at this point in the history
…method
  • Loading branch information
sidz committed Jan 29, 2024
1 parent bd6b9ca commit 8121dde
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/ClassRegistryInitExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace PHPStanCakePHP2;

use PhpParser\Node\Expr\ClassConstFetch;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Name;
use PhpParser\Node\Scalar\String_;
use PHPStanCakePHP2\Service\SchemaService;
Expand Down Expand Up @@ -48,23 +49,29 @@ public function isStaticMethodSupported(MethodReflection $methodReflection): boo
public function getTypeFromStaticMethodCall(MethodReflection $methodReflection, StaticCall $methodCall, Scope $scope): ?Type
{
$value = $methodCall->getArgs()[0]->value;
$evaluator = new ConstExprEvaluator();

if ($value instanceof Variable) {
return new ObjectType('Model');
}

if ($value instanceof ClassConstFetch && $value->class instanceof Name\FullyQualified) {
$value = new String_($value->class->toString());
}

$arg1 = $evaluator->evaluateSilently($value);
$arg1 = (new ConstExprEvaluator())->evaluateSilently($value);

if (! is_string($arg1)) {
return $this->getDefaultType();
}

if ($this->reflectionProvider->hasClass($arg1)) {
return new ObjectType($arg1);
}

if ($this->schemaService->hasTable(Inflector::tableize($arg1))) {
return new ObjectType('Model');
}

return $this->getDefaultType();
}

Expand Down
4 changes: 4 additions & 0 deletions tests/Feature/data/class_registry_init.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,7 @@

$class = ClassRegistry::init(BasicModel::class);
assertType('BasicModel', $class);

$var = 'BasicModel';

assertType('Model', ClassRegistry::init($var));

0 comments on commit 8121dde

Please sign in to comment.