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
2 changes: 2 additions & 0 deletions bench/unused_import_removing_bench.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@
};

$file = $testingParser->parseFilePathToFile($sourceFilePath);
$postRector->setFile($file);

$fileNode = $file->getFileNode();
assert($fileNode instanceof FileNode);

Expand Down
33 changes: 31 additions & 2 deletions src/PostRector/Rector/UnusedImportRemovingPostRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,17 @@
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\PhpDocParser\NodeTraverser\SimpleCallableNodeTraverser;
use Rector\PhpParser\Node\FileNode;
use Rector\ValueObject\Application\File;

final class UnusedImportRemovingPostRector extends AbstractPostRector
{
private ?File $usedNamesFile = null;

/**
* @var array<int, array{version: int, names: string[]}>
*/
private array $usedNamesCache = [];

public function __construct(
private readonly SimpleCallableNodeTraverser $simpleCallableNodeTraverser,
private readonly PhpDocInfoFactory $phpDocInfoFactory,
Expand Down Expand Up @@ -198,11 +206,32 @@ private function findNamesInDocBlocks(Namespace_|FileNode $rootNode): array
*/
private function resolveUsedPhpAndDocNames(Namespace_|FileNode $rootNode): array
{
// the referenced names only change with a new stmts version, while the post-rector chain
// re-runs this node across convergence iterations, so cache per (file, version)
$file = $this->getFile();
if ($file !== $this->usedNamesFile) {
$this->usedNamesFile = $file;
$this->usedNamesCache = [];
}

$version = $file->getNewStmtsVersion();
$objectId = spl_object_id($rootNode);

$cached = $this->usedNamesCache[$objectId] ?? null;
if ($cached !== null && $cached['version'] === $version) {
return $cached['names'];
}

$phpNames = $this->findNonUseImportNames($rootNode);
$docBlockNames = $this->findNamesInDocBlocks($rootNode);

$names = [...$phpNames, ...$docBlockNames];
return array_unique($names);
$names = array_unique([...$phpNames, ...$docBlockNames]);
$this->usedNamesCache[$objectId] = [
'version' => $version,
'names' => $names,
];

return $names;
}

/**
Expand Down
Loading