SortHandler::apply()   B
last analyzed

Complexity

Conditions 5
Paths 2

Size

Total Lines 20
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 16
cts 16
cp 1
rs 8.8571
c 0
b 0
f 0
nc 2
cc 5
eloc 14
nop 1
crap 5
1
<?php
2
3
namespace Nayjest\Querying\Handler\PostProcess;
4
5
use Nayjest\Querying\Handler\AbstractHandler;
6
use Nayjest\Querying\Handler\Priority;
7
use Nayjest\Querying\Operation\SortOperation;
8
use Nayjest\Querying\Row\RowInterface;
9
10
class SortHandler extends AbstractHandler
11
{
12 1
    public function getPriority()
13
    {
14 1
        return Priority::POST_PROCESS - 2;
15
    }
16
17
    /**
18
     * Applies operation to source and returns modified source.
19
     *
20
     * @param $src
21
     * @return mixed
22
     */
23 1
    public function apply($src)
24
    {
25
        /** @var SortOperation $operation */
26 1
        $operation = $this->operation;
27 1
        $field = $operation->getField();
28 1
        $desc = $operation->getOrder() === SortOperation::DESC;
29 1
        if (!is_array($src)) {
30 1
            $src = iterator_to_array($src);
31 1
        }
32 1
        usort($src, function (RowInterface $row1, RowInterface $row2) use ($field, $desc) {
33 1
            $val1 = $row1->get($field);
34 1
            $val2 = $row2->get($field);
35 1
            if ($val1 == $val2) {
36 1
                return 0;
37
            }
38 1
            $res = $val1 < $val2 ? -1 : 1;
39 1
            return $desc ? -$res : $res;
40 1
        });
41 1
        return $src;
42
    }
43
}
44