Created
May 1, 2020 09:40
-
-
Save bartwttewaall/d11d3d667569c3a729a122242efa66a5 to your computer and use it in GitHub Desktop.
Twig usort extension
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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