forked from Sylius/Sylius
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SortByExtension.php
82 lines (68 loc) · 2 KB
/
SortByExtension.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Bundle\UiBundle\Twig;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException;
use Symfony\Component\PropertyAccess\PropertyAccess;
/**
* @author Jan Góralski <jan.goralski@lakion.com>
*/
class SortByExtension extends \Twig_Extension
{
/**
* {@inheritdoc}
*/
public function getFilters(): array
{
return [
new \Twig_Filter('sort_by', [$this, 'sortBy']),
];
}
/**
* @param iterable $iterable
* @param string $field
* @param string $order
*
* @return array
*
* @throws NoSuchPropertyException
*/
public function sortBy(iterable $iterable, string $field, string $order = 'ASC'): array
{
$array = $this->transformIterableToArray($iterable);
usort($array, function ($firstElement, $secondElement) use ($field, $order) {
$accessor = PropertyAccess::createPropertyAccessor();
$firstProperty = (string) $accessor->getValue($firstElement, $field);
$secondProperty = (string) $accessor->getValue($secondElement, $field);
$result = strcasecmp($firstProperty, $secondProperty);
if ('DESC' === $order) {
$result *= -1;
}
return $result;
});
return $array;
}
/**
* @param iterable $iterable
*
* @return array
*/
private function transformIterableToArray(iterable $iterable): array
{
if (is_array($iterable)) {
return $iterable;
}
if ($iterable instanceof \Traversable) {
return iterator_to_array($iterable);
}
throw new \RuntimeException('Cannot transform an iterable to an array.');
}
}