Skip to content

Commit

Permalink
Adjust UnusedPrivateConstantRule for dynamic class constants
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Nov 20, 2023
1 parent 1e32f7c commit 1bf37b9
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/Rules/DeadCode/UnusedPrivateConstantRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,6 @@ public function processNode(Node $node, Scope $scope): array

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

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

if (!$fetchNode->name instanceof Node\Identifier) {
if (!$classType->isSuperTypeOf($fetchedOnClass)->no()) {
$constants = [];
break;
}
continue;
}

$constantReflection = $fetchScope->getConstantReflection($fetchedOnClass, $fetchNode->name->toString());
if ($constantReflection === null) {
if (!$classType->isSuperTypeOf($fetchedOnClass)->no()) {
Expand Down
15 changes: 15 additions & 0 deletions tests/PHPStan/Rules/DeadCode/UnusedPrivateConstantRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,19 @@ public function testBug9765(): void
$this->analyse([__DIR__ . '/data/bug-9765.php'], []);
}

public function testDynamicConstantFetch(): void
{
if (PHP_VERSION_ID < 80300) {
$this->markTestSkipped('Test requires PHP 8.3.');
}

$this->analyse([__DIR__ . '/data/unused-private-constant-dynamic-fetch.php'], [
[
'Constant UnusedPrivateConstantDynamicFetch\Baz::FOO is unused.',
32,
'See: https://phpstan.org/developing-extensions/always-used-class-constants',
],
]);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php // lint >= 8.3

namespace UnusedPrivateConstantDynamicFetch;

class Foo
{

private const FOO = 1;

public function doFoo(string $s): void
{
echo self::{$s};
}

}

class Bar
{

private const FOO = 1;

public function doFoo(self $a, string $s): void
{
echo $a::{$s};
}

}

class Baz
{

private const FOO = 1;

public function doFoo(\stdClass $a, string $s): void
{
echo $a::{$s};
}

}

0 comments on commit 1bf37b9

Please sign in to comment.