Make loop.last always available

This commit is contained in:
Fabien Potencier
2024-07-11 09:00:28 +02:00
parent aa80f21239
commit 2e8de1d110
5 changed files with 24 additions and 8 deletions
+1
View File
@@ -1,5 +1,6 @@
# 4.0.0 (2024-XX-XX)
* Make `loop.last` always available (even for non-countable iterators)
* Change the compilation of `for` loops to throw an exception when a `loop.*` variable is not defined
* Make `Environment::getGlobals()` private
* Drop support for PHP < 8.2
+2 -2
View File
@@ -77,8 +77,8 @@ Variable Description
.. note::
When the underlying PHP iterator is not countable, the ``loop.length``,
``loop.revindex``, ``loop.revindex0``, and ``loop.last`` variables are not
available and a ``RuntimeException`` is thrown if you try to use them.
``loop.revindex``, and ``loop.revindex0`` variables are not available and a
``RuntimeException`` is thrown if you try to use them.
The ``else`` Clause
-------------------
+16 -1
View File
@@ -25,6 +25,7 @@ final class Loop implements \Iterator
private \Iterator $seq;
private int $index0;
private int $length;
private bool $peek = false;
public function __construct($seq)
{
@@ -44,7 +45,11 @@ final class Loop implements \Iterator
public function next(): void
{
$this->seq->next();
if ($this->peek) {
$this->peek = false;
} else {
$this->seq->next();
}
++$this->index0;
}
@@ -81,4 +86,14 @@ final class Loop implements \Iterator
return $this->length = count($this->seq);
}
public function isLast(): bool
{
if (!$this->peek) {
$this->seq->next();
$this->peek = true;
}
return !$this->seq->valid();
}
}
+1 -1
View File
@@ -61,6 +61,6 @@ final class LoopContext
public function isLast(): bool
{
return 0 === $this->loop->getLength('last') - $this->getIndex();
return $this->loop->isLast();
}
}
+4 -4
View File
@@ -2,11 +2,11 @@
"for" tag supports Generators
--TEMPLATE--
{% for item in items %}
{{ item }}
{{ item }} {{ loop.last ? 'LAST' : '-' }}
{% endfor %}
--DATA--
return ['items' => (function () { yield 'a'; yield 'b'; yield 'c'; })()]
--EXPECT--
a
b
c
a -
b -
c LAST