Completed
Push — symfony3-fqcn ( fc44dc...d46cdc )
by Kamil
34:08 queued 14:53
created

SortByExtension   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 5
dl 0
loc 56
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getFilters() 0 6 1
B sortBy() 0 26 4
A getName() 0 4 1
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) {
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
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