xref: /webtrees/app/Services/DatatablesService.php (revision d70512ab02636ee884ef6d7907223ed02c754ff5)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2019 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 <http://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
29/**
30 * Paginate and search queries for datatables.
31 *
32 * @link http://www.datatables.net/usage/server-side
33 */
34class DatatablesService
35{
36    /**
37     * Apply filtering and pagination to a collection, and generate a response suitable for datatables.
38     *
39     * @param ServerRequestInterface $request        Includes the datatables request parameters.
40     * @param Collection             $collection     All the data.
41     * @param string[]|int[]         $search_columns The names of searchable columns.
42     * @param string[]|int[]         $sort_columns   Sort column mapping.
43     * @param Closure                $callback       Converts a row-object to an array-of-columns.
44     *
45     * @return ResponseInterface
46     */
47    public function handleCollection(ServerRequestInterface $request, Collection $collection, array $search_columns, array $sort_columns, Closure $callback): ResponseInterface
48    {
49        $search = $request->getQueryParams()['search']['value'] ?? '';
50        $start  = (int) ($request->getQueryParams()['start'] ?? 0);
51        $length = (int) ($request->getQueryParams()['length'] ?? 0);
52        $order  = $request->getQueryParams()['order'] ?? [];
53        $draw   = (int) ($request->getQueryParams()['draw'] ?? 0);
54
55        // Count unfiltered records
56        $recordsTotal = $collection->count();
57
58        // Filtering
59        if ($search !== '') {
60            $collection = $collection->filter(static function (array $row) use ($search, $search_columns): bool {
61                foreach ($search_columns as $search_column) {
62                    if (stripos($row[$search_column], $search) !== false) {
63                        return true;
64                    }
65                }
66
67                return false;
68            });
69        }
70
71        // Sorting
72        if ($order !== []) {
73            $collection = $collection->sort(static function (array $row1, array $row2) use ($order, $sort_columns): int {
74                foreach ($order as $column) {
75                    $key = $sort_columns[$column['column']];
76                    $dir = $column['dir'];
77
78                    if ($dir === 'asc') {
79                        $comparison = $row1[$key] <=> $row2[$key];
80                    } else {
81                        $comparison = $row2[$key] <=> $row1[$key];
82                    }
83
84                    if ($comparison !== 0) {
85                        return $comparison;
86                    }
87                }
88
89                return 0;
90            });
91        }
92
93        // Paginating
94        if ($length > 0) {
95            $recordsFiltered = $collection->count();
96
97            $data = $collection->slice($start, $length);
98        } else {
99            $recordsFiltered = $collection->count();
100
101            $data = $collection;
102        }
103
104        $data = $data->map($callback)->values()->all();
105
106        return response([
107            'draw'            => $draw,
108            'recordsTotal'    => $recordsTotal,
109            'recordsFiltered' => $recordsFiltered,
110            'data'            => $data,
111        ]);
112    }
113
114    /**
115     * Apply filtering and pagination to a database query, and generate a response suitable for datatables.
116     *
117     * @param ServerRequestInterface $request        Includes the datatables request parameters.
118     * @param Builder                $query          A query to fetch the unfiltered rows and columns.
119     * @param string[]               $search_columns The names of searchable columns.
120     * @param string[]               $sort_columns   Sort column mapping.
121     * @param Closure                $callback       Converts a row-object to an array-of-columns.
122     *
123     * @return ResponseInterface
124     */
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        ]);
179    }
180}
181