Skip to content

Commit e614730

Browse files
authored
[AutoImport] Allow on FQCN current same class (#7232)
* [AutoImport] Allow FQCN current same class * [AutoImport] Allow FQCN current same class * future note * future note * future note
1 parent 9929af7 commit e614730

2 files changed

Lines changed: 56 additions & 0 deletions

File tree

rules/CodingStyle/Node/NameImporter.php

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
use PhpParser\Node\Name\FullyQualified;
1010
use PhpParser\Node\Stmt\GroupUse;
1111
use PhpParser\Node\Stmt\Use_;
12+
use PHPStan\Analyser\Scope;
1213
use Rector\CodingStyle\ClassNameImport\ClassNameImportSkipper;
1314
use Rector\Naming\Naming\AliasNameResolver;
1415
use Rector\NodeTypeResolver\Node\AttributeKey;
@@ -90,6 +91,12 @@ private function importNameAndCollectNewUseStatement(
9091
return $nameInUse;
9192
}
9293

94+
$nameInNamespacedScope = $this->resolveNameInNamespacedScope($fullyQualified);
95+
if ($nameInNamespacedScope instanceof Name) {
96+
$nameInNamespacedScope->setAttribute(AttributeKey::NAMESPACED_NAME, $fullyQualified->toString());
97+
return $nameInNamespacedScope;
98+
}
99+
93100
// the same end is already imported → skip
94101
if ($this->classNameImportSkipper->shouldSkipNameForFullyQualifiedObjectType(
95102
$file,
@@ -111,6 +118,34 @@ private function importNameAndCollectNewUseStatement(
111118
return $fullyQualifiedObjectType->getShortNameNode();
112119
}
113120

121+
private function resolveNameInNamespacedScope(FullyQualified $fullyQualified): ?Name
122+
{
123+
/**
124+
* Note: Don't use ScopeFetcher::fetch() on Name instance,
125+
* Scope can be null on Name
126+
* This is part of ScopeAnalyzer::NON_REFRESHABLE_NODES
127+
* @see https://github.com/rectorphp/rector-src/blob/9929af7c0179929b4fde6915cb7a06c3141dde6c/src/NodeAnalyzer/ScopeAnalyzer.php#L17
128+
*/
129+
$scope = $fullyQualified->getAttribute(AttributeKey::SCOPE);
130+
if (! $scope instanceof Scope) {
131+
return null;
132+
}
133+
134+
$namespace = $scope->getNamespace();
135+
if ($namespace === null) {
136+
return null;
137+
}
138+
139+
$shortName = $fullyQualified->getLast();
140+
$namepaceFullyQualifiedName = substr($fullyQualified->toString(), 0, -strlen($shortName) - 1);
141+
142+
if ($namepaceFullyQualifiedName === $namespace) {
143+
return new Name($shortName);
144+
}
145+
146+
return null;
147+
}
148+
114149
private function addUseImport(
115150
File $file,
116151
FullyQualified $fullyQualified,
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<?php
2+
3+
namespace App\Bar;
4+
5+
class FqcnCurrentSameClass
6+
{
7+
public \App\Bar\FqcnCurrentSameClass $prop;
8+
}
9+
10+
?>
11+
-----
12+
<?php
13+
14+
namespace App\Bar;
15+
16+
class FqcnCurrentSameClass
17+
{
18+
public FqcnCurrentSameClass $prop;
19+
}
20+
21+
?>

0 commit comments

Comments
 (0)