Completed
Push — master ( 0a6a25...887b35 )
by Arjay
01:45
created

CollectionEngine::count()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
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
     * Organizes works.
136
     *
137
     * @param bool $mDataSupport
138
     * @return \Illuminate\Http\JsonResponse
139
     */
140
    public function make($mDataSupport = true)
141
    {
142
        try {
143
            $this->totalRecords = $this->totalCount();
144
145
            if ($this->totalRecords) {
146
                $results   = $this->results();
147
                $processed = $this->processResults($results, $mDataSupport);
148
                $output    = $this->transform($results, $processed);
149
150
                $this->collection = collect($output);
151
                $this->ordering();
152
                $this->filterRecords();
153
                $this->paginate();
154
            }
155
156
            return $this->render($this->collection->values()->all());
157
        } catch (\Exception $exception) {
158
            return $this->errorResponse($exception);
159
        }
160
    }
161
162
    /**
163
     * Count total items.
164
     *
165
     * @return integer
166
     */
167
    public function totalCount()
168
    {
169
        return $this->totalRecords ? $this->totalRecords : $this->collection->count();
170
    }
171
172
    /**
173
     * Get results.
174
     *
175
     * @return mixed
176
     */
177
    public function results()
178
    {
179
        return $this->collection->all();
180
    }
181
182
    /**
183
     * Perform global search for the given keyword.
184
     *
185
     * @param string $keyword
186
     */
187
    protected function globalSearch($keyword)
188
    {
189
        $columns = $this->request->columns();
190
        $keyword = $this->config->isCaseInsensitive() ? Str::lower($keyword) : $keyword;
191
192
        $this->collection = $this->collection->filter(function ($row) use ($columns, $keyword) {
193
            $this->isFilterApplied = true;
194
195
            $data = $this->serialize($row);
196
            foreach ($this->request->searchableColumnIndex() as $index) {
197
                $column = $this->getColumnName($index);
198
                $value  = Arr::get($data, $column);
199
                if (!$value || is_array($value)) {
200
                    continue;
201
                }
202
203
                $value = $this->config->isCaseInsensitive() ? Str::lower($value) : $value;
204
                if (Str::contains($value, $keyword)) {
205
                    return true;
206
                }
207
            }
208
209
            return false;
210
        });
211
    }
212
213
    /**
214
     * Perform default query orderBy clause.
215
     */
216
    protected function defaultOrdering()
217
    {
218
        $criteria = $this->request->orderableColumns();
219
        if ($criteria) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $criteria of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
220
            $comparer = function ($a, $b) use ($criteria) {
221
                foreach ($criteria as $orderable) {
222
                    $column = $this->getColumnName($orderable['column']);
223
                    $direction = $orderable['direction'];
224
                    if ($direction === 'desc') {
225
                        $first = $b;
226
                        $second = $a;
227
                    } else {
228
                        $first = $a;
229
                        $second = $b;
230
                    }
231
                    if ($this->config->isCaseInsensitive()) {
232
                        $cmp = strnatcasecmp($first[$column], $second[$column]);
233
                    } else {
234
                        $cmp = strnatcmp($first[$column], $second[$column]);
235
                    }
236
                    if ($cmp != 0) {
237
                        return $cmp;
238
                    }
239
                }
240
                // all elements were equal
241
                return 0;
242
            };
243
            $this->collection = $this->collection->sort($comparer);
244
        }
245
    }
246
247
    /**
248
     * Resolve callback parameter instance.
249
     *
250
     * @return $this
251
     */
252
    protected function resolveCallbackParameter()
253
    {
254
        return $this;
255
    }
256
}
257