From 595fe48a3bf43282d21e6930e433d22014f9ecbd Mon Sep 17 00:00:00 2001 From: Vincent Langlet Date: Wed, 6 Nov 2024 17:21:28 +0100 Subject: [PATCH] Fix TrailingCommaMultiLine when there is no elements (#326) --- src/Rules/Punctuation/TrailingCommaMultiLineRule.php | 8 +++++++- .../TrailingCommaMultiLineRuleTest.fixed.twig | 7 +++++++ .../TrailingCommaMultiLineRuleTest.fixed2.twig | 7 +++++++ .../TrailingCommaMultiLineRuleTest.twig | 7 +++++++ 4 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/Rules/Punctuation/TrailingCommaMultiLineRule.php b/src/Rules/Punctuation/TrailingCommaMultiLineRule.php index d48fa006..e14c1a95 100644 --- a/src/Rules/Punctuation/TrailingCommaMultiLineRule.php +++ b/src/Rules/Punctuation/TrailingCommaMultiLineRule.php @@ -52,7 +52,13 @@ protected function process(int $tokenIndex, Tokens $tokens): void return; } - $isMatchingComma = $tokens->get($previous)->isMatching(Token::PUNCTUATION_TYPE, ','); + $previousToken = $tokens->get($previous); + if ($previousToken === $token->getRelatedToken()) { + // There is no element, so adding a trailing comma will break the code. + return; + } + + $isMatchingComma = $previousToken->isMatching(Token::PUNCTUATION_TYPE, ','); if ($this->useTrailingComma === $isMatchingComma) { return; } diff --git a/tests/Rules/Punctuation/TrailingCommaMultiLine/TrailingCommaMultiLineRuleTest.fixed.twig b/tests/Rules/Punctuation/TrailingCommaMultiLine/TrailingCommaMultiLineRuleTest.fixed.twig index ee4d4986..11075699 100644 --- a/tests/Rules/Punctuation/TrailingCommaMultiLine/TrailingCommaMultiLineRuleTest.fixed.twig +++ b/tests/Rules/Punctuation/TrailingCommaMultiLine/TrailingCommaMultiLineRuleTest.fixed.twig @@ -40,3 +40,10 @@ 1 + 2 ) }} + +{% set emptyArray = [ +] %} +{% set emptyObject = { +} %} +{{ emptyCall( +) }} diff --git a/tests/Rules/Punctuation/TrailingCommaMultiLine/TrailingCommaMultiLineRuleTest.fixed2.twig b/tests/Rules/Punctuation/TrailingCommaMultiLine/TrailingCommaMultiLineRuleTest.fixed2.twig index 06199a72..fb40ff6a 100644 --- a/tests/Rules/Punctuation/TrailingCommaMultiLine/TrailingCommaMultiLineRuleTest.fixed2.twig +++ b/tests/Rules/Punctuation/TrailingCommaMultiLine/TrailingCommaMultiLineRuleTest.fixed2.twig @@ -40,3 +40,10 @@ 1 + 2 ) }} + +{% set emptyArray = [ +] %} +{% set emptyObject = { +} %} +{{ emptyCall( +) }} diff --git a/tests/Rules/Punctuation/TrailingCommaMultiLine/TrailingCommaMultiLineRuleTest.twig b/tests/Rules/Punctuation/TrailingCommaMultiLine/TrailingCommaMultiLineRuleTest.twig index 44e92833..c0ef0696 100644 --- a/tests/Rules/Punctuation/TrailingCommaMultiLine/TrailingCommaMultiLineRuleTest.twig +++ b/tests/Rules/Punctuation/TrailingCommaMultiLine/TrailingCommaMultiLineRuleTest.twig @@ -40,3 +40,10 @@ 1 + 2 ) }} + +{% set emptyArray = [ +] %} +{% set emptyObject = { +} %} +{{ emptyCall( +) }}