Completed
Push — master ( 5d2be1...68f0c9 )
by Dominik
01:57
created

ModelSortTrait::sort()   C

Complexity

Conditions 7
Paths 4

Size

Total Lines 36
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 36
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 20
nc 4
nop 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chubbyphp\Model;
6
7
trait ModelSortTrait
8
{
9
    /**
10
     * @param string $modelClass
11
     * @param array $models
12
     * @param array|null $orderBy
13
     * @return array
14
     */
15
    private function sort(string $modelClass, array $models, array $orderBy = null): array
16
    {
17
        if ([] === $models) {
18
            return [];
19
        }
20
21
        if (null === $orderBy) {
22
            return $models;
23
        }
24
25
        $reflections = [];
26
        foreach ($orderBy as $property => $sortingDirection) {
27
            $reflection = new \ReflectionProperty($modelClass, $property);
28
            $reflection->setAccessible(true);
29
30
            $reflections[$property] = $reflection;
31
        }
32
33
        usort($models, function (ModelInterface $a, ModelInterface $b) use ($reflections, $orderBy) {
34
            foreach ($orderBy as $property => $sortingDirection) {
35
                $reflection = $reflections[$property];
36
                $sorting = strcmp($reflection->getValue($a), $reflection->getValue($b));
37
                if ($sortingDirection === 'DESC') {
38
                    $sorting = $sorting * -1;
39
                }
40
41
                if (0 !== $sorting) {
42
                    return $sorting;
43
                }
44
            }
45
46
            return 0;
47
        });
48
49
        return $models;
50
    }
51
}
52