2019-10-13 07:59:52 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
declare(strict_types=1);
|
2019-09-19 10:37:16 +02:00
|
|
|
|
|
|
|
namespace Rector\CodingStyle\Application;
|
|
|
|
|
|
|
|
use PhpParser\Node\Stmt;
|
|
|
|
use PhpParser\Node\Stmt\Namespace_;
|
|
|
|
use PhpParser\Node\Stmt\Use_;
|
|
|
|
|
|
|
|
final class UseImportsRemover
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* @param Stmt[] $stmts
|
|
|
|
* @param string[] $removedShortUses
|
|
|
|
* @return Stmt[]
|
|
|
|
*/
|
|
|
|
public function removeImportsFromStmts(array $stmts, array $removedShortUses): array
|
|
|
|
{
|
|
|
|
foreach ($stmts as $stmtKey => $stmt) {
|
|
|
|
if (! $stmt instanceof Use_) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
$this->removeUseFromUse($removedShortUses, $stmt);
|
|
|
|
|
|
|
|
// nothing left → remove
|
2020-10-29 15:59:39 +07:00
|
|
|
if ($stmt->uses === []) {
|
2019-09-19 10:37:16 +02:00
|
|
|
unset($stmts[$stmtKey]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return $stmts;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param string[] $removedShortUses
|
|
|
|
*/
|
|
|
|
public function removeImportsFromNamespace(Namespace_ $namespace, array $removedShortUses): void
|
|
|
|
{
|
|
|
|
foreach ($namespace->stmts as $namespaceKey => $stmt) {
|
|
|
|
if (! $stmt instanceof Use_) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
$this->removeUseFromUse($removedShortUses, $stmt);
|
|
|
|
|
|
|
|
// nothing left → remove
|
2020-10-29 15:59:39 +07:00
|
|
|
if ($stmt->uses === []) {
|
2019-09-19 10:37:16 +02:00
|
|
|
unset($namespace->stmts[$namespaceKey]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param string[] $removedShortUses
|
|
|
|
*/
|
|
|
|
private function removeUseFromUse(array $removedShortUses, Use_ $use): void
|
|
|
|
{
|
|
|
|
foreach ($use->uses as $usesKey => $useUse) {
|
|
|
|
foreach ($removedShortUses as $removedShortUse) {
|
|
|
|
if ($useUse->name->getLast() !== $removedShortUse) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
unset($use->uses[$usesKey]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|