xref: /webtrees/app/Services/DatatablesService.php (revision 33cff286aecf9317eb2681d07dac202bc5d54f7b)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2022 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 Illuminate\Database\Query\Builder;
24use Illuminate\Database\Query\Expression;
25use Illuminate\Support\Collection;
26use Psr\Http\Message\ResponseInterface;
27use Psr\Http\Message\ServerRequestInterface;
28
29use function addcslashes;
30use function strtr;
31
32/**
33 * Paginate and search queries for datatables.
34 *
35 * @link https://www.datatables.net/usage/server-side
36 */
37class DatatablesService
38{
39    /**
40     * Apply filtering and pagination to a collection, and generate a response suitable for datatables.
41     *
42     * @param ServerRequestInterface   $request        Includes the datatables request parameters.
43     * @param Collection<int,mixed>    $collection     All the data.
44     * @param array<string>|array<int> $search_columns The names of searchable columns.
45     * @param array<string>|array<int> $sort_columns   Sort column mapping.
46     * @param Closure                  $callback       Converts a row-object to an array-of-columns.
47     *
48     * @return ResponseInterface
49     */
50    public function handleCollection(ServerRequestInterface $request, Collection $collection, array $search_columns, array $sort_columns, Closure $callback): ResponseInterface
51    {
52        $search = $request->getQueryParams()['search']['value'] ?? '';
53        $start  = (int) ($request->getQueryParams()['start'] ?? 0);
54        $length = (int) ($request->getQueryParams()['length'] ?? 0);
55        $order  = $request->getQueryParams()['order'] ?? [];
56        $draw   = (int) ($request->getQueryParams()['draw'] ?? 0);
57
58        // Count unfiltered records
59        $recordsTotal = $collection->count();
60
61        // Filtering
62        if ($search !== '') {
63            $collection = $collection->filter(static function (array $row) use ($search, $search_columns): bool {
64                foreach ($search_columns as $search_column) {
65                    if (stripos($row[$search_column], $search) !== false) {
66                        return true;
67                    }
68                }
69
70                return false;
71            });
72        }
73
74        // Sorting
75        if ($order !== []) {
76            $collection = $collection->sort(static function (array $row1, array $row2) use ($order, $sort_columns): int {
77                foreach ($order as $column) {
78                    $key = $sort_columns[$column['column']];
79                    $dir = $column['dir'];
80
81                    if ($dir === 'asc') {
82                        $comparison = $row1[$key] <=> $row2[$key];
83                    } else {
84                        $comparison = $row2[$key] <=> $row1[$key];
85                    }
86
87                    if ($comparison !== 0) {
88                        return $comparison;
89                    }
90                }
91
92                return 0;
93            });
94        }
95
96        // Paginating
97        $recordsFiltered = $collection->count();
98
99        if ($length > 0) {
100            $data = $collection->slice($start, $length);
101        } else {
102            $data = $collection;
103        }
104
105        $data = $data->map($callback)->values()->all();
106
107        return response([
108            'draw'            => $draw,
109            'recordsTotal'    => $recordsTotal,
110            'recordsFiltered' => $recordsFiltered,
111            'data'            => $data,
112        ]);
113    }
114
115    /**
116     * Apply filtering and pagination to a database query, and generate a response suitable for datatables.
117     *
118     * @param ServerRequestInterface   $request        Includes the datatables request parameters.
119     * @param Builder                  $query          A query to fetch the unfiltered rows and columns.
120     * @param array<string>            $search_columns The names of searchable columns.
121     * @param array<string|Expression> $sort_columns   Sort column mapping.
122     * @param Closure                  $callback       Converts a row-object to an array-of-columns.
123     *
124     * @return ResponseInterface
125     */
126    public function handleQuery(ServerRequestInterface $request, Builder $query, array $search_columns, array $sort_columns, Closure $callback): ResponseInterface
127    {
128        $search = $request->getQueryParams()['search']['value'] ?? '';
129        $start  = (int) ($request->getQueryParams()['start'] ?? 0);
130        $length = (int) ($request->getQueryParams()['length'] ?? 0);
131        $order  = $request->getQueryParams()['order'] ?? [];
132        $draw   = (int) ($request->getQueryParams()['draw'] ?? 0);
133
134        // Count unfiltered records
135        $recordsTotal = (clone $query)->count();
136
137        // Filtering
138        if ($search !== '') {
139            $query->where(static function (Builder $query) use ($search, $search_columns): void {
140                $like = '%' . addcslashes($search, '\\%_') . '%';
141                $like = strtr($like, [' ' => '%']);
142
143                foreach ($search_columns as $search_column) {
144                    $query->orWhere($search_column, 'LIKE', $like);
145                }
146            });
147        }
148
149        // Sorting
150        if ($order !== []) {
151            foreach ($order as $value) {
152                // Columns in datatables are numbered from zero.
153                // Columns in MySQL are numbered starting with one.
154                // If not specified, the Nth table column maps onto the Nth query column.
155                $sort_column = $sort_columns[$value['column']] ?? new Expression(1 + $value['column']);
156
157                $query->orderBy($sort_column, $value['dir']);
158            }
159        } else {
160            $query->orderBy(new Expression(1));
161        }
162
163        // Paginating
164        if ($length > 0) {
165            $recordsFiltered = (clone $query)->count();
166
167            $query->skip($start)->limit($length);
168            $data = $query->get();
169        } else {
170            $data = $query->get();
171
172            $recordsFiltered = $data->count();
173        }
174
175        $data = $data->map($callback)->all();
176
177        return response([
178            'draw'            => $draw,
179            'recordsTotal'    => $recordsTotal,
180            'recordsFiltered' => $recordsFiltered,
181            'data'            => $data,
182        ]);
183    }
184}
185