Passed
Push — master ( 1b1398...893bce )
by Dominik
02:29
created

ModelSortTrait   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 56.52%

Importance

Changes 0
Metric Value
wmc 7
lcom 0
cbo 0
dl 0
loc 49
ccs 13
cts 23
cp 0.5652
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
C sort() 0 39 7
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
     *
14
     * @return array
15
     */
16 4
    private function sort(string $modelClass, array $models, array $orderBy = null): array
17
    {
18 4
        if ([] === $models) {
19 4
            return [];
20
        }
21
22 4
        if (null === $orderBy) {
23 2
            return $models;
24
        }
25
26 2
        $reflections = [];
27 2
        foreach ($orderBy as $property => $sortingDirection) {
28 2
            $reflection = new \ReflectionProperty($modelClass, $property);
29 2
            $reflection->setAccessible(true);
30
31 2
            $reflections[$property] = $reflection;
32
        }
33
34 2
        usort($models, function (ModelInterface $a, ModelInterface $b) use ($reflections, $orderBy) {
35
            foreach ($orderBy as $property => $sortingDirection) {
36
                $reflection = $reflections[$property];
37
                $valueA = $reflection->getValue($a);
38
                $valueB = $reflection->getValue($b);
39
40
                $sorting = $valueA <=> $valueB;
41
                if ($sortingDirection === 'DESC') {
42
                    $sorting = $sorting * -1;
43
                }
44
45
                if (0 !== $sorting) {
46
                    return $sorting;
47
                }
48
            }
49
50
            return 0;
51 2
        });
52
53 2
        return $models;
54
    }
55
}
56