-
-
Notifications
You must be signed in to change notification settings - Fork 439
Expand file tree
/
Copy pathClassLikeNameClassNameImportSkipVoter.php
More file actions
69 lines (58 loc) · 2.18 KB
/
ClassLikeNameClassNameImportSkipVoter.php
File metadata and controls
69 lines (58 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php
declare(strict_types=1);
namespace Rector\CodingStyle\ClassNameImport\ClassNameImportSkipVoter;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use Rector\CodingStyle\ClassNameImport\ShortNameResolver;
use Rector\CodingStyle\Contract\ClassNameImport\ClassNameImportSkipVoterInterface;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType;
use Rector\ValueObject\Application\File;
/**
* Prevents adding:
*
* use App\SomeClass;
*
* If there is already:
*
* class SomeClass {}
*/
final readonly class ClassLikeNameClassNameImportSkipVoter implements ClassNameImportSkipVoterInterface
{
public function __construct(
private ShortNameResolver $shortNameResolver
) {
}
public function shouldSkip(File $file, FullyQualifiedObjectType $fullyQualifiedObjectType, Node $node): bool
{
$classLikeNames = $this->shortNameResolver->resolveShortClassLikeNames($file);
if ($classLikeNames === []) {
return false;
}
/**
* Note: Don't use ScopeFetcher::fetch() on Name instance,
* Scope can be null on Name
* This is part of ScopeAnalyzer::NON_REFRESHABLE_NODES
* @see https://github.com/rectorphp/rector-src/blob/9929af7c0179929b4fde6915cb7a06c3141dde6c/src/NodeAnalyzer/ScopeAnalyzer.php#L17
*/
$scope = $node->getAttribute(AttributeKey::SCOPE);
$namespace = $scope instanceof Scope ? $scope->getNamespace() : null;
$namespace = strtolower((string) $namespace);
$shortNameLowered = $fullyQualifiedObjectType->getShortNameLowered();
$fullyQualifiedObjectTypeNamespace = strtolower(
substr($fullyQualifiedObjectType->getClassName(), 0, -strlen($fullyQualifiedObjectType->getShortName()) - 1)
);
foreach ($classLikeNames as $classLikeName) {
if (strtolower($classLikeName) !== $shortNameLowered) {
continue;
}
if ($namespace === '') {
return true;
}
if ($namespace !== $fullyQualifiedObjectTypeNamespace) {
return true;
}
}
return false;
}
}