diff --git a/src/Util/UseStatementGenerator.php b/src/Util/UseStatementGenerator.php index 2523cca18..38f63084a 100644 --- a/src/Util/UseStatementGenerator.php +++ b/src/Util/UseStatementGenerator.php @@ -45,7 +45,11 @@ public function __toString(): string $class = $aliasClass; } - $transformed[$key] = str_replace('\\', ' ', $class); + $transformedClass = str_replace('\\', ' ', $class); + // Let's not add the class again if it already exists. + if (!\in_array($transformedClass, $transformed, true)) { + $transformed[$key] = $transformedClass; + } } asort($transformed); diff --git a/tests/Util/UseStatementGeneratorTest.php b/tests/Util/UseStatementGeneratorTest.php index 10a46aec6..53fdf8144 100644 --- a/tests/Util/UseStatementGeneratorTest.php +++ b/tests/Util/UseStatementGeneratorTest.php @@ -90,4 +90,20 @@ public function testUseStatementsWithAliases(): void EOT; self::assertSame($expected, (string) $unsorted); } + + public function testUseStatementsWithDuplicates(): void + { + $unsorted = new UseStatementGenerator([ + \Symfony\UX\Turbo\Attribute\Broadcast::class, + \ApiPlatform\Core\Annotation\ApiResource::class, + \ApiPlatform\Core\Annotation\ApiResource::class, + ]); + + $expected = <<< 'EOT' + use ApiPlatform\Core\Annotation\ApiResource; + use Symfony\UX\Turbo\Attribute\Broadcast; + + EOT; + self::assertSame($expected, (string) $unsorted); + } }