From 70c96493b4caa5514b45429ec5fe6f412ea6cde6 Mon Sep 17 00:00:00 2001 From: Nikita Popov Date: Sat, 2 Mar 2024 18:59:44 +0100 Subject: [PATCH] Fix indentation detection after opening tag Fixes #982. --- lib/PhpParser/Internal/TokenStream.php | 6 +++++- test/code/formatPreservation/comments.test | 11 +++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/lib/PhpParser/Internal/TokenStream.php b/lib/PhpParser/Internal/TokenStream.php index 8fba13124d..c02844ac75 100644 --- a/lib/PhpParser/Internal/TokenStream.php +++ b/lib/PhpParser/Internal/TokenStream.php @@ -251,7 +251,7 @@ 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) { @@ -259,6 +259,10 @@ private function calcIndentMap(): array { $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); } } } diff --git a/test/code/formatPreservation/comments.test b/test/code/formatPreservation/comments.test index 1b62ab391a..e57477cac9 100644 --- a/test/code/formatPreservation/comments.test +++ b/test/code/formatPreservation/comments.test @@ -50,3 +50,14 @@ class Test { // some code } } +----- +setDocComment(new Comment\Doc("/** foo */")); +----- +