Completed
Push — scalar-types/ui ( 162de3 )
by Kamil
22:15
created

SortByExtension::sortBy()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 20
rs 9.4285
c 1
b 0
f 0
cc 2
eloc 11
nc 1
nop 3
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