mirror of
https://github.com/twigphp/Twig.git
synced 2026-09-04 22:47:21 +00:00
Make loop.last always available
This commit is contained in:
@@ -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
@@ -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
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,6 +61,6 @@ final class LoopContext
|
||||
|
||||
public function isLast(): bool
|
||||
{
|
||||
return 0 === $this->loop->getLength('last') - $this->getIndex();
|
||||
return $this->loop->isLast();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user