Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions src/Type/Php/ReflectionEnumGetCaseDynamicReturnTypeExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php declare(strict_types = 1);

namespace PHPStan\Type\Php;

use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Identifier;
use PHPStan\Analyser\Scope;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Type\DynamicMethodReturnTypeExtension;
use PHPStan\Type\ObjectType;
use PHPStan\Type\Type;

/**
* Narrows ReflectionEnum::getCase() to ReflectionEnumBackedCase once getBackingType()
* is known to be non-null (e.g. after isBacked()), which the conditional return type
* cannot express when the template type of ReflectionEnum is invariant.
*/
#[AutowiredService]
final class ReflectionEnumGetCaseDynamicReturnTypeExtension implements DynamicMethodReturnTypeExtension
{

public function getClass(): string
{
return 'ReflectionEnum';

Check failure on line 25 in src/Type/Php/ReflectionEnumGetCaseDynamicReturnTypeExtension.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, ubuntu-latest)

Method PHPStan\Type\Php\ReflectionEnumGetCaseDynamicReturnTypeExtension::getClass() should return class-string but returns string.

Check failure on line 25 in src/Type/Php/ReflectionEnumGetCaseDynamicReturnTypeExtension.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, windows-latest)

Method PHPStan\Type\Php\ReflectionEnumGetCaseDynamicReturnTypeExtension::getClass() should return class-string but returns string.
}

public function isMethodSupported(MethodReflection $methodReflection): bool
{
return $methodReflection->getName() === 'getCase';
}

public function getTypeFromMethodCall(MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope): ?Type
{
$backingType = $scope->getType(new MethodCall($methodCall->var, new Identifier('getBackingType')));
if (!$backingType->isNull()->no()) {
return null;
}

return new ObjectType('ReflectionEnumBackedCase');
}

}
4 changes: 3 additions & 1 deletion stubs/ReflectionEnumWithLazyObjects.stub
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ class ReflectionEnum extends ReflectionClass
public function getCase(string $name): ReflectionEnumUnitCase {}

/**
* @phpstan-assert-if-true self<T&BackedEnum> $this
* @phpstan-assert-if-true class-string<T&BackedEnum> $this->name
* @phpstan-assert-if-true class-string<T&BackedEnum> $this->getName()
* @phpstan-assert-if-true array<ReflectionEnumBackedCase> $this->getCases()
* @phpstan-assert-if-true !null $this->getBackingType()
*/
public function isBacked(): bool {}
Expand Down
2 changes: 1 addition & 1 deletion tests/PHPStan/Analyser/NodeScopeResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ private static function findTestFiles(): iterable
yield __DIR__ . '/data/enum-reflection-php81.php';
}

