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:
Complex classes like QueryBuilderEngine often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use QueryBuilderEngine, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
19 | class QueryBuilderEngine extends BaseEngine |
||
20 | { |
||
21 | /** |
||
22 | * @param \Illuminate\Database\Query\Builder $builder |
||
23 | * @param \Yajra\Datatables\Request $request |
||
24 | */ |
||
25 | public function __construct(Builder $builder, Request $request) |
||
26 | { |
||
27 | $this->query = $builder; |
||
28 | $this->init($request, $builder); |
||
29 | } |
||
30 | |||
31 | /** |
||
32 | * Initialize attributes. |
||
33 | * |
||
34 | * @param \Yajra\Datatables\Request $request |
||
35 | * @param \Illuminate\Database\Query\Builder $builder |
||
36 | * @param string $type |
||
37 | */ |
||
38 | protected function init($request, $builder, $type = 'builder') |
||
|
|||
39 | { |
||
40 | $this->request = $request; |
||
41 | $this->query_type = $type; |
||
42 | $this->columns = $builder->columns; |
||
43 | $this->connection = $builder->getConnection(); |
||
44 | $this->prefix = $this->connection->getTablePrefix(); |
||
45 | $this->database = $this->connection->getDriverName(); |
||
46 | if ($this->isDebugging()) { |
||
47 | $this->connection->enableQueryLog(); |
||
48 | } |
||
49 | } |
||
50 | |||
51 | /** |
||
52 | * Set auto filter off and run your own filter. |
||
53 | * Overrides global search |
||
54 | * |
||
55 | * @param \Closure $callback |
||
56 | * @return $this |
||
57 | */ |
||
58 | public function filter(Closure $callback) |
||
59 | { |
||
60 | $this->overrideGlobalSearch($callback, $this->query); |
||
61 | |||
62 | return $this; |
||
63 | } |
||
64 | |||
65 | /** |
||
66 | * Organizes works |
||
67 | * |
||
68 | * @param bool $mDataSupport |
||
69 | * @param bool $orderFirst |
||
70 | * @return \Illuminate\Http\JsonResponse |
||
71 | */ |
||
72 | public function make($mDataSupport = false, $orderFirst = false) |
||
73 | { |
||
74 | return parent::make($mDataSupport, $orderFirst); |
||
75 | } |
||
76 | |||
77 | /** |
||
78 | * Count total items. |
||
79 | * |
||
80 | * @return integer |
||
81 | */ |
||
82 | public function totalCount() |
||
83 | { |
||
84 | return $this->count(); |
||
85 | } |
||
86 | |||
87 | /** |
||
88 | * Counts current query. |
||
89 | * |
||
90 | * @return int |
||
91 | */ |
||
92 | public function count() |
||
93 | { |
||
94 | $myQuery = clone $this->query; |
||
95 | // if its a normal query ( no union, having and distinct word ) |
||
96 | // replace the select with static text to improve performance |
||
97 | if (! Str::contains(Str::lower($myQuery->toSql()), ['union', 'having', 'distinct', 'order by', 'group by'])) { |
||
98 | $row_count = $this->connection->getQueryGrammar()->wrap('row_count'); |
||
99 | $myQuery->select($this->connection->raw("'1' as {$row_count}")); |
||
100 | } |
||
101 | |||
102 | return $this->connection->table($this->connection->raw('(' . $myQuery->toSql() . ') count_row_table')) |
||
103 | ->setBindings($myQuery->getBindings())->count(); |
||
104 | } |
||
105 | |||
106 | /** |
||
107 | * Perform global search. |
||
108 | * |
||
109 | * @return void |
||
110 | */ |
||
111 | public function filtering() |
||
112 | { |
||
113 | $this->query->where( |
||
114 | function ($query) { |
||
115 | $globalKeyword = $this->setupKeyword($this->request->keyword()); |
||
116 | $queryBuilder = $this->getQueryBuilder($query); |
||
117 | |||
118 | foreach ($this->request->searchableColumnIndex() as $index) { |
||
119 | $columnName = $this->getColumnName($index); |
||
120 | if ($this->isBlacklisted($columnName)) { |
||
121 | continue; |
||
122 | } |
||
123 | |||
124 | // check if custom column filtering is applied |
||
125 | if (isset($this->columnDef['filter'][$columnName])) { |
||
126 | $columnDef = $this->columnDef['filter'][$columnName]; |
||
127 | // check if global search should be applied for the specific column |
||
128 | $applyGlobalSearch = count($columnDef['parameters']) == 0 || end($columnDef['parameters']) !== false; |
||
129 | if (! $applyGlobalSearch) { |
||
130 | continue; |
||
131 | } |
||
132 | |||
133 | if ($columnDef['method'] instanceof Closure) { |
||
134 | $whereQuery = $queryBuilder->newQuery(); |
||
135 | call_user_func_array($columnDef['method'], [$whereQuery, $this->request->keyword()]); |
||
136 | $queryBuilder->addNestedWhereQuery($whereQuery, 'or'); |
||
137 | } else { |
||
138 | $this->compileColumnQuery( |
||
139 | $queryBuilder, |
||
140 | Helper::getOrMethod($columnDef['method']), |
||
141 | $columnDef['parameters'], |
||
142 | $columnName, |
||
143 | $this->request->keyword() |
||
144 | ); |
||
145 | } |
||
146 | } else { |
||
147 | if (count(explode('.', $columnName)) > 1) { |
||
148 | $eagerLoads = $this->getEagerLoads(); |
||
149 | $parts = explode('.', $columnName); |
||
150 | $relationColumn = array_pop($parts); |
||
151 | $relation = implode('.', $parts); |
||
152 | if (in_array($relation, $eagerLoads)) { |
||
153 | $this->compileRelationSearch( |
||
154 | $queryBuilder, |
||
155 | $relation, |
||
156 | $relationColumn, |
||
157 | $globalKeyword |
||
158 | ); |
||
159 | } else { |
||
160 | $this->compileGlobalSearch($queryBuilder, $columnName, $globalKeyword); |
||
161 | } |
||
162 | } else { |
||
163 | $this->compileGlobalSearch($queryBuilder, $columnName, $globalKeyword); |
||
164 | } |
||
165 | } |
||
166 | |||
167 | $this->isFilterApplied = true; |
||
168 | } |
||
169 | } |
||
170 | ); |
||
171 | } |
||
172 | |||
173 | /** |
||
174 | * Perform filter column on selected field. |
||
175 | * |
||
176 | * @param mixed $query |
||
177 | * @param string|Closure $method |
||
178 | * @param mixed $parameters |
||
179 | * @param string $column |
||
180 | * @param string $keyword |
||
181 | */ |
||
182 | protected function compileColumnQuery($query, $method, $parameters, $column, $keyword) |
||
183 | { |
||
184 | if (method_exists($query, $method) |
||
185 | && count($parameters) <= with(new \ReflectionMethod($query, $method))->getNumberOfParameters() |
||
186 | ) { |
||
187 | if (Str::contains(Str::lower($method), 'raw') |
||
188 | || Str::contains(Str::lower($method), 'exists') |
||
189 | ) { |
||
190 | call_user_func_array( |
||
191 | [$query, $method], |
||
192 | $this->parameterize($parameters, $keyword) |
||
193 | ); |
||
194 | } else { |
||
195 | call_user_func_array( |
||
196 | [$query, $method], |
||
197 | $this->parameterize($column, $parameters, $keyword) |
||
198 | ); |
||
199 | } |
||
200 | } |
||
201 | } |
||
202 | |||
203 | /** |
||
204 | * Build Query Builder Parameters. |
||
205 | * |
||
206 | * @return array |
||
207 | */ |
||
208 | protected function parameterize() |
||
209 | { |
||
210 | $args = func_get_args(); |
||
211 | $keyword = count($args) > 2 ? $args[2] : $args[1]; |
||
212 | $parameters = Helper::buildParameters($args); |
||
213 | $parameters = Helper::replacePatternWithKeyword($parameters, $keyword, '$1'); |
||
214 | |||
215 | return $parameters; |
||
216 | } |
||
217 | |||
218 | /** |
||
219 | * Get eager loads keys if eloquent. |
||
220 | * |
||
221 | * @return array |
||
222 | */ |
||
223 | protected function getEagerLoads() |
||
224 | { |
||
225 | if ($this->query_type == 'eloquent') { |
||
226 | return array_keys($this->query->getEagerLoads()); |
||
227 | } |
||
228 | |||
229 | return []; |
||
230 | } |
||
231 | |||
232 | /** |
||
233 | * Add relation query on global search. |
||
234 | * |
||
235 | * @param mixed $query |
||
236 | * @param string $relation |
||
237 | * @param string $column |
||
238 | * @param string $keyword |
||
239 | */ |
||
240 | protected function compileRelationSearch($query, $relation, $column, $keyword) |
||
241 | { |
||
242 | $myQuery = clone $this->query; |
||
243 | $myQuery->orWhereHas($relation, function ($q) use ($column, $keyword, $query) { |
||
244 | $sql = $q->select($this->connection->raw('count(1)')) |
||
245 | ->where($column, 'like', $keyword) |
||
246 | ->toSql(); |
||
247 | $sql = "($sql) >= 1"; |
||
248 | $query->orWhereRaw($sql, [$keyword]); |
||
249 | }); |
||
250 | } |
||
251 | |||
252 | /** |
||
253 | * Add a query on global search. |
||
254 | * |
||
255 | * @param mixed $query |
||
256 | * @param string $column |
||
257 | * @param string $keyword |
||
258 | */ |
||
259 | protected function compileGlobalSearch($query, $column, $keyword) |
||
260 | { |
||
261 | if ($this->isSmartSearch()) { |
||
262 | $column = $this->castColumn($column); |
||
263 | $sql = $column . ' LIKE ?'; |
||
264 | if ($this->isCaseInsensitive()) { |
||
265 | $sql = 'LOWER(' . $column . ') LIKE ?'; |
||
266 | $keyword = Str::lower($keyword); |
||
267 | } |
||
268 | |||
269 | $query->orWhereRaw($sql, [$keyword]); |
||
270 | } else { // exact match |
||
271 | $query->orWhereRaw("$column like ?", [$keyword]); |
||
272 | } |
||
273 | } |
||
274 | |||
275 | /** |
||
276 | * Wrap a column and cast in pgsql. |
||
277 | * |
||
278 | * @param string $column |
||
279 | * @return string |
||
280 | */ |
||
281 | public function castColumn($column) |
||
282 | { |
||
283 | $column = $this->connection->getQueryGrammar()->wrap($column); |
||
284 | if ($this->database === 'pgsql') { |
||
285 | $column = 'CAST(' . $column . ' as TEXT)'; |
||
286 | } elseif ($this->database === 'firebird') { |
||
287 | $column = 'CAST(' . $column . ' as VARCHAR(255))'; |
||
288 | } |
||
289 | |||
290 | return $column; |
||
291 | } |
||
292 | |||
293 | /** |
||
294 | * Perform column search. |
||
295 | * |
||
296 | * @return void |
||
297 | */ |
||
298 | public function columnSearch() |
||
353 | |||
354 | /** |
||
355 | * Get proper keyword to use for search. |
||
356 | * |
||
357 | * @param int $i |
||
358 | * @param bool $raw |
||
359 | * @return string |
||
360 | */ |
||
361 | private function getSearchKeyword($i, $raw = false) |
||
370 | |||
371 | /** |
||
372 | * Compile queries for column search. |
||
373 | * |
||
374 | * @param int $i |
||
375 | * @param mixed $column |
||
376 | * @param string $keyword |
||
377 | * @param bool $caseSensitive |
||
378 | */ |
||
379 | protected function compileColumnSearch($i, $column, $keyword, $caseSensitive = true) |
||
391 | |||
392 | /** |
||
393 | * Compile regex query column search. |
||
394 | * |
||
395 | * @param mixed $column |
||
396 | * @param string $keyword |
||
397 | * @param bool $caseSensitive |
||
398 | */ |
||
399 | protected function regexColumnSearch($column, $keyword, $caseSensitive = true) |
||
409 | |||
410 | /** |
||
411 | * Perform sorting of columns. |
||
412 | * |
||
413 | * @return void |
||
414 | */ |
||
415 | public function ordering() |
||
416 | { |
||
417 | if ($this->orderCallback) { |
||
418 | call_user_func($this->orderCallback, $this->getQueryBuilder()); |
||
419 | |||
420 | return; |
||
421 | } |
||
422 | |||
456 | |||
457 | /** |
||
458 | * Join eager loaded relation and get the related column name. |
||
459 | * |
||
460 | * @param string $relation |
||
461 | * @param string $relationColumn |
||
462 | * @return string |
||
463 | */ |
||
464 | protected function joinEagerLoadedColumn($relation, $relationColumn) |
||
508 | |||
509 | /** |
||
510 | * Perform pagination |
||
511 | * |
||
512 | * @return void |
||
513 | */ |
||
514 | public function paging() |
||
519 | |||
520 | /** |
||
521 | * Get results |
||
522 | * |
||
523 | * @return array|static[] |
||
524 | */ |
||
525 | public function results() |
||
529 | } |
||
530 |