Skip to content

Commit 1bf37b9

Browse files
committed
Adjust UnusedPrivateConstantRule for dynamic class constants
1 parent 1e32f7c commit 1bf37b9

File tree

3 files changed

+62
-3
lines changed

3 files changed

+62
-3
lines changed

src/Rules/DeadCode/UnusedPrivateConstantRule.php

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,6 @@ public function processNode(Node $node, Scope $scope): array
5757

5858
foreach ($node->getFetches() as $fetch) {
5959
$fetchNode = $fetch->getNode();
60-
if (!$fetchNode->name instanceof Node\Identifier) {
61-
continue;
62-
}
6360

6461
$fetchScope = $fetch->getScope();
6562
if ($fetchNode->class instanceof Node\Name) {
@@ -68,6 +65,14 @@ public function processNode(Node $node, Scope $scope): array
6865
$fetchedOnClass = $fetchScope->getType($fetchNode->class);
6966
}
7067

68+
if (!$fetchNode->name instanceof Node\Identifier) {
69+
if (!$classType->isSuperTypeOf($fetchedOnClass)->no()) {
70+
$constants = [];
71+
break;
72+
}
73+
continue;
74+
}
75+
7176
$constantReflection = $fetchScope->getConstantReflection($fetchedOnClass, $fetchNode->name->toString());
7277
if ($constantReflection === null) {
7378
if (!$classType->isSuperTypeOf($fetchedOnClass)->no()) {

tests/PHPStan/Rules/DeadCode/UnusedPrivateConstantRuleTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,4 +97,19 @@ public function testBug9765(): void
9797
$this->analyse([__DIR__ . '/data/bug-9765.php'], []);
9898
}
9999

100+
public function testDynamicConstantFetch(): void
101+
{
102+
if (PHP_VERSION_ID < 80300) {
103+
$this->markTestSkipped('Test requires PHP 8.3.');
104+
}
105+
106+
$this->analyse([__DIR__ . '/data/unused-private-constant-dynamic-fetch.php'], [
107+
[
108+
'Constant UnusedPrivateConstantDynamicFetch\Baz::FOO is unused.',
109+
32,
110+
'See: https://phpstan.org/developing-extensions/always-used-class-constants',
111+
],
112+
]);
113+
}
114+
100115
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<?php // lint >= 8.3
2+
3+
namespace UnusedPrivateConstantDynamicFetch;
4+
5+
class Foo
6+
{
7+
8+
private const FOO = 1;
9+
10+
public function doFoo(string $s): void
11+
{
12+
echo self::{$s};
13+
}
14+
15+
}
16+
17+
class Bar
18+
{
19+
20+
private const FOO = 1;
21+
22+
public function doFoo(self $a, string $s): void
23+
{
24+
echo $a::{$s};
25+
}
26+
27+
}
28+
29+
class Baz
30+
{
31+
32+
private const FOO = 1;
33+
34+
public function doFoo(\stdClass $a, string $s): void
35+
{
36+
echo $a::{$s};
37+
}
38+
39+
}

0 commit comments

Comments
 (0)