| Conditions | 6 |
| Paths | 8 |
| Total Lines | 53 |
| Code Lines | 29 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | <?php |
||
| 125 | public function handleQuery(ServerRequestInterface $request, Builder $query, array $search_columns, array $sort_columns, Closure $callback): ResponseInterface |
||
| 126 | { |
||
| 127 | $search = $request->getQueryParams()['search']['value'] ?? ''; |
||
| 128 | $start = (int) ($request->getQueryParams()['start'] ?? 0); |
||
| 129 | $length = (int) ($request->getQueryParams()['length'] ?? 0); |
||
| 130 | $order = $request->getQueryParams()['order'] ?? []; |
||
| 131 | $draw = (int) ($request->getQueryParams()['draw'] ?? 0); |
||
| 132 | |||
| 133 | // Count unfiltered records |
||
| 134 | $recordsTotal = (clone $query)->count(); |
||
| 135 | |||
| 136 | // Filtering |
||
| 137 | if ($search !== '') { |
||
| 138 | $query->where(static function (Builder $query) use ($search, $search_columns): void { |
||
| 139 | foreach ($search_columns as $search_column) { |
||
| 140 | $query->whereContains($search_column, $search, 'or'); |
||
| 141 | } |
||
| 142 | }); |
||
| 143 | } |
||
| 144 | |||
| 145 | // Sorting |
||
| 146 | if ($order !== []) { |
||
| 147 | foreach ($order as $value) { |
||
| 148 | // Columns in datatables are numbered from zero. |
||
| 149 | // Columns in MySQL are numbered starting with one. |
||
| 150 | // If not specified, the Nth table column maps onto the Nth query column. |
||
| 151 | $sort_column = $sort_columns[$value['column']] ?? new Expression(1 + $value['column']); |
||
| 152 | |||
| 153 | $query->orderBy($sort_column, $value['dir']); |
||
| 154 | } |
||
| 155 | } else { |
||
| 156 | $query->orderBy(new Expression(1)); |
||
| 157 | } |
||
| 158 | |||
| 159 | // Paginating |
||
| 160 | if ($length > 0) { |
||
| 161 | $recordsFiltered = (clone $query)->count(); |
||
| 162 | |||
| 163 | $query->skip($start)->limit($length); |
||
| 164 | $data = $query->get(); |
||
| 165 | } else { |
||
| 166 | $data = $query->get(); |
||
| 167 | |||
| 168 | $recordsFiltered = $data->count(); |
||
| 169 | } |
||
| 170 | |||
| 171 | $data = $data->map($callback)->all(); |
||
| 172 | |||
| 173 | return response([ |
||
| 174 | 'draw' => $draw, |
||
| 175 | 'recordsTotal' => $recordsTotal, |
||
| 176 | 'recordsFiltered' => $recordsFiltered, |
||
| 177 | 'data' => $data, |
||
| 178 | ]); |
||
| 181 |