AbstractSorter   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 12
c 1
b 0
f 0
dl 0
loc 38
ccs 15
cts 15
cp 1
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A sort() 0 5 1
A getSortedArray() 0 11 2
A validateOrder() 0 3 1
A doSortingOperation() 0 3 2
A getSortingFunction() 0 3 1
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 72
    public function sort(array $array, string $order): array
11
    {
12 72
        $this->validateOrder($order);
13
14 68
        return $this->getSortedArray($array, $order);
15
    }
16
17 68
    protected function getSortedArray(array $array, string $order): array
18
    {
19 68
        $function = $this->getSortingFunction($order);
20
21 68
        if (array_is_list($array)) {
22 34
            usort($array, $function);
23
        } else {
24 34
            uasort($array, $function);
25
        }
26
27 68
        return $array;
28
    }
29
30 72
    protected function validateOrder($order): void
31
    {
32 72
        Order::throwExceptionIfInvalid($order);
33
    }
34
35 68
    protected function getSortingFunction(string $order): callable
36
    {
37 68
        return fn ($a, $b) => $this->doSortingOperation($a, $b, $order);
38
    }
39
40 68
    protected function doSortingOperation(object $a, object $b, string $order): int
41
    {
42 68
        return $this->compare($a, $b) * ($order === Order::Desc ? -1 : 1);
43
    }
44
45
    abstract protected function compare(object $a, object $b): int;
46
}
47