Skip to content

Instantly share code, notes, and snippets.

@bartwttewaall
Created May 1, 2020 09:40
Show Gist options
  • Save bartwttewaall/d11d3d667569c3a729a122242efa66a5 to your computer and use it in GitHub Desktop.
Save bartwttewaall/d11d3d667569c3a729a122242efa66a5 to your computer and use it in GitHub Desktop.
Twig usort extension
<?php
declare(strict_types=1);
namespace App\MyBundle\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
final class MyExtensions extends AbstractExtension
{
public function getFilters(): array
{
return [
new TwigFilter('usort', [$this, 'usortFilter']),
];
}
public function usortFilter($array, string $prop, string $mode = 'ASC')
{
$asc = 'ASC' == strtoupper($mode) ? 1 : -1;
usort($array, function ($a, $b) use ($prop, $asc) {
$value1 = is_object($a) ? call_user_func([$a, 'get'.ucfirst($prop)]) : $a['code'];
$value2 = is_object($b) ? call_user_func([$b, 'get'.ucfirst($prop)]) : $b['code'];
return ($value1 == $value2) ? 0 : ($value1 < $value2 ? -1 : 1) * $asc;
});
return $array;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment