Skip to content
This repository has been archived by the owner on Dec 27, 2018. It is now read-only.

Commit

Permalink
New Twig filter: sortByTitle.
Browse files Browse the repository at this point in the history
  • Loading branch information
ArnaudLigny committed Jul 3, 2016
1 parent f722e4f commit 7f91ef1
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/Renderer/TwigExtensionSorts.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,47 @@ public function getName()
public function getFilters()
{
$filters = [
new \Twig_SimpleFilter('sortByTitle', [$this, 'sortByTitle']),
new \Twig_SimpleFilter('sortByWeight', [$this, 'sortByWeight']),
new \Twig_SimpleFilter('sortByDate', [$this, 'sortByDate']),
];

return $filters;
}

/**
* Sort by title.
*
* @param $array|\PHPoole\Collection\CollectionInterface
*
* @return mixed
*/
public function sortByTitle($array)
{
$callback = function ($a, $b) {
if (!isset($a['title'])) {
return 1;
}
if (!isset($b['title'])) {
return -1;
}
if ($a['title'] == $b['title']) {
return 0;
}

return ($a['title'] < $b['title']) ? -1 : 1;
};

if ($array instanceof \PHPoole\Collection\AbstractCollection) {
$array = $array->toArray();
}
if (is_array($array)) {
usort($array, $callback);
}

return $array;
}

/**
* Sort by weight.
*
Expand Down

0 comments on commit 7f91ef1

Please sign in to comment.