diff --git a/src/Twig/ArrayExtension.php b/src/Twig/ArrayExtension.php index 7d4c8c2b5..5e014fc21 100644 --- a/src/Twig/ArrayExtension.php +++ b/src/Twig/ArrayExtension.php @@ -6,6 +6,7 @@ use Bolt\Entity\Content; use Pagerfanta\Pagerfanta; +use Twig\Environment; use Twig\Extension\AbstractExtension; use Twig\TwigFilter; @@ -21,9 +22,12 @@ final class ArrayExtension extends AbstractExtension */ public function getFilters(): array { + $env = ['needs_environment' => true]; + return [ new TwigFilter('order', [$this, 'order']), new TwigFilter('shuffle', [$this, 'shuffle']), + new TwigFilter('length', [$this, 'length'], $env), ]; } @@ -32,9 +36,7 @@ public function getFilters(): array */ public function shuffle($array) { - if ($array instanceof Pagerfanta) { - $array = iterator_to_array($array->getCurrentPageResults()); - } + $array = $this->getArray($array); if (is_array($array)) { shuffle($array); @@ -43,6 +45,16 @@ public function shuffle($array) return $array; } + /** + * Returns the length of a variable. + * Overrides the default Twig |length filter + * for accurate results with paginated content + */ + public function length(Environment $env, $thing) + { + return twig_length_filter($env, $this->getArray($thing)); + } + /** * Sorts / orders items of an array. */ @@ -106,4 +118,13 @@ private static function orderHelper(Content $a, Content $b, string $orderOn, boo return $bVal <=> $aVal; } + + private function getArray($array) + { + if ($array instanceof Pagerfanta) { + return (array) $array->getCurrentPageResults(); + } + + return $array; + } }