Skip to content

Commit 9ce8faf

Browse files
committed
Make ReflectionEnum generic
1 parent 58d53bf commit 9ce8faf

File tree

4 files changed

+65
-0
lines changed

4 files changed

+65
-0
lines changed

conf/config.neon

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ parameters:
3535
- InfiniteIterator
3636
- CachingIterator
3737
- RegexIterator
38+
- ReflectionEnum
3839
explicitMixedInUnknownGenericNew: false
3940
explicitMixedForGlobalVariables: false
4041
explicitMixedViaIsArray: false

stubs/ReflectionClass.stub

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,3 +48,23 @@ class ReflectionClass
4848
{
4949
}
5050
}
51+
52+
/**
53+
* @template-covariant T of UnitEnum
54+
* @extends ReflectionClass<T>
55+
*/
56+
class ReflectionEnum extends ReflectionClass
57+
{
58+
59+
/**
60+
* @return (T is BackedEnum ? ReflectionEnumBackedCase[] : ReflectionEnumUnitCase[])
61+
*/
62+
public function getCases(): array {}
63+
64+
/**
65+
* @return (T is BackedEnum ? ReflectionEnumBackedCase : ReflectionEnumUnitCase)
66+
* @throws ReflectionException If no found single reflection object for the corresponding case
67+
*/
68+
public function getCase(string $name): ReflectionEnumUnitCase {}
69+
70+
}

tests/PHPStan/Analyser/NodeScopeResolverTest.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,7 @@ public function dataFileAsserts(): iterable
240240

241241
if (PHP_VERSION_ID >= 80100) {
242242
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-9734.php');
243+
yield from $this->gatherAssertTypes(__DIR__ . '/data/enum-reflection.php');
243244
}
244245

245246
yield from $this->gatherAssertTypes(__DIR__ . '/data/match-expr.php');
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
<?php // lint >= 8.1
2+
3+
namespace EnumReflection;
4+
5+
use ReflectionEnum;
6+
use ReflectionEnumBackedCase;
7+
use ReflectionEnumUnitCase;
8+
use function PHPStan\Testing\assertType;
9+
10+
enum Foo: int
11+
{
12+
13+
case FOO = 1;
14+
case BAR = 2;
15+
16+
public function doFoo(): void
17+
{
18+
$r = new ReflectionEnum(self::class);
19+
foreach ($r->getCases() as $case) {
20+
assertType(ReflectionEnumBackedCase::class, $case);
21+
}
22+
23+
assertType(ReflectionEnumBackedCase::class, $r->getCase('FOO'));
24+
}
25+
26+
}
27+
28+
enum Bar
29+
{
30+
31+
case FOO;
32+
case BAR;
33+
34+
public function doFoo(): void
35+
{
36+
$r = new ReflectionEnum(self::class);
37+
foreach ($r->getCases() as $case) {
38+
assertType(ReflectionEnumUnitCase::class, $case);
39+
}
40+
assertType(ReflectionEnumUnitCase::class, $r->getCase('FOO'));
41+
}
42+
43+
}

0 commit comments

Comments
 (0)