twigphp / Twig

Twig, the flexible, fast, and secure template language for PHP
https://twig.symfony.com/
BSD 3-Clause "New" or "Revised" License
8.15k stars 1.24k forks source link

ext-ds Vector/Map not supported by the following filters: slice, first, last (infinite loop) #3857

Closed josephLaurent closed 1 month ago

josephLaurent commented 1 year ago

We use ext-ds object in twig files and the slice/first or last filters get stuck when using it on Vector or Map. Exemple: {% set result = myVector|last %} This is due to the following while loop in the twig_slice function (https://github.com/twigphp/Twig/blob/3.x/src/Extension/CoreExtension.php#L651):

while ($item instanceof \IteratorAggregate) {
      $item = $item->getIterator();
}

And because $item->getIterator() return a Vector which implement \IteratorAggregate.

I don't know if it can be fixed ? Thank you in advance for your help

josephLaurent commented 6 months ago

Up

ericmorand commented 6 months ago

Is Vector a traversable?

The last filter returns the last "element" of a sequence, a mapping, or a string [...] It also works with objects implementing the Traversable

josephLaurent commented 6 months ago

Yes Vector and Map are both traversable and they also implement the \IteratorAggregate interface which end up in the following infinite loop

while ($item instanceof \IteratorAggregate) { $item = $item->getIterator(); }

because the getIterator of Vector/Map always return an \IteratorAggregate. But I don't understand this while loop because nothing say that this while loop will end.

stof commented 6 months ago

Well, in userland, you cannot have an infinite loop there, because at some point, you need to reach a place actually implementing the iteration protocol. But for extensions, they might be able to override the iteration protocol without actually implementing Iterator.

josephLaurent commented 5 months ago

I don't understand why the getIterator function of an IteratorAggregate should at some point not return an IteratorAggregate. For me, there is no reason to believe that. But maybe I missed something ?