Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 6386151

Browse files
committed
Reserve same-namespace short names during import
When a class is imported with the same namespace as the current file, its short name is now recorded as a reserved alias rather than silently returned. Without the reservation, a later import from a different namespace with the same short name was also returned unaliased, so the generated file ended up with `use X\Y\Foo;` alongside a `class Foo` declaration — which PHP rejects as a redeclaration. `findAvailableAlias` already bumps colliding entries to `Foo2`, so recording the reservation is enough to make conflicting external imports flow through that path automatically.
1 parent 710c32e commit 6386151

2 files changed

Lines changed: 33 additions & 2 deletions

File tree

src/CodeGenerator.php

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -214,8 +214,14 @@ public function import(Importable | string $name) : string
214214

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

221227
$alias = $this->findAvailableAlias($fqcn, $fqcn->className->name);

tests/CodeGeneratorTest.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,31 @@ public function testImportClassWithConflict() : void
170170
);
171171
}
172172

173+
public function testImportClassConflictsWithSameNamespaceDeclaration() : void
174+
{
175+
$this->generator = new CodeGenerator('App\\Models');
176+
177+
$local = $this->generator->import('App\\Models\\User');
178+
$external = $this->generator->import('App\\Domain\\User');
179+
180+
self::assertSame('User', $local);
181+
self::assertSame('User2', $external);
182+
183+
$this->assertDumpFile(
184+
<<<'PHP'
185+
<?php
186+
187+
declare(strict_types=1);
188+
189+
namespace App\Models;
190+
191+
use App\Domain\User as User2;
192+
193+
PHP,
194+
[],
195+
);
196+
}
197+
173198
public function testImportFunction() : void
174199
{
175200
$alias = $this->generator->import(new FunctionName('array_map'));

0 commit comments

Comments
 (0)