Skip to content

Instantly share code, notes, and snippets.

@DarkMukke
Created July 14, 2017 10:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save DarkMukke/f3b0243f957a9f820999e3b18766467b to your computer and use it in GitHub Desktop.
Save DarkMukke/f3b0243f957a9f820999e3b18766467b to your computer and use it in GitHub Desktop.
<?php
/**
* @license MIT
* @author Ruben Decleyn mukke@tbs-dev.co.uk>
* @created 12/02/2017
*/
namespace App\TwigExtensions;
class CustomSort extends \Twig_Extension
{
public function getFilters()
{
return array(
new \Twig_SimpleFilter('csort', function ($trav, array $options = []) {
return $this->customSort($trav, $options);
}, ['is_variadic' => true]),
);
}
/**
* Custom Sorter for twig
* The first option is always the compare function to use.
* Customer compare functions are not yet supported.
* The other arguments are the keys of the multi-dimensional array to traverse down to.
*
* If you want to compare $a['some']['deep]['level'] to $a['some']['deep]['level']
* use {{ data|csort( 'strcasecmp', 'some', 'deep', 'level') }}
*
* @param $array array Array to be sorted
* @param $options array Levels of the multidimensial array to be sorted
* @return array The Sorted array
*/
public function customSort($array, $options)
{
usort($array, function ($a, $b) use ($options) {
$sortFunc = array_shift($options);
return $sortFunc($this->getToLevel($a, $options), $this->getToLevel($b, $options));
});
return $array;
}
/**
* Recursive function to get to the right element of the multi-dimensial array to compare
*
* @param $trav
* @param array $levels
* @return mixed
*/
protected function getToLevel($trav, array $levels = [])
{
if (count($levels) > 1) {
$lvl = array_shift($levels);
return $this->getToLevel($trav[$lvl], $levels);
} elseif (count($levels) === 1) {
$lvl = array_shift($levels);
return $trav[$lvl];
} else {
return $trav;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment