Fix usage of loop in a for else clause

This commit is contained in:
Fabien Potencier
2024-07-31 09:52:42 +02:00
parent ab0c632f02
commit 5649de8a14
3 changed files with 70 additions and 3 deletions
+1 -1
View File
@@ -38,7 +38,7 @@ final class LoopContext
public function getRevindex0(): int
{
return $this->loop->getLength('revindex0') - $this->getIndex();
return max(0, $this->loop->getLength('revindex0') - $this->getIndex());
}
public function getRevindex(): int
+7 -2
View File
@@ -74,8 +74,8 @@ final class LoopIterator implements \Iterator
public function rewind(): void
{
$this->seq->rewind();
$this->previous = ['valid' => false, 'key' => null, 'value' => null];
if ($this->seq->valid()) {
$this->previous = ['valid' => false, 'key' => null, 'value' => null];
$this->current = ['valid' => $this->seq->valid(), 'key' => $this->seq->key(), 'value' => $this->seq->current()];
} else {
// EmptyIterator
@@ -123,7 +123,12 @@ final class LoopIterator implements \Iterator
{
if (!$this->next) {
$this->seq->next();
$this->next = ['valid' => $this->seq->valid(), 'key' => $this->seq->key(), 'value' => $this->seq->current()];
if ($this->seq->valid()) {
$this->next = ['valid' => $this->seq->valid(), 'key' => $this->seq->key(), 'value' => $this->seq->current()];
} else {
// EmptyIterator
$this->next = ['valid' => false, 'key' => null, 'value' => null];
}
}
return $this->next;
+62
View File
@@ -0,0 +1,62 @@
--TEST--
"for" tag loop behavior in an else clause
--TEMPLATE--
{% for item in [] %}
{% else %}
{{ loop.previous is null ? 'OK' : 'KO' }}
{{ loop.next is null ? 'OK' : 'KO' }}
{{ loop.first ? 'OK' : 'KO' }}
{{ loop.last ? 'OK' : 'KO' }}
{{ loop.index0 is same as 0 ? 'OK' : 'KO' }}
{{ loop.revindex0 is same as 0 ? 'OK' : 'KO' }}
{{ loop.length is same as 0 ? 'OK' : 'KO' }}
{{ loop.depth is same as 1 ? 'OK' : 'KO' }}
{% endfor %}
{% for item in empty_it %}
{% else %}
{{ loop.previous is null ? 'OK' : 'KO' }}
{{ loop.next is null ? 'OK' : 'KO' }}
{{ loop.first ? 'OK' : 'KO' }}
{{ loop.last ? 'OK' : 'KO' }}
{{ loop.index0 is same as 0 ? 'OK' : 'KO' }}
{{ loop.depth is same as 1 ? 'OK' : 'KO' }}
{% endfor %}
{% for item in yielding_it %}
{% else %}
{{ loop.previous is null ? 'OK' : 'KO' }}
{{ loop.next is null ? 'OK' : 'KO' }}
{{ loop.first ? 'OK' : 'KO' }}
{{ loop.last ? 'OK' : 'KO' }}
{{ loop.index0 is same as 0 ? 'OK' : 'KO' }}
{{ loop.depth is same as 1 ? 'OK' : 'KO' }}
{% endfor %}
--DATA--
return [
'empty_it' => new \EmptyIterator(),
'yielding_it' => (function (): \Generator { return; yield; })(),
]
--EXPECT--
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK