Skip to content

Commit

Permalink
Merge pull request #4 from sidz/fix-error-occured-if-not-a-string-pas…
Browse files Browse the repository at this point in the history
…sed-into-init

Fix error occurred when not a string is passed into ClassRegistry::init method
  • Loading branch information
sidz authored Jan 29, 2024
2 parents 467dd97 + e8a3efe commit 2fe3af0
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 17 deletions.
26 changes: 10 additions & 16 deletions src/ClassRegistryInitExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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');
}

Expand All @@ -79,7 +73,7 @@ private function getDefaultType(): Type
{
return new UnionType([
new BooleanType(),
new ObjectWithoutClassType()
new ObjectWithoutClassType(),
]);
}
}
4 changes: 3 additions & 1 deletion tests/Feature/data/class_registry_init.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,6 @@

$var = 'BasicModel';

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

assertType('bool|object', ClassRegistry::init([123]));

0 comments on commit 2fe3af0

Please sign in to comment.