From 7523a5423644c3a2abb4c2923ebb229570776d0c Mon Sep 17 00:00:00 2001 From: Ruud Kamphuis Date: Fri, 27 Nov 2026 08:57:38 +0100 Subject: [PATCH] Drop trailing whitespace from prefixed empty lines `prefix()` put the full prefix in front of an empty line, so an empty line in a doc comment became ` * ` with a trailing space. Callers had to write such comments by hand to avoid it. An empty line now gets the prefix without its trailing whitespace (` *`, `//`), the same way `indent()` leaves empty lines empty. --- src/CodeGenerator.php | 3 ++- tests/CodeGeneratorTest.php | 24 ++++++++++++++++++++++-- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/src/CodeGenerator.php b/src/CodeGenerator.php index 2a81fa3..14ff6ec 100644 --- a/src/CodeGenerator.php +++ b/src/CodeGenerator.php @@ -739,7 +739,8 @@ public function prefix(string $prefix, array|Closure|Generator|string $data): Ge } foreach (explode(PHP_EOL, $line) as $singleLine) { - yield $prefix . $singleLine; + // An empty line gets the prefix without its trailing whitespace, like `indent()` does + yield $singleLine === '' ? rtrim($prefix) : $prefix . $singleLine; } } } diff --git a/tests/CodeGeneratorTest.php b/tests/CodeGeneratorTest.php index 87cda46..c137ffd 100644 --- a/tests/CodeGeneratorTest.php +++ b/tests/CodeGeneratorTest.php @@ -1385,12 +1385,32 @@ public function testDocComment(): void ])); } + public function testPrefixDoesNotLeaveTrailingWhitespaceOnEmptyLines(): void + { + self::assertSame( + ['// first', '//', '// third'], + iterator_to_array($this->generator->prefix('// ', "first\n\nthird"), preserve_keys: false), + ); + self::assertSame(['>'], iterator_to_array($this->generator->prefix('> ', ''), preserve_keys: false)); + } + + public function testDocCommentWithEmptyLine(): void + { + $this->assertDump(<<<'PHP' + /** + * Summary + * + * @deprecated Use something else + */ + PHP, $this->generator->docComment(['Summary', '', '@deprecated Use something else'])); + } + public function testDocCommentWithFullDump(): void { $this->assertDump(<<<'PHP' /** * Calculate the sum of two numbers - * + * * @param int $a First number * @param int $b Second number * @return int The sum @@ -1475,7 +1495,7 @@ public function testBlockCommentWithEmptyString(): void { $this->assertDump(<<<'PHP' /* - * + * */ PHP, $this->generator->blockComment('')); }