Skip to content

Commit

Permalink
PhpNamespace::unresolveName() prefers shorter names
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Sep 18, 2021
1 parent 74ffdd5 commit 7880996
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 7 deletions.
11 changes: 5 additions & 6 deletions src/PhpGenerator/PhpNamespace.php
Original file line number Diff line number Diff line change
Expand Up @@ -141,8 +141,11 @@ public function unresolveName(string $name): string
return $name;
}
$name = ltrim($name, '\\');
$res = null;
$lower = strtolower($name);
$res = Strings::startsWith($lower, strtolower($this->name) . '\\')
? substr($name, strlen($this->name) + 1)
: null;

foreach ($this->uses as $alias => $original) {
if (Strings::startsWith($lower . '\\', strtolower($original) . '\\')) {
$short = $alias . substr($name, strlen($original));
Expand All @@ -152,11 +155,7 @@ public function unresolveName(string $name): string
}
}

if (!$res && Strings::startsWith($lower, strtolower($this->name) . '\\')) {
return substr($name, strlen($this->name) + 1);
} else {
return $res ?: ($this->name ? '\\' : '') . $name;
}
return $res ?: ($this->name ? '\\' : '') . $name;
}


Expand Down
5 changes: 4 additions & 1 deletion tests/PhpGenerator/PhpNamespace.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,11 @@ Assert::same('?A', $namespace->unresolveType('?foo\A'));
Assert::same('A&\Countable', $namespace->unresolveType('foo\A&Countable'));
Assert::same('', $namespace->unresolveType(''));

$namespace->addUse('Foo');
Assert::same('B', $namespace->unresolveName('Foo\B'));

$namespace->addUse('Bar\C');
Assert::same(['C' => 'Bar\C'], $namespace->getUses());
Assert::same(['C' => 'Bar\C', 'Foo' => 'Foo'], $namespace->getUses());

Assert::same('\Bar', $namespace->unresolveName('Bar'));
Assert::same('C', $namespace->unresolveName('\bar\C'));
Expand Down
1 change: 1 addition & 0 deletions tests/PhpGenerator/expected/PhpNamespace.expect
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
namespace Foo;

use Bar\C;
use Foo;

#[A]
class A implements A, C
Expand Down

0 comments on commit 7880996

Please sign in to comment.