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