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
35 changes: 35 additions & 0 deletions rules/CodingStyle/Node/NameImporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use PhpParser\Node\Name\FullyQualified;
use PhpParser\Node\Stmt\GroupUse;
use PhpParser\Node\Stmt\Use_;
use PHPStan\Analyser\Scope;
use Rector\CodingStyle\ClassNameImport\ClassNameImportSkipper;
use Rector\Naming\Naming\AliasNameResolver;
use Rector\NodeTypeResolver\Node\AttributeKey;
Expand Down Expand Up @@ -90,6 +91,12 @@ private function importNameAndCollectNewUseStatement(
return $nameInUse;
}

$nameInNamespacedScope = $this->resolveNameInNamespacedScope($fullyQualified);
if ($nameInNamespacedScope instanceof Name) {
$nameInNamespacedScope->setAttribute(AttributeKey::NAMESPACED_NAME, $fullyQualified->toString());
return $nameInNamespacedScope;
}

// the same end is already imported → skip
if ($this->classNameImportSkipper->shouldSkipNameForFullyQualifiedObjectType(
$file,
Expand All @@ -111,6 +118,34 @@ private function importNameAndCollectNewUseStatement(
return $fullyQualifiedObjectType->getShortNameNode();
}

private function resolveNameInNamespacedScope(FullyQualified $fullyQualified): ?Name
{
/**
* 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 = $fullyQualified->getAttribute(AttributeKey::SCOPE);
if (! $scope instanceof Scope) {
return null;
}

$namespace = $scope->getNamespace();
if ($namespace === null) {
return null;
}

$shortName = $fullyQualified->getLast();
$namepaceFullyQualifiedName = substr($fullyQualified->toString(), 0, -strlen($shortName) - 1);

if ($namepaceFullyQualifiedName === $namespace) {
return new Name($shortName);
}

return null;
}

private function addUseImport(
File $file,
FullyQualified $fullyQualified,
Expand Down
21 changes: 21 additions & 0 deletions tests/Issues/AutoImport/Fixture/fqcn_current_same_class.php.inc
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

namespace App\Bar;

class FqcnCurrentSameClass
{
public \App\Bar\FqcnCurrentSameClass $prop;
}

?>
-----
<?php

namespace App\Bar;

class FqcnCurrentSameClass
{
public FqcnCurrentSameClass $prop;
}

?>
Loading