From 63f41604007f39b8e062e977cb0a490bb1e8a94f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Andr=C3=A9?= Date: Sun, 22 Dec 2024 05:53:28 +0100 Subject: [PATCH] [TwigComponent] Minimal support of comment lines Twig introduced the inline comments in https://github.com/twigphp/Twig/pull/4349 This PR add minimal support for it the PreLexer / HTML syntax ```twig ``` I'd like some IRL feedbacks on this one :) --- src/TwigComponent/src/Twig/TwigPreLexer.php | 8 +++ .../tests/Unit/TwigPreLexerTest.php | 60 +++++++++++++++++++ 2 files changed, 68 insertions(+) diff --git a/src/TwigComponent/src/Twig/TwigPreLexer.php b/src/TwigComponent/src/Twig/TwigPreLexer.php index 5d6d41f3fa3..3cdee464e67 100644 --- a/src/TwigComponent/src/Twig/TwigPreLexer.php +++ b/src/TwigComponent/src/Twig/TwigPreLexer.php @@ -233,6 +233,7 @@ private function consumeAttributes(string $componentName): string $isAttributeDynamic = false; // :someProp="dynamicVar" + $this->consumeWhitespace(); if ($this->check(':')) { $this->consume(':'); $isAttributeDynamic = true; @@ -244,6 +245,7 @@ private function consumeAttributes(string $componentName): string // -> someProp: true if (!$this->check('=')) { + $this->consumeWhitespace(); // don't allow "" if ($isAttributeDynamic) { throw new SyntaxError(\sprintf('Expected "=" after ":%s" when parsing the "line); @@ -332,6 +334,12 @@ private function consumeWhitespace(): void $whitespace = substr($this->input, $this->position, strspn($this->input, " \t\n\r\0\x0B", $this->position)); $this->line += substr_count($whitespace, "\n"); $this->position += \strlen($whitespace); + + if ($this->check('#')) { + $this->consume('#'); + $this->consumeUntil("\n"); + $this->consumeWhitespace(); + } } /** diff --git a/src/TwigComponent/tests/Unit/TwigPreLexerTest.php b/src/TwigComponent/tests/Unit/TwigPreLexerTest.php index f4489867d40..4e105acd7c2 100644 --- a/src/TwigComponent/tests/Unit/TwigPreLexerTest.php +++ b/src/TwigComponent/tests/Unit/TwigPreLexerTest.php @@ -376,5 +376,65 @@ public static function getLexTests(): iterable 'content', '{% component \'foobar\' with { bar: \'baz\', ...attr } %}{% block content %}content{% endblock %}{% endcomponent %}', ]; + yield 'component_with_comment_line' => [ + "", + '{{ component(\'foo\') }}', + ]; + yield 'component_with_comment_line_between_args' => [ + << + TWIG, + '{{ component(\'foo\', { bar: \'baz\' }) }}', + ]; + yield 'component_with_comment_lines_between_args' => [ + << + TWIG, + '{{ component(\'foo\', { foo: \'foo\', bar: \'bar\' }) }}', + ]; + yield 'component_with_comment_line_containing_ending_tag' => [ + << + bar="bar" + /> + TWIG, + '{{ component(\'foo\', { bar: \'bar\' }) }}', + ]; + yield 'component_with_comment_line_in_argument_value' => [ + << + TWIG, + '{{ component(\'foo\', { bar: \'# bar\' }) }}', + ]; + yield 'component_with_comment_line_in_argument_array_value_is_kept' => [ + << + TWIG, + // Twig will remove the comment, we don't need to remove it + <<