Skip to content

Commit f3c66c1

Browse files
committed
[CodeQuality] Skip @Final doc with public class constant on ConvertStaticToSelfRector
1 parent 1bcddc7 commit f3c66c1

File tree

2 files changed

+41
-3
lines changed

2 files changed

+41
-3
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<?php
2+
3+
namespace Rector\Tests\CodeQuality\Rector\Class_\ConvertStaticToSelfRector\Fixture;
4+
5+
class SkipFinalDocClassConstant
6+
{
7+
/**
8+
* @final
9+
*/
10+
public const BAR = 1;
11+
12+
public function run()
13+
{
14+
static::BAR;
15+
}
16+
}

rules/CodeQuality/Rector/Class_/ConvertStaticToSelfRector.php

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,11 @@
1616
use PHPStan\Reflection\ClassReflection;
1717
use Rector\Configuration\Parameter\FeatureFlags;
1818
use Rector\Enum\ObjectReference;
19+
use Rector\Php\PhpVersionProvider;
1920
use Rector\PHPStan\ScopeFetcher;
2021
use Rector\Rector\AbstractRector;
22+
use Rector\ValueObject\PhpVersionFeature;
23+
use ReflectionClassConstant;
2124
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
2225
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
2326

@@ -31,6 +34,11 @@
3134
*/
3235
final class ConvertStaticToSelfRector extends AbstractRector
3336
{
37+
public function __construct(
38+
private readonly PhpVersionProvider $phpVersionProvider
39+
) {
40+
}
41+
3442
public function getRuleDefinition(): RuleDefinition
3543
{
3644
return new RuleDefinition('Change `static::*` to `self::*` on final class or private static members', [
@@ -163,10 +171,24 @@ private function shouldSkip(
163171
}
164172

165173
if (! $isFinal) {
166-
$memberIsFinal = $reflection instanceof ClassConstantReflection
167-
? $reflection->isFinal()
168-
: $reflection->isFinalByKeyword()
174+
if ($reflection instanceof ClassConstantReflection) {
175+
// Get the native ReflectionClassConstant
176+
$declaringClass = $reflection->getDeclaringClass();
177+
$nativeReflectionClass = $declaringClass->getNativeReflection();
178+
$constantName = $reflection->getName();
179+
180+
if ($this->phpVersionProvider->isAtLeastPhpVersion(PhpVersionFeature::FINAL_CLASS_CONSTANTS)) {
181+
// PHP 8.1+
182+
$nativeReflection = $nativeReflectionClass->getReflectionConstant($constantName);
183+
$memberIsFinal = $nativeReflection instanceof ReflectionClassConstant && $nativeReflection->isFinal();
184+
} else {
185+
// On PHP < 8.1, class constants can't be final
186+
$memberIsFinal = false;
187+
}
188+
} else {
189+
$memberIsFinal = $reflection->isFinalByKeyword()
169190
->yes();
191+
}
170192

171193
// Final native members can be safely converted
172194
if ($memberIsFinal) {

0 commit comments

Comments
 (0)