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
10 changes: 8 additions & 2 deletions src/CodeGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -214,8 +214,14 @@ public function import(Importable | string $name) : string

// Check if the class is in the same namespace as the current namespace
if ($this->namespace !== null && $fqcn->namespace !== null && $this->namespace->equals($fqcn->namespace)) {
// No import needed, just return the class name
return (string) $fqcn->className;
// No import needed, but reserve the short name so later imports from
// other namespaces are aliased instead of colliding with the local
// declaration (PHP would reject `use X\Y\Foo;` in a file that also
// declares `class Foo`).
$alias = (string) $fqcn->className;
$this->imports[$alias] ??= $fqcn;

return $alias;
}

$alias = $this->findAvailableAlias($fqcn, $fqcn->className->name);
Expand Down
25 changes: 25 additions & 0 deletions tests/CodeGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,31 @@ public function testImportClassWithConflict() : void
);
}

public function testImportClassConflictsWithSameNamespaceDeclaration() : void
{
$this->generator = new CodeGenerator('App\\Models');

$local = $this->generator->import('App\\Models\\User');
$external = $this->generator->import('App\\Domain\\User');

self::assertSame('User', $local);
self::assertSame('User2', $external);

$this->assertDumpFile(
<<<'PHP'
<?php

declare(strict_types=1);

namespace App\Models;

use App\Domain\User as User2;

PHP,
[],
);
}

public function testImportFunction() : void
{
$alias = $this->generator->import(new FunctionName('array_map'));
Expand Down
Loading