Completed
Push — master ( 7b03c6...e1d713 )
by Arjay
01:43
created

CollectionDataTable   B

Complexity

Total Complexity 37

Size/Duplication

Total Lines 261
Duplicated Lines 4.6 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 0
Metric Value
dl 12
loc 261
rs 8.6
c 0
b 0
f 0
wmc 37
lcom 1
cbo 7

13 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A serialize() 0 4 2
A showDebugger() 0 6 1
A count() 0 4 2
B columnSearch() 12 35 6
A paging() 0 7 2
A make() 0 23 3
A revertIndexColumn() 0 12 3
A totalCount() 0 4 2
A results() 0 4 1
C globalSearch() 0 25 7
B defaultOrdering() 0 30 6
A resolveCallbackParameter() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Yajra\DataTables;
4
5
use Illuminate\Contracts\Support\Arrayable;
6
use Illuminate\Support\Arr;
7
use Illuminate\Support\Collection;
8
use Illuminate\Support\Str;
9
10
class CollectionDataTable extends DataTableAbstract
11
{
12
    /**
13
     * Collection object
14
     *
15
     * @var \Illuminate\Support\Collection
16
     */
17
    public $collection;
18
19
    /**
20
     * Collection object
21
     *
22
     * @var \Illuminate\Support\Collection
23
     */
24
    public $original;
25
26
    /**
27
     * CollectionEngine constructor.
28
     *
29
     * @param \Illuminate\Support\Collection $collection
30
     */
31
    public function __construct(Collection $collection)
32
    {
33
        $this->request    = resolve('datatables.request');
34
        $this->config     = resolve('datatables.config');
35
        $this->collection = $collection;
36
        $this->original   = $collection;
37
        $this->columns    = array_keys($this->serialize($collection->first()));
38
    }
39
40
    /**
41
     * Serialize collection
42
     *
43
     * @param  mixed $collection
44
     * @return mixed|null
45
     */
46
    protected function serialize($collection)
47
    {
48
        return $collection instanceof Arrayable ? $collection->toArray() : (array) $collection;
49
    }
50
51
    /**
52
     * Append debug parameters on output.
53
     *
54
     * @param  array $output
55
     * @return array
56
     */
57
    public function showDebugger(array $output)
58
    {
59
        $output["input"] = $this->request->all();
60
61
        return $output;
62
    }
63
64
    /**
65
     * Count results.
66
     *
67
     * @return integer
68
     */
69
    public function count()
70
    {
71
        return $this->collection->count() > $this->totalRecords ? $this->totalRecords : $this->collection->count();
72
    }
73
74
    /**
75
     * Perform column search.
76
     *
77
     * @return void
78
     */
79
    public function columnSearch()
80
    {
81
        $columns = $this->request->get('columns');
82
        for ($i = 0, $c = count($columns); $i < $c; $i++) {
83
            if ($this->request->isColumnSearchable($i)) {
84
                $this->isFilterApplied = true;
85
86
                $regex   = $this->request->isRegex($i);
87
                $column  = $this->getColumnName($i);
88
                $keyword = $this->request->columnKeyword($i);
89
90
                $this->collection = $this->collection->filter(
91
                    function ($row) use ($column, $keyword, $regex) {
92
                        $data = $this->serialize($row);
93
94
                        $value = Arr::get($data, $column);
95
96
                        if ($this->config->isCaseInsensitive()) {
97 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...
98
                                return preg_match('/' . $keyword . '/i', $value) == 1;
99
                            } else {
100
                                return strpos(Str::lower($value), Str::lower($keyword)) !== false;
101
                            }
102 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...
103
                            if ($regex) {
104
                                return preg_match('/' . $keyword . '/', $value) == 1;
105
                            } else {
106
                                return strpos($value, $keyword) !== false;
107
                            }
108
                        }
109
                    }
110
                );
111
            }
112
        }
113
    }
114
115
    /**
116
     * Perform pagination.
117
     *
118
     * @return void
119
     */
120
    public function paging()
121
    {
122
        $this->collection = $this->collection->slice(
123
            $this->request->input('start'),
124
            (int) $this->request->input('length') > 0 ? $this->request->input('length') : 10
125
        );
126
    }
