| Conditions | 9 |
| Paths | 8 |
| Total Lines | 62 |
| Code Lines | 35 |
| 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 |
||
| 51 | public function handleCollection(ServerRequestInterface $request, Collection $collection, array $search_columns, array $sort_columns, Closure $callback): ResponseInterface |
||
| 52 | { |
||
| 53 | $search = Validator::queryParams($request)->array('search')['value'] ?? ''; |
||
| 54 | $start = Validator::queryParams($request)->integer('start', 0); |
||
| 55 | $length = Validator::queryParams($request)->integer('length', 0); |
||
| 56 | $order = Validator::queryParams($request)->array('order'); |
||
| 57 | $draw = Validator::queryParams($request)->integer('draw', 0); |
||
| 58 | |||
| 59 | // Count unfiltered records |
||
| 60 | $recordsTotal = $collection->count(); |
||
| 61 | |||
| 62 | // Filtering |
||
| 63 | if ($search !== '') { |
||
| 64 | $collection = $collection->filter(static function (array $row) use ($search, $search_columns): bool { |
||
| 65 | foreach ($search_columns as $search_column) { |
||
| 66 | if (stripos($row[$search_column], $search) !== false) { |
||
| 67 | return true; |
||
| 68 | } |
||
| 69 | } |
||
| 70 | |||
| 71 | return false; |
||
| 72 | }); |
||
| 73 | } |
||
| 74 | |||
| 75 | // Sorting |
||
| 76 | if ($order !== []) { |
||
| 77 | $collection = $collection->sort(static function (array $row1, array $row2) use ($order, $sort_columns): int { |
||
| 78 | foreach ($order as $column) { |
||
| 79 | $key = $sort_columns[$column['column']]; |
||
| 80 | $dir = $column['dir']; |
||
| 81 | |||
| 82 | if ($dir === 'asc') { |
||
| 83 | $comparison = $row1[$key] <=> $row2[$key]; |
||
| 84 | } else { |
||
| 85 | $comparison = $row2[$key] <=> $row1[$key]; |
||
| 86 | } |
||
| 87 | |||
| 88 | if ($comparison !== 0) { |
||
| 89 | return $comparison; |
||
| 90 | } |
||
| 91 | } |
||
| 92 | |||
| 93 | return 0; |
||
| 94 | }); |
||
| 95 | } |
||
| 96 | |||
| 97 | // Paginating |
||
| 98 | $recordsFiltered = $collection->count(); |
||
| 99 | |||
| 100 | if ($length > 0) { |
||
| 101 | $data = $collection->slice($start, $length); |
||
| 102 | } else { |
||
| 103 | $data = $collection; |
||
| 104 | } |
||
| 105 | |||
| 106 | $data = $data->map($callback)->values()->all(); |
||
| 107 | |||
| 108 | return response([ |
||
| 109 | 'draw' => $draw, |
||
| 110 | 'recordsTotal' => $recordsTotal, |
||
| 111 | 'recordsFiltered' => $recordsFiltered, |
||
| 112 | 'data' => $data, |
||
| 113 | ]); |
||
| 186 |