| Total Complexity | 7 |
| Total Lines | 42 |
| Duplicated Lines | 0 % |
| Coverage | 100% |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
| 1 | <?php |
||
| 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 |
|
| 47 | } |
||
| 48 | |||
| 49 | abstract protected function resolveValue(object $object); |
||
| 50 | } |
||
| 51 |