127
128
    /**
129
     * Organizes works.
130
     *
131
     * @param bool $mDataSupport
132
     * @return \Illuminate\Http\JsonResponse
133
     */
134
    public function make($mDataSupport = true)
135
    {
136
        try {
137
            $this->totalRecords = $this->totalCount();
138
139
            if ($this->totalRecords) {
140
                $results   = $this->results();
141
                $processed = $this->processResults($results, $mDataSupport);
142
                $output    = $this->transform($results, $processed);
143
144
                $this->collection = collect($output);
145
                $this->ordering();
146
                $this->filterRecords();
147
                $this->paginate();
148
149
                $this->revertIndexColumn($mDataSupport);
150
            }
151
152
            return $this->render($this->collection->values()->all());
153
        } catch (\Exception $exception) {
154
            return $this->errorResponse($exception);
155
        }
156
    }
157
158
    /**
159
     * Revert transformed DT_Row_Index back to it's original values.
160
     *
161
     * @param bool $mDataSupport
162
     */
163
    private function revertIndexColumn($mDataSupport)
164
    {
165
        if ($this->columnDef['index']) {
166
            $index = $mDataSupport ? config('datatables.index_column', 'DT_Row_Index') : 0;
167
            $start = (int) $this->request->input('start');
168
            $this->collection->transform(function ($data) use ($index, &$start) {
169
                $data[$index] = ++$start;
170
171
                return $data;
172
            });
173
        }
174
    }
175
176
    /**
177
     * Count total items.
178
     *
179
     * @return integer
180
     */
181
    public function totalCount()
182
    {
183
        return $this->totalRecords ? $this->totalRecords : $this->collection->count();
184
    }
185
186
    /**
187
     * Get results.
188
     *
189
     * @return mixed
190
     */
191
    public function results()
192
    {
193
        return $this->collection->all();
194
    }
195
196
    /**
197
     * Perform global search for the given keyword.
198
     *
199
     * @param string $keyword
200
     */
201
    protected function globalSearch($keyword)
202
    {
203
        $columns = $this->request->columns();
204
        $keyword = $this->config->isCaseInsensitive() ? Str::lower($keyword) : $keyword;
205
206
        $this->collection = $this->collection->filter(function ($row) use ($columns, $keyword) {
207
            $this->isFilterApplied = true;
208
209
            $data = $this->serialize($row);
210
            foreach ($this->request->searchableColumnIndex() as $index) {
211
                $column = $this->getColumnName($index);
212
                $value  = Arr::get($data, $column);
213
                if (!$value || is_array($value)) {
214
                    continue;
215
                }
216
217
                $value = $this->config->isCaseInsensitive() ? Str::lower($value) : $value;
218
                if (Str::contains($value, $keyword)) {
219
                    return true;
220
                }
221
            }
222
223
            return false;
224
        });
225
    }
226
227
    /**
228
     * Perform default query orderBy clause.
229
     */
230
    protected function defaultOrdering()
231
    {
232
        $criteria = $this->request->orderableColumns();
233
        if (! empty($criteria)) {
234
            $sorter = function ($a, $b) use ($criteria) {
235
                foreach ($criteria as $orderable) {
236
                    $column = $this->getColumnName($orderable['column']);
237
                    $direction = $orderable['direction'];
238
                    if ($direction === 'desc') {
239
                        $first = $b;
240
                        $second = $a;
241
                    } else {
242
                        $first = $a;
243
                        $second = $b;
244
                    }
245
                    if ($this->config->isCaseInsensitive()) {
246
                        $cmp = strnatcasecmp($first[$column], $second[$column]);
247
                    } else {
248
                        $cmp = strnatcmp($first[$column], $second[$column]);
249
                    }
250
                    if ($cmp != 0) {
251
                        return $cmp;
252
                    }
253
                }
254
                // all elements were equal
255
                return 0;
256
            };
257
            $this->collection = $this->collection->sort($sorter);
258
        }
259
    }
260
261
    /**
262
     * Resolve callback parameter instance.
263
     *
264
     * @return $this
265
     */
266
    protected function resolveCallbackParameter()
267
    {
268
        return $this;
269
    }
270
}
271