Skip to content

Commit

Permalink
Prevent false-positive in get_parent_class() on interfaces
Browse files Browse the repository at this point in the history
  • Loading branch information
staabm authored Apr 19, 2023
1 parent b8ff8ea commit 532094b
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,15 @@ private function findParentClassNameType(string $className): Type
]);
}

return $this->findParentClassType($this->reflectionProvider->getClass($className));
$classReflection = $this->reflectionProvider->getClass($className);
if ($classReflection->isInterface()) {
return new UnionType([
new ClassStringType(),
new ConstantBooleanType(false),
]);
}

return $this->findParentClassType($classReflection);
}

private function findParentClassType(
Expand Down
1 change: 1 addition & 0 deletions tests/PHPStan/Analyser/NodeScopeResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1244,6 +1244,7 @@ public function dataFileAsserts(): iterable
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-9062.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/object-shape.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/memcache-get.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-4302b.php');
}

/**
Expand Down
20 changes: 20 additions & 0 deletions tests/PHPStan/Analyser/data/bug-4302b.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php declare(strict_types = 1);

namespace Bug4302b;

use function PHPStan\Testing\assertType;

class HelloWorld
{
public function theMethod(MyInterface $interface, MyClass $class, MySubClass $subclass) {
assertType('class-string|false', get_parent_class($interface));
assertType('false', get_parent_class($class));
assertType("'Bug4302b\\\\MyClass'", get_parent_class($subclass));
}
}

interface MyInterface {}

class MyClass implements MyInterface {}

class MySubClass extends MyClass {}
Original file line number Diff line number Diff line change
Expand Up @@ -144,4 +144,10 @@ public function testBug8485(): void
$this->analyse([__DIR__ . '/data/bug-8485.php'], []);
}

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

}
14 changes: 14 additions & 0 deletions tests/PHPStan/Rules/Comparison/data/bug-4302.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php declare(strict_types = 1);

namespace Bug4302;

class HelloWorld
{
public function theMethod(MyInterface $object) {
if (get_parent_class($object)) {
return 1;
}
}
}

interface MyInterface {}

0 comments on commit 532094b

Please sign in to comment.