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 |
||
| 21 | class QueryBuilderEngine extends BaseEngine |
||
| 22 | { |
||
| 23 | /** |
||
| 24 | * @param \Illuminate\Database\Query\Builder $builder |
||
| 25 | * @param \Yajra\Datatables\Request $request |
||
| 26 | */ |
||
| 27 | public function __construct(Builder $builder, Request $request) |
||
| 28 | { |
||
| 29 | $this->query = $builder; |
||
| 30 | $this->init($request, $builder); |
||
| 31 | } |
||
| 32 | |||
| 33 | /** |
||
| 34 | * Initialize attributes. |
||
| 35 | * |
||
| 36 | * @param \Yajra\Datatables\Request $request |
||
| 37 | * @param \Illuminate\Database\Query\Builder $builder |
||
| 38 | * @param string $type |
||
| 39 | */ |
||
| 40 | protected function init($request, $builder, $type = 'builder') |
||
|
|
|||
| 41 | { |
||
| 42 | $this->request = $request; |
||
| 43 | $this->query_type = $type; |
||
| 44 | $this->columns = $builder->columns; |
||
| 45 | $this->connection = $builder->getConnection(); |
||
| 46 | $this->prefix = $this->connection->getTablePrefix(); |
||
| 47 | $this->database = $this->connection->getDriverName(); |
||
| 48 | if ($this->isDebugging()) { |
||
| 49 | $this->connection->enableQueryLog(); |
||
| 50 | } |
||
| 51 | } |
||
| 52 | |||
| 53 | /** |
||
| 54 | * Set auto filter off and run your own filter. |
||
| 55 | * Overrides global search |
||
| 56 | * |
||
| 57 | * @param \Closure $callback |
||
| 58 | * @param bool $globalSearch |
||
| 59 | * @return $this |
||
| 60 | */ |
||
| 61 | public function filter(Closure $callback, $globalSearch = false) |
||
| 62 | { |
||
| 63 | $this->overrideGlobalSearch($callback, $this->query, $globalSearch); |
||
| 64 | |||
| 65 | return $this; |
||
| 66 | } |
||
| 67 | |||
| 68 | /** |
||
| 69 | * Organizes works |
||
| 70 | * |
||
| 71 | * @param bool $mDataSupport |
||
| 72 | * @param bool $orderFirst |
||
| 73 | * @return \Illuminate\Http\JsonResponse |
||
| 74 | */ |
||
| 75 | public function make($mDataSupport = false, $orderFirst = false) |
||
| 76 | { |
||
| 77 | return parent::make($mDataSupport, $orderFirst); |
||
| 78 | } |
||
| 79 | |||
| 80 | /** |
||
| 81 | * Count total items. |
||
| 82 | * |
||
| 83 | * @return integer |
||
| 84 | */ |
||
| 85 | public function totalCount() |
||
| 86 | { |
||
| 87 | return $this->totalRecords ? $this->totalRecords : $this->count(); |
||
| 88 | } |
||
| 89 | |||
| 90 | /** |
||
| 91 | * Counts current query. |
||
| 92 | * |
||
| 93 | * @return int |
||
| 94 | */ |
||
| 95 | public function count() |
||
| 96 | { |
||
| 97 | $myQuery = clone $this->query; |
||
| 98 | // if its a normal query ( no union, having and distinct word ) |
||
| 99 | // replace the select with static text to improve performance |
||
| 100 | if (! Str::contains(Str::lower($myQuery->toSql()), ['union', 'having', 'distinct', 'order by', 'group by'])) { |
||
| 101 | $row_count = $this->wrap('row_count'); |
||
| 102 | $myQuery->select($this->connection->raw("'1' as {$row_count}")); |
||
| 103 | } |
||
| 104 | |||
| 105 | // check for select soft deleted records |
||
| 106 | if (! $this->withTrashed && $this->modelUseSoftDeletes()) { |
||
| 107 | $myQuery->whereNull($myQuery->getModel()->getTable() . '.deleted_at'); |
||
| 108 | } |
||
| 109 | |||
| 110 | return $this->connection->table($this->connection->raw('(' . $myQuery->toSql() . ') count_row_table')) |
||
| 111 | ->setBindings($myQuery->getBindings())->count(); |
||
| 112 | } |
||
| 113 | |||
| 114 | /** |
||
| 115 | * Wrap column with DB grammar. |
||
| 116 | * |
||
| 117 | * @param string $column |
||
| 118 | * @return string |
||
| 119 | */ |
||
| 120 | protected function wrap($column) |
||
| 121 | { |
||
| 122 | return $this->connection->getQueryGrammar()->wrap($column); |
||
| 123 | } |
||
| 124 | |||
| 125 | /** |
||
| 126 | * Check if model use SoftDeletes trait |
||
| 127 | * |
||
| 128 | * @return boolean |
||
| 129 | */ |
||
| 130 | private function modelUseSoftDeletes() |
||
| 131 | { |
||
| 132 | if ($this->query_type == 'eloquent') { |
||
| 133 | return in_array('Illuminate\Database\Eloquent\SoftDeletes', class_uses($this->query->getModel())); |
||
| 134 | } |
||
| 135 | |||
| 136 | return false; |
||
| 137 | } |
||
| 138 | |||
| 139 | /** |
||
| 140 | * Perform global search. |
||
| 141 | * |
||
| 142 | * @return void |
||
| 143 | */ |
||
| 144 | public function filtering() |
||
| 145 | { |
||
| 146 | $this->query->where( |
||
| 147 | function ($query) { |
||
| 148 | $globalKeyword = $this->request->keyword(); |
||
| 149 | $queryBuilder = $this->getQueryBuilder($query); |
||
| 150 | |||
| 151 | foreach ($this->request->searchableColumnIndex() as $index) { |
||
| 152 | $columnName = $this->getColumnName($index); |
||
| 153 | if ($this->isBlacklisted($columnName)) { |
||
| 154 | continue; |
||
| 155 | } |
||
| 156 | |||
| 157 | // check if custom column filtering is applied |
||
| 158 | if (isset($this->columnDef['filter'][$columnName])) { |
||
| 159 | $columnDef = $this->columnDef['filter'][$columnName]; |
||
| 160 | // check if global search should be applied for the specific column |
||
| 161 | $applyGlobalSearch = count($columnDef['parameters']) == 0 || end($columnDef['parameters']) !== false; |
||
| 162 | if (! $applyGlobalSearch) { |
||
| 163 | continue; |
||
| 164 | } |
||
| 165 | |||
| 166 | View Code Duplication | if ($columnDef['method'] instanceof Closure) { |
|
| 167 | $whereQuery = $queryBuilder->newQuery(); |
||
| 168 | call_user_func_array($columnDef['method'], [$whereQuery, $globalKeyword]); |
||
| 169 | $queryBuilder->addNestedWhereQuery($whereQuery, 'or'); |
||
| 170 | } else { |
||
| 171 | $this->compileColumnQuery( |
||
| 172 | $queryBuilder, |
||
| 173 | Helper::getOrMethod($columnDef['method']), |
||
| 174 | $columnDef['parameters'], |
||
| 175 | $columnName, |
||
| 176 | $globalKeyword |
||
| 177 | ); |
||
| 178 | } |
||
| 179 | View Code Duplication | } else { |
|
| 180 | if (count(explode('.', $columnName)) > 1) { |
||
| 181 | $eagerLoads = $this->getEagerLoads(); |
||
| 182 | $parts = explode('.', $columnName); |
||
| 183 | $relationColumn = array_pop($parts); |
||
| 184 | $relation = implode('.', $parts); |
||
| 185 | if (in_array($relation, $eagerLoads)) { |
||
| 186 | $this->compileRelationSearch( |
||
| 187 | $queryBuilder, |
||
| 188 | $relation, |
||
| 189 | $relationColumn, |
||
| 190 | $globalKeyword |
||
| 191 | ); |
||
| 192 | } else { |
||
| 193 | $this->compileQuerySearch($queryBuilder, $columnName, $globalKeyword); |
||
| 194 | } |
||
| 195 | } else { |
||
| 196 | $this->compileQuerySearch($queryBuilder, $columnName, $globalKeyword); |
||
| 197 | } |
||
| 198 | } |
||
| 199 | |||
| 200 | $this->isFilterApplied = true; |
||
| 201 | } |
||
| 202 | } |
||
| 203 | ); |
||
| 204 | } |
||
| 205 | |||
| 206 | /** |
||
| 207 | * Perform filter column on selected field. |
||
| 208 | * |
||
| 209 | * @param mixed $query |
||
| 210 | * @param string|Closure $method |
||
| 211 | * @param mixed $parameters |
||
| 212 | * @param string $column |
||
| 213 | * @param string $keyword |
||
| 214 | */ |
||
| 215 | protected function compileColumnQuery($query, $method, $parameters, $column, $keyword) |
||
| 216 | { |
||
| 217 | if (method_exists($query, $method) |
||
| 218 | && count($parameters) <= with(new \ReflectionMethod($query, $method))->getNumberOfParameters() |
||
| 219 | ) { |
||
| 220 | if (Str::contains(Str::lower($method), 'raw') |
||
| 221 | || Str::contains(Str::lower($method), 'exists') |
||
| 222 | ) { |
||
| 223 | call_user_func_array( |
||
| 224 | [$query, $method], |
||
| 225 | $this->parameterize($parameters, $keyword) |
||
| 226 | ); |
||
| 227 | } else { |
||
| 228 | call_user_func_array( |
||
| 229 | [$query, $method], |
||
| 230 | $this->parameterize($column, $parameters, $keyword) |
||
| 231 | ); |
||
| 232 | } |
||
| 233 | } |
||
| 234 | } |
||
| 235 | |||
| 236 | /** |
||
| 237 | * Build Query Builder Parameters. |
||
| 238 | * |
||
| 239 | * @return array |
||
| 240 | */ |
||
| 241 | protected function parameterize() |
||
| 242 | { |
||
| 243 | $args = func_get_args(); |
||
| 244 | $keyword = count($args) > 2 ? $args[2] : $args[1]; |
||
| 245 | $parameters = Helper::buildParameters($args); |
||
| 246 | $parameters = Helper::replacePatternWithKeyword($parameters, $keyword, '$1'); |
||
| 247 | |||
| 248 | return $parameters; |
||
| 249 | } |
||
| 250 | |||
| 251 | /** |
||
| 252 | * Get eager loads keys if eloquent. |
||
| 253 | * |
||
| 254 | * @return array |
||
| 255 | */ |
||
| 256 | protected function getEagerLoads() |
||
| 257 | { |
||
| 258 | if ($this->query_type == 'eloquent') { |
||
| 259 | return array_keys($this->query->getEagerLoads()); |
||
| 260 | } |
||
| 261 | |||
| 262 | return []; |
||
| 263 | } |
||
| 264 | |||
| 265 | /** |
||
| 266 | * Add relation query on global search. |
||
| 267 | * |
||
| 268 | * @param mixed $query |
||
| 269 | * @param string $relation |
||
| 270 | * @param string $column |
||
| 271 | * @param string $keyword |
||
| 272 | */ |
||
| 273 | protected function compileRelationSearch($query, $relation, $column, $keyword) |
||
| 274 | { |
||
| 275 | $myQuery = clone $this->query; |
||
| 276 | $relationType = $myQuery->getModel()->{$relation}(); |
||
| 277 | $myQuery->orWhereHas($relation, function ($builder) use ($column, $keyword, $query, $relationType) { |
||
| 278 | $builder->select($this->connection->raw('count(1)')); |
||
| 279 | $this->compileQuerySearch($builder, $column, $keyword, ''); |
||
| 280 | $builder = "({$builder->toSql()}) >= 1"; |
||
| 281 | |||
| 282 | if ($relationType instanceof MorphToMany) { |
||
| 283 | $query->orWhereRaw($builder, [$relationType->getMorphClass(), $this->prepareKeyword($keyword)]); |
||
| 284 | } else { |
||
| 285 | $query->orWhereRaw($builder, [$this->prepareKeyword($keyword)]); |
||
| 286 | } |
||
| 287 | }); |
||
| 288 | } |
||
| 289 | |||
| 290 | /** |
||
| 291 | * Compile query builder where clause depending on configurations. |
||
| 292 | * |
||
| 293 | * @param mixed $query |
||
| 294 | * @param string $column |
||
| 295 | * @param string $keyword |
||
| 296 | * @param string $relation |
||
| 297 | */ |
||
| 298 | protected function compileQuerySearch($query, $column, $keyword, $relation = 'or') |
||
| 299 | { |
||
| 300 | $column = $this->castColumn($column); |
||
| 301 | $sql = $column . ' LIKE ?'; |
||
| 302 | |||
| 303 | if ($this->isCaseInsensitive()) { |
||
| 304 | $sql = 'LOWER(' . $column . ') LIKE ?'; |
||
| 305 | } |
||
| 306 | |||
| 307 | $query->{$relation . 'WhereRaw'}($sql, [$this->prepareKeyword($keyword)]); |
||
| 308 | } |
||
| 309 | |||
| 310 | /** |
||
| 311 | * Wrap a column and cast in pgsql. |
||
| 312 | * |
||
| 313 | * @param string $column |
||
| 314 | * @return string |
||
| 315 | */ |
||
| 316 | public function castColumn($column) |
||
| 327 | |||
| 328 | /** |
||
| 329 | * Prepare search keyword based on configurations. |
||
| 330 | * |
||
| 331 | * @param string $keyword |
||
| 332 | * @return string |
||
| 333 | */ |
||
| 334 | protected function prepareKeyword($keyword) |
||
| 350 | |||
| 351 | /** |
||
| 352 | * Perform column search. |
||
| 353 | * |
||
| 354 | * @return void |
||
| 355 | */ |
||
| 356 | public function columnSearch() |
||
| 404 | |||
| 405 | /** |
||
| 406 | * Get proper keyword to use for search. |
||
| 407 | * |
||
| 408 | * @param int $i |
||
| 409 | * @param bool $raw |
||
| 410 | * @return string |
||
| 411 | */ |
||
| 412 | private function getSearchKeyword($i, $raw = false) |
||
| 421 | |||
| 422 | /** |
||
| 423 | * Join eager loaded relation and get the related column name. |
||
| 424 | * |
||
| 425 | * @param string $relation |
||
| 426 | * @param string $relationColumn |
||
| 427 | * @return string |
||
| 428 | */ |
||
| 429 | protected function joinEagerLoadedColumn($relation, $relationColumn) |
||
| 473 | |||
| 474 | /** |
||
| 475 | * Compile queries for column search. |
||
| 476 | * |
||
| 477 | * @param int $i |
||
| 478 | * @param mixed $column |
||
| 479 | * @param string $keyword |
||
| 480 | */ |
||
| 481 | protected function compileColumnSearch($i, $column, $keyword) |
||
| 490 | |||
| 491 | /** |
||
| 492 | * Compile regex query column search. |
||
| 493 | * |
||
| 494 | * @param mixed $column |
||
| 495 | * @param string $keyword |
||
| 496 | */ |
||
| 497 | protected function regexColumnSearch($column, $keyword) |
||
| 507 | |||
| 508 | /** |
||
| 509 | * Perform sorting of columns. |
||
| 510 | * |
||
| 511 | * @return void |
||
| 512 | */ |
||
| 513 | public function ordering() |
||
| 514 | { |
||
| 515 | if ($this->orderCallback) { |
||
| 516 | call_user_func($this->orderCallback, $this->getQueryBuilder()); |
||
| 517 | |||
| 518 | return; |
||
| 519 | } |
||
| 520 | |||
| 521 | foreach ($this->request->orderableColumns() as $orderable) { |
||
| 566 | |||
| 567 | /** |
||
| 568 | * Get NULLS LAST SQL. |
||
| 569 | * |
||
| 570 | * @param string $column |
||
| 571 | * @param string $direction |
||
| 572 | * @return string |
||
| 573 | */ |
||
| 574 | protected function getNullsLastSql($column, $direction) |
||
| 580 | |||
| 581 | /** |
||
| 582 | * Perform pagination |
||
| 583 | * |
||
| 584 | * @return void |
||
| 585 | */ |
||
| 586 | public function paging() |
||
| 591 | |||
| 592 | /** |
||
| 593 | * Get results |
||
| 594 | * |
||
| 595 | * @return array|static[] |
||
| 596 | */ |
||
| 597 | public function results() |
||
| 601 | } |
||
| 602 |