diff --git a/src/Parser.php b/src/Parser.php index feda1d535..d6fd88aa5 100644 --- a/src/Parser.php +++ b/src/Parser.php @@ -204,7 +204,7 @@ class Parser public function peekBlockStack() { - return $this->blockStack[\count($this->blockStack) - 1]; + return isset($this->blockStack[\count($this->blockStack) - 1]) ? $this->blockStack[\count($this->blockStack) - 1] : null; } public function popBlockStack(): void diff --git a/src/TokenParser/ExtendsTokenParser.php b/src/TokenParser/ExtendsTokenParser.php index 006ddc524..fd2751471 100644 --- a/src/TokenParser/ExtendsTokenParser.php +++ b/src/TokenParser/ExtendsTokenParser.php @@ -27,8 +27,10 @@ final class ExtendsTokenParser extends AbstractTokenParser { $stream = $this->parser->getStream(); - if (!$this->parser->isMainScope()) { - throw new SyntaxError('Cannot extend from a block.', $token->getLine(), $stream->getSourceContext()); + if ($this->parser->peekBlockStack()) { + throw new SyntaxError('Cannot use "extend" in a block.', $token->getLine(), $stream->getSourceContext()); + } elseif (!$this->parser->isMainScope()) { + throw new SyntaxError('Cannot use "extend" in a macro.', $token->getLine(), $stream->getSourceContext()); } if (null !== $this->parser->getParent()) { diff --git a/test/Twig/Tests/Fixtures/tags/inheritance/extends_in_block.test b/test/Twig/Tests/Fixtures/tags/inheritance/extends_in_block.test new file mode 100644 index 000000000..a372ea1c8 --- /dev/null +++ b/test/Twig/Tests/Fixtures/tags/inheritance/extends_in_block.test @@ -0,0 +1,10 @@ +--TEST-- +"extends" tag in a block +--TEMPLATE-- +{% block foo %} + {% extends "foo.twig" %} +{% endblock %} +--DATA-- +return [] +--EXCEPTION-- +Twig\Error\SyntaxError: Cannot use "extend" in a block in "index.twig" at line 3. diff --git a/test/Twig/Tests/Fixtures/tags/inheritance/extends_in_macro.test b/test/Twig/Tests/Fixtures/tags/inheritance/extends_in_macro.test new file mode 100644 index 000000000..dc87b2a8c --- /dev/null +++ b/test/Twig/Tests/Fixtures/tags/inheritance/extends_in_macro.test @@ -0,0 +1,10 @@ +--TEST-- +"extends" tag in a macro +--TEMPLATE-- +{% macro foo() %} + {% extends "foo.twig" %} +{% endmacro %} +--DATA-- +return [] +--EXCEPTION-- +Twig\Error\SyntaxError: Cannot use "extend" in a macro in "index.twig" at line 3. diff --git a/test/Twig/Tests/Fixtures/tags/inheritance/parent_in_a_block.test b/test/Twig/Tests/Fixtures/tags/inheritance/parent_in_a_block.test deleted file mode 100644 index 1d1987d5b..000000000 --- a/test/Twig/Tests/Fixtures/tags/inheritance/parent_in_a_block.test +++ /dev/null @@ -1,8 +0,0 @@ ---TEST-- -"extends" tag ---TEMPLATE-- -{% block content %} - {% extends "foo.twig" %} -{% endblock %} ---EXCEPTION-- -Twig\Error\SyntaxError: Cannot extend from a block in "index.twig" at line 3.