Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\Class_\ConvertStaticToSelfRector\Fixture;

class SkipFinalDocClassConstant
{
/**
* @final
*/
public const BAR = 1;

public function run()
{
static::BAR;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

use Rector\CodeQuality\Rector\Class_\ConvertStaticToSelfRector;
use Rector\Config\RectorConfig;
use Rector\ValueObject\PhpVersionFeature;

return RectorConfig::configure()
->withRules([ConvertStaticToSelfRector::class]);
->withRules([ConvertStaticToSelfRector::class])
->withPhpVersion(PhpVersionFeature::FINAL_CLASS_CONSTANTS);
27 changes: 24 additions & 3 deletions rules/CodeQuality/Rector/Class_/ConvertStaticToSelfRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,11 @@
use PHPStan\Reflection\ClassReflection;
use Rector\Configuration\Parameter\FeatureFlags;
use Rector\Enum\ObjectReference;
use Rector\Php\PhpVersionProvider;
use Rector\PHPStan\ScopeFetcher;
use Rector\Rector\AbstractRector;
use Rector\ValueObject\PhpVersionFeature;
use ReflectionClassConstant;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;

Expand All @@ -31,6 +34,11 @@
*/
final class ConvertStaticToSelfRector extends AbstractRector
{
public function __construct(
private readonly PhpVersionProvider $phpVersionProvider
) {
}

public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Change `static::*` to `self::*` on final class or private static members', [
Expand Down Expand Up @@ -163,10 +171,23 @@ private function shouldSkip(
}

if (! $isFinal) {
$memberIsFinal = $reflection instanceof ClassConstantReflection
? $reflection->isFinal()
: $reflection->isFinalByKeyword()
// init
$memberIsFinal = false;
if ($reflection instanceof ClassConstantReflection) {
// Get the native ReflectionClassConstant
$declaringClass = $reflection->getDeclaringClass();
$nativeReflectionClass = $declaringClass->getNativeReflection();
$constantName = $reflection->getName();

if ($this->phpVersionProvider->isAtLeastPhpVersion(PhpVersionFeature::FINAL_CLASS_CONSTANTS)) {
// PHP 8.1+
$nativeReflection = $nativeReflectionClass->getReflectionConstant($constantName);
$memberIsFinal = $nativeReflection instanceof ReflectionClassConstant && $nativeReflection->isFinal();
}
} else {
$memberIsFinal = $reflection->isFinalByKeyword()
->yes();
}

// Final native members can be safely converted
if ($memberIsFinal) {
Expand Down
Loading