|
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
|
|
|
namespace Sylius\Bundle\UiBundle\Twig; |
|
13
|
|
|
|
|
14
|
|
|
use Doctrine\Common\Collections\Collection; |
|
15
|
|
|
use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException; |
|
16
|
|
|
use Symfony\Component\PropertyAccess\PropertyAccess; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* @author Jan Góralski <[email protected]> |
|
20
|
|
|
*/ |
|
21
|
|
|
class SortByExtension extends \Twig_Extension |
|
22
|
|
|
{ |
|
23
|
|
|
/** |
|
24
|
|
|
* {@inheritdoc} |
|
25
|
|
|
*/ |
|
26
|
|
|
public function getFilters() |
|
27
|
|
|
{ |
|
28
|
|
|
return [ |
|
29
|
|
|
new \Twig_SimpleFilter('sort_by', [$this, 'sortBy']), |
|
30
|
|
|
]; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* @param array|Collection $array |
|
35
|
|
|
* @param string $field |
|
36
|
|
|
* @param string $order |
|
37
|
|
|
* |
|
38
|
|
|
* @return array |
|
39
|
|
|
* |
|
40
|
|
|
* @throws NoSuchPropertyException |
|
41
|
|
|
*/ |
|
42
|
|
|
public function sortBy($array, $field, $order = 'ASC') |
|
43
|
|
|
{ |
|
44
|
|
|
if ($array instanceof Collection) { |
|
45
|
|
|
$array = $array->toArray(); |
|
46
|
|
|
} |
|
47
|
|
|
if (1 >= count($array)) { |
|
48
|
|
|
return $array; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** "@usort" so it won't explode on php 5.6 */ |
|
52
|
|
|
@usort($array, function ($firstElement, $secondElement) use ($field, $order) { |
|
|
|
|
|
|
53
|
|
|
$accessor = PropertyAccess::createPropertyAccessor(); |
|
54
|
|
|
|
|
55
|
|
|
$firstProperty = $accessor->getValue($firstElement, $field); |
|
56
|
|
|
$secondProperty = $accessor->getValue($secondElement, $field); |
|
57
|
|
|
|
|
58
|
|
|
$result = strcasecmp($firstProperty, $secondProperty); |
|
59
|
|
|
if ('DESC' === $order) { |
|
60
|
|
|
$result *= -1; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
return $result; |
|
64
|
|
|
}); |
|
65
|
|
|
|
|
66
|
|
|
return $array; |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
/** |
|
70
|
|
|
* {@inheritdoc} |
|
71
|
|
|
*/ |
|
72
|
|
|
public function getName() |
|
73
|
|
|
{ |
|
74
|
|
|
return 'sort_by'; |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|
If you suppress an error, we recommend checking for the error condition explicitly: