ModelSortTrait::sort()   B
last analyzed

Complexity

Conditions 7
Paths 4

Size

Total Lines 39

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 7

Importance

Changes 0
Metric Value
cc 7
nc 4
nop 3
dl 0
loc 39
ccs 22
cts 22
cp 1
crap 7
rs 8.3626
c 0
b 0
f 0
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 6
    private function sort(string $modelClass, array $models, array $orderBy = null): array
17
    {
18 6
        if ([] === $models) {
19 6
            return [];
20
        }
21
22 6
        if (null === $orderBy) {
23 2
            return $models;
24
        }
25
26 4
        $reflections = [];
27 4
        foreach ($orderBy as $property => $sortingDirection) {
28 4
            $reflection = new \ReflectionProperty($modelClass, $property);
29 4
            $reflection->setAccessible(true);
30
31 4
            $reflections[$property] = $reflection;
32
        }
33
34 4
        usort($models, function (ModelInterface $a, ModelInterface $b) use ($reflections, $orderBy) {
35 4
            foreach ($orderBy as $property => $sortingDirection) {
36 4
                $reflection = $reflections[$property];
37 4
                $valueA = $reflection->getValue($a);
38 4
                $valueB = $reflection->getValue($b);
39
40 4
                $sorting = $valueA <=> $valueB;
41 4
                if ($sortingDirection === 'DESC') {
42 2
                    $sorting = $sorting * -1;
43
                }
44
45 4
                if (0 !== $sorting) {
46 4
                    return $sorting;
47
                }
48
            }
49
50 4
            return 0;
51 4
        });
52
53
        return $models;
54
    }
55
}
56