Passed
Push — master ( a4571b...162929 )
by Chris
07:18
created

AbstractSorter::getSortingFunction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace WebTheory\Collection\Sorting\Abstracts;
4
5
use WebTheory\Collection\Contracts\CollectionSorterInterface;
6
use WebTheory\Collection\Sorting\Order;
7
8
abstract class AbstractSorter implements CollectionSorterInterface
9
{
10 102
    public function sort(array $array, string $order): array
11
    {
12 102
        $this->validateOrder($order);
13
14 96
        return $this->getSortedArray($array, $order);
15
    }
16
17 96
    protected function getSortedArray(array $array, string $order): array
18
    {
19 96
        $function = $this->getSortingFunction($order);
20
21 96
        if (array_is_list($array)) {
22 42
            usort($array, $function);
23
        } else {
24 54
            uasort($array, $function);
25
        }
26
27 96
        return $array;
28
    }
29
30 96
    protected function getSortingFunction(string $order): callable
31
    {
32 96
        return fn ($a, $b): int => $this->resolveEntriesOrder(
33 96
            $this->resolveValue($a),
34 96
            $this->resolveValue($b),
35
            $order
36
        );
37
    }
38
39 96
    protected function resolveEntriesOrder($a, $b, string $order): int
40
    {
41 96
        return ($a <=> $b) * ($order === Order::DESC ? -1 : 1);
42
    }
43
44 102
    protected function validateOrder($order): void
45
    {
46 102
        Order::throwExceptionIfInvalid($order);
47
    }
48
49
    abstract protected function resolveValue(object $object);
50
}
51