From 80f158a2d2fa44c1785b16a3dcdabef3120b3e71 Mon Sep 17 00:00:00 2001 From: David Grudl Date: Thu, 6 Oct 2022 23:13:58 +0200 Subject: [PATCH] PhpNamespace: better use-statements sorting behavior --- src/PhpGenerator/PhpNamespace.php | 2 +- tests/PhpGenerator/Printer.use-order.phpt | 28 +++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 tests/PhpGenerator/Printer.use-order.phpt diff --git a/src/PhpGenerator/PhpNamespace.php b/src/PhpGenerator/PhpNamespace.php index 890fc8bf..660ff026 100644 --- a/src/PhpGenerator/PhpNamespace.php +++ b/src/PhpGenerator/PhpNamespace.php @@ -162,7 +162,7 @@ public function addUseConstant(string $name, ?string $alias = null): static /** @return string[] */ public function getUses(string $of = self::NameNormal): array { - asort($this->aliases[$of]); + uasort($this->aliases[$of], fn(string $a, string $b): int => strtr($a, '\\', ' ') <=> strtr($b, '\\', ' ')); return array_filter( $this->aliases[$of], fn($name, $alias) => strcasecmp(($this->name ? $this->name . '\\' : '') . $alias, $name), diff --git a/tests/PhpGenerator/Printer.use-order.phpt b/tests/PhpGenerator/Printer.use-order.phpt new file mode 100644 index 00000000..f7e642eb --- /dev/null +++ b/tests/PhpGenerator/Printer.use-order.phpt @@ -0,0 +1,28 @@ +addUse('Example\Foo\EmailAlias\Bar'); +$namespace->addUse('Example\Foo\Email\Test'); +$namespace->addUse('Example\Foo\MyClass'); + +Assert::match( + <<<'XX' + namespace Foo; + + use Example\Foo\Email\Test; + use Example\Foo\EmailAlias\Bar; + use Example\Foo\MyClass; + + XX, + $printer->printNamespace($namespace), +);