Passed
Push — master ( f8b808...2b4fc7 )
by Chris
36:39
created

AbstractSorter::resolveEntriesOrder()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 2
nc 2
nop 3
crap 2
1
<?php
2
3
namespace WebTheory\Collection\Sorting\Abstracts;
4
5
use WebTheory\Collection\Contracts\CollectionSorterInterface;
6
use WebTheory\Collection\Enum\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 102
    protected function validateOrder($order): void
31
    {
32 102
        Order::throwExceptionIfInvalid($order);
33
    }
34
35 96
    protected function getSortingFunction(string $order): callable
36
    {
37 96
        return fn ($a, $b) => $this->doSortingOperation($a, $b, $order);
38
    }
39
40 96
    protected function doSortingOperation(object $a, object $b, string $order): int
41
    {
42 96
        return $this->compare($a, $b) * ($order === Order::Desc ? -1 : 1);
43
    }
44
45
    abstract protected function compare(object $a, object $b): int;
46
}
47