Skip to content

Commit

Permalink
Do not infer anything when context is falsy
Browse files Browse the repository at this point in the history
  • Loading branch information
VincentLanglet committed Mar 27, 2022
1 parent a355aaa commit 6523471
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 5 deletions.
7 changes: 2 additions & 5 deletions src/Type/Php/IsSubclassOfFunctionTypeSpecifyingExtension.php
Expand Up @@ -29,23 +29,20 @@ public function __construct(
public function isFunctionSupported(FunctionReflection $functionReflection, FuncCall $node, TypeSpecifierContext $context): bool
{
return strtolower($functionReflection->getName()) === 'is_subclass_of'
&& !$context->null();
&& $context->truthy();
}

public function specifyTypes(FunctionReflection $functionReflection, FuncCall $node, Scope $scope, TypeSpecifierContext $context): SpecifiedTypes
{
if (count($node->getArgs()) < 2) {
return new SpecifiedTypes();
}

$objectOrClassType = $scope->getType($node->getArgs()[0]->value);
$classType = $scope->getType($node->getArgs()[1]->value);
$allowStringType = isset($node->getArgs()[2]) ? $scope->getType($node->getArgs()[2]->value) : new ConstantBooleanType(true);
$allowString = !$allowStringType->equals(new ConstantBooleanType(false));

if (!$classType instanceof ConstantStringType && !$context->truthy()) {
return new SpecifiedTypes([], []);
}

return $this->typeSpecifier->create(
$node->getArgs()[0]->value,
$this->isAFunctionTypeSpecifyingHelper->determineType($objectOrClassType, $classType, $allowString, false),
Expand Down
Expand Up @@ -471,6 +471,13 @@ public function testBug6698(): void
$this->analyse([__DIR__ . '/data/bug-6698.php'], []);
}

public function testBug6891(): void
{
$this->checkAlwaysTrueCheckTypeFunctionCall = true;
$this->treatPhpDocTypesAsCertain = true;
$this->analyse([__DIR__ . '/data/bug-6891.php'], []);
}

public function testBug5369(): void
{
$this->checkAlwaysTrueCheckTypeFunctionCall = true;
Expand Down
49 changes: 49 additions & 0 deletions tests/PHPStan/Rules/Comparison/data/bug-6891.php
@@ -0,0 +1,49 @@
<?php declare(strict_types = 1);

namespace Comparison\Bug6891;

class HelloWorld
{

/**
* @param mixed $context
*/
public function sayHello($context): bool
{
if (is_subclass_of($context, HelloWorld::class)) {
return true;
}

return HelloWorld::class === $context;
}

/**
* @param mixed $context
*/
public function sayHello2($context): bool
{
if (is_subclass_of($context, HelloWorld::class)) {
return true;
}

return HelloWorld::class === get_class($context);
}

public function sayHello3(object $context): bool
{
if (is_subclass_of($context, HelloWorld::class)) {
return true;
}

return HelloWorld::class === get_class($context);
}

public function sayHello4(string $context): bool
{
if (is_subclass_of($context, HelloWorld::class)) {
return true;
}

return HelloWorld::class === $context;
}
}

0 comments on commit 6523471

Please sign in to comment.