DatatablesService::handleQuery()   B
last analyzed

Complexity

Conditions 6
Paths 8

Size

Total Lines 56
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 31
nc 8
nop 5
dl 0
loc 56
rs 8.8017
c 0
b 0
f 0

How to fix   Long Method   

Long Method

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:

1
<?php
2
3
/**
4
 * webtrees: online genealogy
5
 * Copyright (C) 2025 webtrees development team
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
 * GNU General Public License for more details.
14
 * You should have received a copy of the GNU General Public License
15
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16
 */
17
18
declare(strict_types=1);
19
20
namespace Fisharebest\Webtrees\Services;
21
22
use Closure;
23
use Fisharebest\Webtrees\Validator;
24
use Illuminate\Database\Query\Builder;
25
use Illuminate\Database\Query\Expression;
26
use Illuminate\Support\Collection;
27
use Psr\Http\Message\ResponseInterface;
28
use Psr\Http\Message\ServerRequestInterface;
29
30
use function addcslashes;
31
use function strtr;
32
33
/**
34
 * Paginate and search queries for datatables.
35
 *
36
 * @link https://www.datatables.net/usage/server-side
37
 */
38
class DatatablesService
39
{
40
    /**
41
     * Apply filtering and pagination to a collection, and generate a response suitable for datatables.
42
     *
43
     * @param ServerRequestInterface   $request        Includes the datatables request parameters.
44
     * @param Collection<int,mixed>    $collection     All the data.
45
     * @param array<string>|array<int> $search_columns The names of searchable columns.
46
     * @param array<string>|array<int> $sort_columns   Sort column mapping.
47
     * @param Closure                  $callback       Converts a row-object to an array-of-columns.
48
     *
49
     * @return ResponseInterface
50
     */
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
        ]);
114
    }
115
116
    /**
117
     * Apply filtering and pagination to a database query, and generate a response suitable for datatables.
118
     *
119
     * @param ServerRequestInterface           $request        Includes the datatables request parameters.
120
     * @param Builder                          $query          A query to fetch the unfiltered rows and columns.
121
     * @param array<string>                    $search_columns The names of searchable columns.
122
     * @param array<string|Expression<string>> $sort_columns   Sort column mapping.
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<string|Expression<string>> at position 4 could not be parsed: Expected '>' at position 4, but found 'Expression'.
Loading history...
123
     * @param Closure                          $callback       Converts a row-object to an array-of-columns.
124
     *
125
     * @return ResponseInterface
126
     */
127
    public function handleQuery(ServerRequestInterface $request, Builder $query, array $search_columns, array $sort_columns, Closure $callback): ResponseInterface
128
    {
129
        $search = Validator::queryParams($request)->array('search')['value'] ?? '';
130
        $start  = Validator::queryParams($request)->integer('start', 0);
131
        $length = Validator::queryParams($request)->integer('length', 0);
132
        $order  = Validator::queryParams($request)->array('order');
133
        $draw   = Validator::queryParams($request)->integer('draw', 0);
134
135
        // Count unfiltered records
136
        $recordsTotal = (clone $query)->count();
137
138
        // Filtering
139
        if ($search !== '') {
140
            $query->where(static function (Builder $query) use ($search, $search_columns): void {
141
                $like = '%' . addcslashes($search, '\\%_') . '%';
142
                $like = strtr($like, [' ' => '%']);
143
144
                foreach ($search_columns as $search_column) {
145
                    $query->orWhere($search_column, 'LIKE', $like);
146
                }
147
            });
148
        }
149
150
        // Sorting
151
        if ($order !== []) {
152
            foreach ($order as $value) {
153
                // Columns in datatables are numbered from zero.
154
                // Columns in MySQL are numbered starting with one.
155
                // If not specified, the Nth table column maps onto the Nth query column.
156
                $sort_column = $sort_columns[$value['column']] ?? new Expression(1 + $value['column']);
0 ignored issues
show
Bug introduced by
1 + $value['column'] of type integer is incompatible with the type Illuminate\Database\Query\TValue expected by parameter $value of Illuminate\Database\Quer...pression::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

156
                $sort_column = $sort_columns[$value['column']] ?? new Expression(/** @scrutinizer ignore-type */ 1 + $value['column']);
Loading history...
157
158
                $query->orderBy($sort_column, $value['dir']);
0 ignored issues
show
Bug introduced by
It seems like $sort_column can also be of type Illuminate\Database\Query\Expression; however, parameter $column of Illuminate\Database\Query\Builder::orderBy() does only seem to accept Closure|Illuminate\Datab...\Database\Query\Builder, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

158
                $query->orderBy(/** @scrutinizer ignore-type */ $sort_column, $value['dir']);
Loading history...
159
            }
160
        } else {
161
            $query->orderBy(new Expression(1));
162
        }
163
164
        // Paginating
165
        if ($length > 0) {
166
            $recordsFiltered = (clone $query)->count();
167
168
            $query->skip($start)->limit($length);
169
            $data = $query->get();
170
        } else {
171
            $data = $query->get();
172
173
            $recordsFiltered = $data->count();
174
        }
175
176
        $data = $data->map($callback)->all();
177
178
        return response([
179
            'draw'            => $draw,
180
            'recordsTotal'    => $recordsTotal,
181
            'recordsFiltered' => $recordsFiltered,
182
            'data'            => $data,
183
        ]);
184
    }
185
}
186