[CodingStyle] Prevent adding non-namespaced imports to non-namespaced class

This commit is contained in:
TomasVotruba 2020-01-11 09:53:25 +01:00
parent 4107774ffc
commit 23c0fb1d2a
2 changed files with 32 additions and 0 deletions

View File

@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Rector\CodingStyle\Application;
use Nette\Utils\Strings;
use PhpParser\Node;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Namespace_;
@ -155,7 +156,9 @@ final class UseAddingCommander implements CommanderInterface
// B. no namespace? add in the top
// first clean
$nodes = $this->useImportsRemover->removeImportsFromStmts($nodes, $removedShortUses);
$useImportTypes = $this->filterOutNonNamespacedNames($useImportTypes);
// then add, to prevent adding + removing false positive of same short use
return $this->useImportsAdder->addImportsToStmts($nodes, $useImportTypes, $functionUseImportTypes);
}
@ -287,4 +290,24 @@ final class UseAddingCommander implements CommanderInterface
return $this->useImportTypesInFilePath[$filePath] ?? [];
}
/**
* Prevents
* @param FullyQualifiedObjectType[] $useImportTypes
* @return FullyQualifiedObjectType[]
*/
private function filterOutNonNamespacedNames(array $useImportTypes): array
{
$namespacedUseImportTypes = [];
foreach ($useImportTypes as $useImportType) {
if (! Strings::contains($useImportType->getClassName(), '\\')) {
continue;
}
$namespacedUseImportTypes[] = $useImportType;
}
return $namespacedUseImportTypes;
}
}

View File

@ -0,0 +1,9 @@
<?php
class SearchagentController extends ApplicationController
{
}
class ApplicationController
{
}