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

Order   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 49
c 0
b 0
f 0
rs 10
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A normalizeOrderBy() 0 9 2
A orderRows() 0 7 3
A handle() 0 11 3
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
}