if (PHP_VERSION_ID >= 80100 && PHP_VERSION_ID < 80400) {
if (PHP_VERSION_ID >= 80100) {
yield __DIR__ . '/data/enum-reflection-backed.php';
}

Expand Down
2 changes: 1 addition & 1 deletion tests/PHPStan/Analyser/data/enum-reflection-backed.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?php // lint < 8.4
<?php // lint >= 8.1

namespace EnumReflection;

Expand Down
40 changes: 40 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-15165.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php // lint >= 8.4

namespace Bug15165Types;

use ReflectionEnum;
use UnitEnum;
use function PHPStan\Testing\assertType;

/** @param class-string<UnitEnum> $class */
function testNarrowGetNameTypeAfterIsBacked(string $class): void
{
$r = new ReflectionEnum($class);
assertType('class-string<UnitEnum>', $r->getName());
assertType('class-string<UnitEnum>', $r->name);
assertType('ReflectionNamedType|null', $r->getBackingType());
assertType('array<ReflectionEnumUnitCase>', $r->getCases());
assertType('ReflectionEnumUnitCase', $r->getCase('A'));
if ($r->isBacked()) {
assertType('array<ReflectionEnumBackedCase>', $r->getCases());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should in addition assert the type for $r->getCase(), before and after $r->isBacked()

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added the getCase() assertions to the test, before and after isBacked(). To make the "after" case come out right, I also added a small extension so getCase() now actually narrows. Both are in one local commit, not pushed. make tests and make phpstan both pass.

Tests (tests/PHPStan/Analyser/nsrt/bug-15165.php):

  • ReflectionEnum<UnitEnum>: getCase('A') is ReflectionEnumUnitCase before isBacked() and ReflectionEnumBackedCase inside if ($r->isBacked()).
  • Templated ReflectionEnum<T of UnitEnum>: the same two types, before and after.

The extension: before this, getCase() stayed ReflectionEnumUnitCase after isBacked(), so the "after" check would only have recorded a wrong result. A docblock assertion can't fix this, because it doesn't apply to getCase($name) calls that pass an argument. So I added src/Type/Php/ReflectionEnumGetCaseDynamicReturnTypeExtension.php. When the current scope already knows that getBackingType() on the same enum isn't null (which is what isBacked() returning true tells it), getCase() returns ReflectionEnumBackedCase. Otherwise it changes nothing. The new "after isBacked()" checks fail without the extension (they get ReflectionEnumUnitCase) and pass with it.

The extension also runs on PHP < 8.4. There the older stub already narrows getCase(), and the extension gives the same answer, so nothing should change. I only ran the tests on PHP 8.4, though, and the new test file only runs on 8.4+, so CI will be the first check on 8.1–8.3.

If you'd rather keep the extension out of this PR, I can drop it and only assert the current type, ReflectionEnumUnitCase.

assertType('ReflectionEnumBackedCase', $r->getCase('A'));
assertType('class-string<BackedEnum>', $r->getName());
assertType('class-string<BackedEnum>', $r->name);
assertType('ReflectionNamedType', $r->getBackingType());
}
}

/**
* @template T of UnitEnum
* @param ReflectionEnum<T> $enum
*/
function testTemplate(ReflectionEnum $enum): void
{
assertType('ReflectionEnumUnitCase', $enum->getCase('A'));
if ($enum->isBacked()) {
assertType('ReflectionEnum<T of UnitEnum (function Bug15165Types\testTemplate(), argument)>', $enum);
assertType('ReflectionNamedType', $enum->getBackingType());
assertType('array<ReflectionEnumBackedCase>', $enum->getCases());
assertType('ReflectionEnumBackedCase', $enum->getCase('A'));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use PHPStan\Testing\RuleTestCase;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\RequiresPhp;
use const PHP_VERSION_ID;

/**
* @extends RuleTestCase<CompositeRule>
Expand Down Expand Up @@ -346,6 +347,19 @@ public function testBug14705(): void
]);
}

#[RequiresPhp('>= 8.1.0')]
public function testBug15165(): void
{
$this->treatPhpDocTypesAsCertain = true;
$this->analyse([__DIR__ . '/data/bug-15165.php'], [
[
'Call to method ReflectionEnum<Bug15165\\UnitFoo>::isBacked() will always evaluate to false.',
58,
PHP_VERSION_ID >= 80400 ? 'Because the type is coming from a PHPDoc, you can turn off this check by setting <fg=cyan>treatPhpDocTypesAsCertain: false</> in your <fg=cyan>%configurationFile%</>.' : null,
],
]);
}

public function testInTrait(): void
{
$this->treatPhpDocTypesAsCertain = true;
Expand Down
66 changes: 66 additions & 0 deletions tests/PHPStan/Rules/Comparison/data/bug-15165.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php // lint >= 8.1

namespace Bug15165;

use BackedEnum;
use ReflectionEnum;
use UnitEnum;

/**
* @template T of UnitEnum
* @param ReflectionEnum<T> $enum
* @return void
*/
function testUnit(ReflectionEnum $enum): void
{
if ($enum->isBacked()) {
echo "Backed!";
}
}

/**
* @template T of BackedEnum
* @param ReflectionEnum<T> $enum
* @return void
*/
function testBacked(ReflectionEnum $enum): void
{
if (!$enum->isBacked()) {
echo "Unit!";
}
}

/**
* @template T of BackedEnum|UnitEnum
* @param ReflectionEnum<T> $enum
* @return void
*/
function testAny(ReflectionEnum $enum): void
{
if ($enum->isBacked()) {
echo "Backed!";
}
}

enum UnitFoo
{
case A;
}

enum BackedFoo: int
{
case A = 1;
}

function testConcrete(): void
{
$unit = new ReflectionEnum(UnitFoo::class);
if ($unit->isBacked()) {
echo "Backed!";
}

$backed = new ReflectionEnum(BackedFoo::class);
if ($backed->isBacked()) {
echo "Backed!";
}
}
Loading