Passed
Pull Request — master (#1095)
by Iman
03:10
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
     * Order constructor.
9
     *
10
     * @param $ctrl
11
     */
12
    public function __construct($ctrl)
13
    {
14
        $this->ctrl = $ctrl;
0 ignored issues
show
Bug Best Practice introduced by
The property ctrl does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
15
    }
16
17
    /**
18
     * @param $result
19
     * @param $table
20
     * @param $index
21
     */
22
    function handle($result, $table)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
23
    {
24
        $orderby = $this->ctrl->orderby;
25
        if (! $orderby) {
26
            $result->orderby($table.'.'.$this->ctrl->primary_key, 'desc');
27
            return;
28
        }
29
        if (is_string($orderby)) {
30
            $orderby = $this->normalizeOrderBy($orderby);
31
        }
32
33
        $this->orderRows($result, $table, $orderby);
34
    }
35
36
    /**
37
     * @param $result
38
     * @param $table
39
     * @param $orderby
40
     */
41
    private function orderRows($result, $table, $orderby)
42
    {
43
        foreach ($orderby as $key => $value) {
44
            if (strpos($key, '.')) {
45
                $table = explode(".", $key)[0];
46
            }
47
            $result->orderby($table.'.'.$key, $value);
48
        }
49
    }
50
51
    /**
52
     * @param $orderby
53
     * @return array
54
     */
55
    private function normalizeOrderBy($orderby)
56
    {
57
        $x = [];
58
        foreach (explode(";", $orderby) as $by) {
59
            $by = explode(",", $by);
60
            $x[$by[0]] = $by[1];
61
        }
62
63
        return $x;
64
    }
65
}