Passed
Push — master ( 62919d...1f65fa )
by Iman
04:23
created

Search   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 87
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 87
rs 10
c 0
b 0
f 0
wmc 12

5 Methods

Rating   Name   Duplication   Size   Complexity  
A limitRows() 0 4 2
A searchData() 0 23 3
A decode() 0 4 1
A orderRows() 0 6 2
A filterRow() 0 12 4
1
<?php
2
3
namespace Crocodicstudio\Crudbooster\CBCoreModule;
4
5
use Illuminate\Support\Facades\DB;
6
7
class Search
8
{
9
    private $rows;
10
11
    /**
12
     * @param $data
13
     * @param $q
14
     * @param $id
15
     *
16
     * @return mixed
17
     */
18
    function searchData($data, $q, $id)
19
    {
20
        $data = $this->decode($data);
21
        $fieldValue = $data['field_value'];
22
23
        $table = $data['table'];
24
        $this->rows = DB::table($table);
25
        $this->rows->select($table.'.*');
26
27
        $this->orderRows($data, $fieldValue);
28
        $this->limitRows($data);
29
30
        if ($data['field_label']) {
31
            $this->rows->addselect($data['field_label'].' as text');
32
        }
33
34
        if ($fieldValue) {
35
            $this->rows->addselect($fieldValue.' as id');
36
        }
37
38
        $this->filterRow($data, $q, $id, $fieldValue);
39
40
        return $this->rows->get();
41
    }
42
43
    /**
44
     * @param $data
45
     * @param $fieldValue
46
     */
47
    private function orderRows($data, $fieldValue)
48
    {
49
        if ($data['sql_orderby']) {
50
            $this->rows->orderbyRaw($data['sql_orderby']);
51
        } else {
52
            $this->rows->orderby($fieldValue, 'desc');
53
        }
54
    }
55
56
    /**
57
     * @param $data
58
     */
59
    private function limitRows($data)
60
    {
61
        $num = (int)$data['limit'] ?: 10;
62
        $this->rows->take($num);
63
    }
64
65
    /**
66
     * @param $data
67
     * @param $q
68
     * @param $id
69
     * @param $fieldValue
70
     */
71
    private function filterRow($data, $q, $id, $fieldValue)
72
    {
73
        if ($data['sql_where']) {
74
            $this->rows->whereRaw($data['sql_where']);
75
        }
76
77
        if ($q) {
78
            $this->rows->where($data['field_label'], 'like', '%'.$q.'%');
79
        }
80
81
        if ($id) {
82
            $this->rows->where($fieldValue, $id);
83
        }
84
    }
85
86
    /**
87
     * @param $data
88
     * @return bool|mixed|string
89
     */
90
    private function decode($data)
91
    {
92
        $data = base64_decode($data);
93
        return json_decode($data, true);
94
    }
95
}