Skip to content

Commit

Permalink
Override Twig length filter so that it works correctly with pagination
Browse files Browse the repository at this point in the history
  • Loading branch information
I-Valchev authored and bobdenotter committed Jul 17, 2020
1 parent ce40525 commit 184eab4
Showing 1 changed file with 24 additions and 3 deletions.
27 changes: 24 additions & 3 deletions src/Twig/ArrayExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Bolt\Entity\Content;
use Pagerfanta\Pagerfanta;
use Twig\Environment;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;

Expand All @@ -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),
];
}

Expand All @@ -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);
Expand All @@ -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.
*/
Expand Down Expand Up @@ -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;
}
}

0 comments on commit 184eab4

Please sign in to comment.