You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP Rector执行失败:无法重命名临时文件,求解决方案

Rector在Windows下执行重构时文件重命名权限错误的解决办法

问题场景

使用Rector自定义规则替换utf8_decode()、utf8_encode()为自定义函数,相关代码及配置如下:

rector.php配置文件

<?php
declare(strict_types=1);

use Rector\Config\RectorConfig;
use Utils\Rector\ReplaceUTF8Functions;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->paths([
        __DIR__ . \DIRECTORY_SEPARATOR . 'service.php'
    ]);
    $rectorConfig->rule(ReplaceUTF8Functions::class);;
};

自定义规则类ReplaceUTF8Functions

<?php
namespace Utils\Rector;

use PhpParser\Node;
use PhpParser\Node\Name;
use PhpParser\Node\Expr\FuncCall;
use Rector\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
use function array_key_exists;

final class ReplaceUTF8Functions extends AbstractRector {

    private const REPLACEMENT = [
        'utf8_decode' => 'utf8ToLatin1',
        'utf8_encode' => 'latin1ToUtf8'
    ];

    public function getNodeTypes(): array {
        return [
            FuncCall::class
        ];
    }

    /**
     * @param FuncCall $node
     * @return null|Node
     */
    public function refactor(Node $node): ?Node {
        $name = $this->getName($node->name);
        if (!array_key_exists($name, self::REPLACEMENT))
            return null;
        $node->name = new Name(self::REPLACEMENT[$name]);
        return $node;
    }

    public function getRuleDefinition(): RuleDefinition {
        return new RuleDefinition('Replace the utf8_* functions with custom counterparts', [
                new CodeSample(
                    'utf8_decode(\'string\');',
                    'utf8ToLatin1(\'string\');'
                )
            ]
        );
    }
}

执行命令vendor\bin\rector process时触发权限错误:

cts\trunk\service.php" file, due to:
    "System error: "Cannot rename "C:\Projects\trunk\ser8FA1.tmp" to
    "C:\Projects\trunk\service.php":
    rename(C:\Projects\trunk\ser8FA1.tmp,C:\Projects\trunk\service.php): Zugriff verweigert (code:

    Run Rector with "--debug" option and post the report here: https://github.com/rectorphp/rector/issues/new". On line: 286

Script rector handling the __exec_command event returned with error code 1

已尝试给目标文件分配全权限、以管理员身份运行命令,问题仍未解决。

可行解决办法

  • 关闭占用目标文件的进程:Windows下文件被IDE(如PHPStorm、VS Code)、编辑器或调试工具锁定时,会导致重命名失败,关闭相关程序后重试。
  • 自定义Rector临时文件目录:在rector.php中配置临时文件路径到非项目目录,比如系统临时文件夹:
    $rectorConfig->tempDirectory(sys_get_temp_dir() . '/rector_temp');
    
  • 先验证规则有效性:执行vendor\bin\rector process --dry-run确认自定义规则能正确匹配替换代码,排除规则本身异常导致的问题。
  • 临时关闭杀毒软件实时保护:部分杀毒软件会拦截Rector的临时文件操作,关闭实时保护后重试。
  • 手动清理残留临时文件:删除项目目录下类似ser8FA1.tmp的临时文件,再重新执行Rector命令。

内容的提问来源于stack exchange,提问作者Nail

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 18:18:30