如何阻止Rector内联类引用?PHP 7.4版本升级场景
Rector PHP7.4升级相关问题解答
1. 配置Rector优先使用use语句而非内联全限定类引用
可以通过调整Rector配置实现,核心是控制类型转换规则的行为,优先使用已导入的短类名:
在rector.php配置文件中添加以下内容:
use Rector\Config\RectorConfig; use Rector\CodingStyle\Rector\Namespace_\ImportNamesRector; use Rector\Set\ValueObject\LevelSetList; use Rector\TypeDeclaration\Rector\Property\TypedPropertyFromCommentRector; return static function (RectorConfig $rectorConfig): void { $rectorConfig->import(LevelSetList::UP_TO_PHP_74); // 启用类名导入规则,优先使用已存在的use语句 $rectorConfig->ruleWithConfiguration(ImportNamesRector::class, [ ImportNamesRector::IMPORT_SHORT_CLASSES => true, ImportNamesRector::IMPORT_USE_TRAILING_COMMA => true, ]); // 控制属性类型转换规则,不生成全限定类名 $rectorConfig->ruleWithConfiguration(TypedPropertyFromCommentRector::class, [ TypedPropertyFromCommentRector::INLINE_TYPE_USE_FULL_QUALIFIED_NAME => false, ]); };
该配置会让Rector将@var注释转换为类型声明时,采用已通过use导入的短类名,而非内联全限定类名。
2. 排除问题规则,保留其他规则运行
如果上述配置无效,可直接排除触发转换的具体规则(通常是TypedPropertyFromCommentRector),在rector.php中添加:
use Rector\Config\RectorConfig; use Rector\Set\ValueObject\LevelSetList; use Rector\TypeDeclaration\Rector\Property\TypedPropertyFromCommentRector; return static function (RectorConfig $rectorConfig): void { $rectorConfig->import(LevelSetList::UP_TO_PHP_74); // 排除生成内联全限定类型的规则 $rectorConfig->excludeRule(TypedPropertyFromCommentRector::class); };
这样其他UP_TO_PHP_74规则会正常执行,仅跳过导致问题的属性类型转换规则。
3. 使用PHP CS Fixer将内联全限定类引用转回use语句形式
PHP CS Fixer有对应的规则可自动修复这类问题,在.php-cs-fixer.php配置文件中添加以下规则:
return (new PhpCsFixer\Config()) ->setRules([ // 自动导入类名,将内联全限定类名转换为短名,缺少use语句时自动添加 'import_names' => true, // 移除内联类型或use语句中的前导斜杠 'no_leading_import_slash' => true, // 禁用严格类型的全限定要求,强制使用短类名 'fully_qualified_strict_types' => false, ]) ->setFinder(PhpCsFixer\Finder::create()->in(__DIR__));
运行PHP CS Fixer命令后,会自动将内联的\My\Namespace\My\Classname转换为短类名,并确保对应的use语句存在(无则添加),同时清理非法的前导斜杠。
内容的提问来源于stack exchange,提问作者Mayor of the Plattenbaus
相关产品推荐
相关产品推荐

