|
16 | 16 | use PHPStan\Reflection\ClassReflection; |
17 | 17 | use Rector\Configuration\Parameter\FeatureFlags; |
18 | 18 | use Rector\Enum\ObjectReference; |
| 19 | +use Rector\Php\PhpVersionProvider; |
19 | 20 | use Rector\PHPStan\ScopeFetcher; |
20 | 21 | use Rector\Rector\AbstractRector; |
| 22 | +use Rector\ValueObject\PhpVersionFeature; |
| 23 | +use ReflectionClassConstant; |
21 | 24 | use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample; |
22 | 25 | use Symplify\RuleDocGenerator\ValueObject\RuleDefinition; |
23 | 26 |
|
|
31 | 34 | */ |
32 | 35 | final class ConvertStaticToSelfRector extends AbstractRector |
33 | 36 | { |
| 37 | + public function __construct( |
| 38 | + private readonly PhpVersionProvider $phpVersionProvider |
| 39 | + ) { |
| 40 | + } |
| 41 | + |
34 | 42 | public function getRuleDefinition(): RuleDefinition |
35 | 43 | { |
36 | 44 | return new RuleDefinition('Change `static::*` to `self::*` on final class or private static members', [ |
@@ -163,10 +171,24 @@ private function shouldSkip( |
163 | 171 | } |
164 | 172 |
|
165 | 173 | 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() |
169 | 190 | ->yes(); |
| 191 | + } |
170 | 192 |
|
171 | 193 | // Final native members can be safely converted |
172 | 194 | if ($memberIsFinal) { |
|
0 commit comments