Skip to content

Commit

Permalink
Fix indentation detection after opening tag
Browse files Browse the repository at this point in the history
Fixes #982.
  • Loading branch information
nikic committed Mar 2, 2024
1 parent ec02613 commit 70c9649
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/PhpParser/Internal/TokenStream.php
Original file line number Diff line number Diff line change
Expand Up @@ -251,14 +251,18 @@ public function getTokenCode(int $from, int $to, int $indent): string {
private function calcIndentMap(): array {
$indentMap = [];
$indent = 0;
foreach ($this->tokens as $token) {
foreach ($this->tokens as $i => $token) {
$indentMap[] = $indent;

if ($token->id === \T_WHITESPACE) {
$content = $token->text;
$newlinePos = \strrpos($content, "\n");
if (false !== $newlinePos) {
$indent = \strlen($content) - $newlinePos - 1;
} elseif ($i === 1 && $this->tokens[0]->id === \T_OPEN_TAG &&
$this->tokens[0]->text[\strlen($this->tokens[0]->text) - 1] === "\n") {
// Special case: Newline at the end of opening tag followed by whitespace.
$indent = \strlen($content);
}
}
}
Expand Down
11 changes: 11 additions & 0 deletions test/code/formatPreservation/comments.test
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,14 @@ class Test {
// some code
}
}
-----
<?php
class Example {
}
-----
$stmts[0]->setDocComment(new Comment\Doc("/** foo */"));
-----
<?php
/** foo */
class Example {
}

0 comments on commit 70c9649

Please sign in to comment.