Completed
Push — master ( e96c6d...2336af )
by Arjay
01:52
created

CollectionEngine::resolveCallbackParameter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 4
rs 10
1
<?php
2
3
namespace Yajra\Datatables\Engines;
4
5
use Illuminate\Contracts\Support\Arrayable;
6
use Illuminate\Support\Arr;
7
use Illuminate\Support\Collection;
8
use Illuminate\Support\Str;
9
10
/**
11
 * Class CollectionEngine.
12
 *
13
 * @package Yajra\Datatables\Engines
14
 * @author  Arjay Angeles <[email protected]>
15
 */
16
class CollectionEngine extends BaseEngine
17
{
18
    /**
19
     * Collection object
20
     *
21
     * @var \Illuminate\Support\Collection
22
     */
23
    public $collection;
24
25
    /**
26
     * Collection object
27
     *
28
     * @var \Illuminate\Support\Collection
29
     */
30
    public $original;
31
32
    /**
33
     * CollectionEngine constructor.
34
     *
35
     * @param \Illuminate\Support\Collection $collection
36
     */
37
    public function __construct(Collection $collection)
38
    {
39
        $this->request    = resolve('datatables.request');
40
        $this->config     = resolve('datatables.config');
41
        $this->collection = $collection;
42
        $this->original   = $collection;
43
        $this->columns    = array_keys($this->serialize($collection->first()));
44
    }
45
46
    /**
47
     * Serialize collection
48
     *
49
     * @param  mixed $collection
50
     * @return mixed|null
51
     */
52
    protected function serialize($collection)
53
    {
54
        return $collection instanceof Arrayable ? $collection->toArray() : (array) $collection;
55
    }
56
57
    /**
58
     * Append debug parameters on output.
59
     *
60
     * @param  array $output
61
     * @return array
62
     */
63
    public function showDebugger(array $output)
64
    {
65
        $output["input"] = $this->request->all();
66
67
        return $output;
68
    }
69
70
    /**
71
     * Count results.
72
     *
73
     * @return integer
74
     */
75
    public function count()
76
    {
77
        return $this->collection->count() > $this->totalRecords ? $this->totalRecords : $this->collection->count();
78
    }
79
80
    /**
81
     * Perform column search.
82
     *
83
     * @return void
84
     */
85
    public function columnSearch()
86
    {
87
        $columns = $this->request->get('columns');
88
        for ($i = 0, $c = count($columns); $i < $c; $i++) {
89
            if ($this->request->isColumnSearchable($i)) {
90
                $this->isFilterApplied = true;
91
92
                $regex   = $this->request->isRegex($i);
93
                $column  = $this->getColumnName($i);
94
                $keyword = $this->request->columnKeyword($i);
95
96
                $this->collection = $this->collection->filter(
97
                    function ($row) use ($column, $keyword, $regex) {
98
                        $data = $this->serialize($row);
99
100
                        $value = Arr::get($data, $column);
101
102
                        if ($this->config->isCaseInsensitive()) {
103 View Code Duplication
                            if ($regex) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
104
                                return preg_match('/' . $keyword . '/i', $value) == 1;
105
                            } else {
106
                                return strpos(Str::lower($value), Str::lower($keyword)) !== false;
107
                            }
108 View Code Duplication
                        } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
109
                            if ($regex) {
110
                                return preg_match('/' . $keyword . '/', $value) == 1;
111
                            } else {
112
                                return strpos($value, $keyword) !== false;
113
                            }
114
                        }
115
                    }
116
                );
117
            }
118
        }
119
    }
120
121
    /**
122
     * Perform pagination.
123
     *
124
     * @return void
125
     */
126
    public function paging()
127
    {
128
        $this->collection = $this->collection->slice(
129
            $this->request->input('start'),
130
            (int) $this->request->input('length') > 0 ? $this->request->input('length') : 10
131
        );
132
    }
133
134
    /**
135
     * Get results.
136
     *
137
     * @return mixed
138
     */
139
    public function results()
140
    {
141
        return $this->collection->all();
142
    }
143
144
    /**
145
     * Organizes works.
146
     *
147
     * @param bool $mDataSupport
148
     * @return \Illuminate\Http\JsonResponse
149
     */
150
    public function make($mDataSupport = false)
151
    {
152
        try {
153
            $this->totalRecords = $this->totalCount();
154
155
            if ($this->totalRecords) {
156
                $data   = $this->getProcessedData($mDataSupport);
157
                $output = $this->transform($data);
158
159
                $this->collection = collect($output);
160
                $this->ordering();
161
                $this->filterRecords();
162
                $this->paginate();
163
            }
164
165
            return $this->render($this->collection->values()->all());
166
        } catch (\Exception $exception) {
167
            return $this->errorResponse($exception);
168
        }
169
    }
170
171
    /**
172
     * Count total items.
173
     *
174
     * @return integer
175
     */
176
    public function totalCount()
177
    {
178
        return $this->totalRecords ? $this->totalRecords : $this->collection->count();
179
    }
180
181
    /**
182
     * Perform global search for the given keyword.
183
     *
184
     * @param string $keyword
185
     */
186
    protected function globalSearch($keyword)
187
    {
188
        $columns = $this->request->columns();
189
        if ($this->config->isCaseInsensitive()) {
190
            $keyword = Str::lower($keyword);
191
        }
192
193
        $this->collection = $this->collection->filter(function ($row) use ($columns, $keyword) {
194
            $this->isFilterApplied = true;
195
196
            $data = $this->serialize($row);
197
            foreach ($this->request->searchableColumnIndex() as $index) {
198
                $column = $this->getColumnName($index);
199
                $value  = Arr::get($data, $column);
200
                if (!$value || is_array($value)) {
201
                    continue;
202
                }
203
204
                $value = $this->config->isCaseInsensitive() ? Str::lower($value) : $value;
205
                if (Str::contains($value, $keyword)) {
206
                    return true;
207
                }
208
            }
209
210
            return false;
211
        });
212
    }
213
214
    /**
215
     * Perform default query orderBy clause.
216
     */
217
    protected function defaultOrdering()
218
    {
219
        foreach ($this->request->orderableColumns() as $orderable) {
220
            $column = $this->getColumnName($orderable['column']);
221
222
            $options = SORT_NATURAL;
223
            if ($this->config->isCaseInsensitive()) {
224
                $options = SORT_NATURAL | SORT_FLAG_CASE;
225
            }
226
227
            $this->collection = $this->collection->sortBy(function ($row) use ($column) {
228
                $data = $this->serialize($row);
229
230
                return Arr::get($data, $column);
231
            }, $options);
232
233
            if ($orderable['direction'] == 'desc') {
234
                $this->collection = $this->collection->reverse();
235
            }
236
        }
237
    }
238
239
    /**
240
     * Resolve callback parameter instance.
241
     *
242
     * @return $this
243
     */
244
    protected function resolveCallbackParameter()
245
    {
246
        return $this;
247
    }
248
}
249