Passed
Push — master ( be985d...bcc337 )
by Iman
04:39
created

Order::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace crocodicstudio\crudbooster\CBCoreModule\Index;
4
5
class Order
6
{
7
    /**
8
     * @param $query
9
     * @param $table
10
     * @param $orderBy
11
     * @param $primaryKey
12
     */
13
    public function handle($query, $table, $orderBy, $primaryKey)
14
    {
15
        if (! $orderBy) {
16
            $query->orderby($table.'.'.$primaryKey, 'desc');
17
            return;
18
        }
19
        if (is_string($orderBy)) {
20
            $orderBy = $this->normalizeOrderBy($orderBy);
21
        }
22
23
        $this->orderRows($query, $table, $orderBy);
24
    }
25
26
    /**
27
     * @param $query
28
     * @param $table
29
     * @param $orderby
30
     */
31
    private function orderRows($query, $table, $orderby)
32
    {
33
        foreach ($orderby as $key => $value) {
34
            if (strpos($key, '.')) {
35
                $table = explode(".", $key)[0];
36
            }
37
            $query->orderby($table.'.'.$key, $value);
38
        }
39
    }
40
41
    /**
42
     * @param $orderBy
43
     * @return array
44
     */
45
    private function normalizeOrderBy($orderBy)
46
    {
47
        $x = [];
48
        foreach (explode(";", $orderBy) as $by) {
49
            $by = explode(",", $by);
50
            $x[$by[0]] = $by[1];
51
        }
52
53
        return $x;
54
    }
55
}