xref: /webtrees/app/Services/DatatablesService.php (revision d11be7027e34e3121be11cc025421873364403f9)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2023 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
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Services;
21
22use Closure;
23use Fisharebest\Webtrees\Validator;
24use Illuminate\Database\Query\Builder;
25use Illuminate\Database\Query\Expression;
26use Illuminate\Support\Collection;
27use Psr\Http\Message\ResponseInterface;
28use Psr\Http\Message\ServerRequestInterface;
29
30use function addcslashes;
31use function strtr;
32
33/**
34 * Paginate and search queries for datatables.
35 *
36 * @link https://www.datatables.net/usage/server-side
37 */
38class 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> $sort_columns   Sort column mapping.
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']);
157
158                $query->orderBy($sort_column, $value['dir']);
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