xref: /webtrees/app/Services/DatatablesService.php (revision d11be7027e34e3121be11cc025421873364403f9)
1d346cc1cSGreg Roach<?php
23976b470SGreg Roach
3d346cc1cSGreg Roach/**
4d346cc1cSGreg Roach * webtrees: online genealogy
5*d11be702SGreg Roach * Copyright (C) 2023 webtrees development team
6d346cc1cSGreg Roach * This program is free software: you can redistribute it and/or modify
7d346cc1cSGreg Roach * it under the terms of the GNU General Public License as published by
8d346cc1cSGreg Roach * the Free Software Foundation, either version 3 of the License, or
9d346cc1cSGreg Roach * (at your option) any later version.
10d346cc1cSGreg Roach * This program is distributed in the hope that it will be useful,
11d346cc1cSGreg Roach * but WITHOUT ANY WARRANTY; without even the implied warranty of
12d346cc1cSGreg Roach * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13d346cc1cSGreg Roach * GNU General Public License for more details.
14d346cc1cSGreg Roach * You should have received a copy of the GNU General Public License
1589f7189bSGreg Roach * along with this program. If not, see <https://www.gnu.org/licenses/>.
16d346cc1cSGreg Roach */
17fcfa147eSGreg Roach
18d346cc1cSGreg Roachdeclare(strict_types=1);
19d346cc1cSGreg Roach
20d346cc1cSGreg Roachnamespace Fisharebest\Webtrees\Services;
21d346cc1cSGreg Roach
22d346cc1cSGreg Roachuse Closure;
23748dbe15SGreg Roachuse Fisharebest\Webtrees\Validator;
24d346cc1cSGreg Roachuse Illuminate\Database\Query\Builder;
25a69f5655SGreg Roachuse Illuminate\Database\Query\Expression;
2613aa75d8SGreg Roachuse Illuminate\Support\Collection;
276ccdf4f0SGreg Roachuse Psr\Http\Message\ResponseInterface;
286ccdf4f0SGreg Roachuse Psr\Http\Message\ServerRequestInterface;
29d346cc1cSGreg Roach
30b5961194SGreg Roachuse function addcslashes;
31b5961194SGreg Roachuse function strtr;
32b5961194SGreg Roach
33d346cc1cSGreg Roach/**
34d346cc1cSGreg Roach * Paginate and search queries for datatables.
3513aa75d8SGreg Roach *
36ad3143ccSGreg Roach * @link https://www.datatables.net/usage/server-side
37d346cc1cSGreg Roach */
38d346cc1cSGreg Roachclass DatatablesService
39d346cc1cSGreg Roach{
40d346cc1cSGreg Roach    /**
4113aa75d8SGreg Roach     * Apply filtering and pagination to a collection, and generate a response suitable for datatables.
42d346cc1cSGreg Roach     *
436ccdf4f0SGreg Roach     * @param ServerRequestInterface   $request        Includes the datatables request parameters.
4436779af1SGreg Roach     * @param Collection<int,mixed>    $collection     All the data.
4509482a55SGreg Roach     * @param array<string>|array<int> $search_columns The names of searchable columns.
4609482a55SGreg Roach     * @param array<string>|array<int> $sort_columns   Sort column mapping.
47d346cc1cSGreg Roach     * @param Closure                  $callback       Converts a row-object to an array-of-columns.
48d346cc1cSGreg Roach     *
496ccdf4f0SGreg Roach     * @return ResponseInterface
50d346cc1cSGreg Roach     */
5113aa75d8SGreg Roach    public function handleCollection(ServerRequestInterface $request, Collection $collection, array $search_columns, array $sort_columns, Closure $callback): ResponseInterface
5213aa75d8SGreg Roach    {
53748dbe15SGreg Roach        $search = Validator::queryParams($request)->array('search')['value'] ?? '';
54748dbe15SGreg Roach        $start  = Validator::queryParams($request)->integer('start', 0);
55748dbe15SGreg Roach        $length = Validator::queryParams($request)->integer('length', 0);
56748dbe15SGreg Roach        $order  = Validator::queryParams($request)->array('order');
57748dbe15SGreg Roach        $draw   = Validator::queryParams($request)->integer('draw', 0);
5813aa75d8SGreg Roach
5913aa75d8SGreg Roach        // Count unfiltered records
6013aa75d8SGreg Roach        $recordsTotal = $collection->count();
6113aa75d8SGreg Roach
6213aa75d8SGreg Roach        // Filtering
6313aa75d8SGreg Roach        if ($search !== '') {
6413aa75d8SGreg Roach            $collection = $collection->filter(static function (array $row) use ($search, $search_columns): bool {
6513aa75d8SGreg Roach                foreach ($search_columns as $search_column) {
6613aa75d8SGreg Roach                    if (stripos($row[$search_column], $search) !== false) {
6713aa75d8SGreg Roach                        return true;
6813aa75d8SGreg Roach                    }
6913aa75d8SGreg Roach                }
7013aa75d8SGreg Roach
7113aa75d8SGreg Roach                return false;
7213aa75d8SGreg Roach            });
7313aa75d8SGreg Roach        }
7413aa75d8SGreg Roach
7513aa75d8SGreg Roach        // Sorting
7613aa75d8SGreg Roach        if ($order !== []) {
7713aa75d8SGreg Roach            $collection = $collection->sort(static function (array $row1, array $row2) use ($order, $sort_columns): int {
7813aa75d8SGreg Roach                foreach ($order as $column) {
7913aa75d8SGreg Roach                    $key = $sort_columns[$column['column']];
8013aa75d8SGreg Roach                    $dir = $column['dir'];
8113aa75d8SGreg Roach
8213aa75d8SGreg Roach                    if ($dir === 'asc') {
8313aa75d8SGreg Roach                        $comparison = $row1[$key] <=> $row2[$key];
8413aa75d8SGreg Roach                    } else {
8513aa75d8SGreg Roach                        $comparison = $row2[$key] <=> $row1[$key];
8613aa75d8SGreg Roach                    }
8713aa75d8SGreg Roach
8813aa75d8SGreg Roach                    if ($comparison !== 0) {
8913aa75d8SGreg Roach                        return $comparison;
9013aa75d8SGreg Roach                    }
9113aa75d8SGreg Roach                }
9213aa75d8SGreg Roach
9313aa75d8SGreg Roach                return 0;
9413aa75d8SGreg Roach            });
9513aa75d8SGreg Roach        }
9613aa75d8SGreg Roach
9713aa75d8SGreg Roach        // Paginating
9813aa75d8SGreg Roach        $recordsFiltered = $collection->count();
9913aa75d8SGreg Roach
1001821c9e5SGreg Roach        if ($length > 0) {
10113aa75d8SGreg Roach            $data = $collection->slice($start, $length);
10213aa75d8SGreg Roach        } else {
10313aa75d8SGreg Roach            $data = $collection;
10413aa75d8SGreg Roach        }
10513aa75d8SGreg Roach
10613aa75d8SGreg Roach        $data = $data->map($callback)->values()->all();
10713aa75d8SGreg Roach
10813aa75d8SGreg Roach        return response([
10913aa75d8SGreg Roach            'draw'            => $draw,
11013aa75d8SGreg Roach            'recordsTotal'    => $recordsTotal,
11113aa75d8SGreg Roach            'recordsFiltered' => $recordsFiltered,
11213aa75d8SGreg Roach            'data'            => $data,
11313aa75d8SGreg Roach        ]);
11413aa75d8SGreg Roach    }
11513aa75d8SGreg Roach
11613aa75d8SGreg Roach    /**
11713aa75d8SGreg Roach     * Apply filtering and pagination to a database query, and generate a response suitable for datatables.
11813aa75d8SGreg Roach     *
11913aa75d8SGreg Roach     * @param ServerRequestInterface   $request        Includes the datatables request parameters.
12013aa75d8SGreg Roach     * @param Builder                  $query          A query to fetch the unfiltered rows and columns.
12109482a55SGreg Roach     * @param array<string>            $search_columns The names of searchable columns.
1224b56fbbcSGreg Roach     * @param array<string|Expression> $sort_columns   Sort column mapping.
12313aa75d8SGreg Roach     * @param Closure                  $callback       Converts a row-object to an array-of-columns.
12413aa75d8SGreg Roach     *
12513aa75d8SGreg Roach     * @return ResponseInterface
12613aa75d8SGreg Roach     */
12713aa75d8SGreg Roach    public function handleQuery(ServerRequestInterface $request, Builder $query, array $search_columns, array $sort_columns, Closure $callback): ResponseInterface
128d346cc1cSGreg Roach    {
129748dbe15SGreg Roach        $search = Validator::queryParams($request)->array('search')['value'] ?? '';
130748dbe15SGreg Roach        $start  = Validator::queryParams($request)->integer('start', 0);
131748dbe15SGreg Roach        $length = Validator::queryParams($request)->integer('length', 0);
132748dbe15SGreg Roach        $order  = Validator::queryParams($request)->array('order');
133748dbe15SGreg Roach        $draw   = Validator::queryParams($request)->integer('draw', 0);
134d346cc1cSGreg Roach
135d346cc1cSGreg Roach        // Count unfiltered records
136d346cc1cSGreg Roach        $recordsTotal = (clone $query)->count();
137d346cc1cSGreg Roach
138d346cc1cSGreg Roach        // Filtering
139d346cc1cSGreg Roach        if ($search !== '') {
1400b5fd0a6SGreg Roach            $query->where(static function (Builder $query) use ($search, $search_columns): void {
141b5961194SGreg Roach                $like = '%' . addcslashes($search, '\\%_') . '%';
142b5961194SGreg Roach                $like = strtr($like, [' ' => '%']);
143b5961194SGreg Roach
144d346cc1cSGreg Roach                foreach ($search_columns as $search_column) {
145b5961194SGreg Roach                    $query->orWhere($search_column, 'LIKE', $like);
146d346cc1cSGreg Roach                }
147d346cc1cSGreg Roach            });
148d346cc1cSGreg Roach        }
149d346cc1cSGreg Roach
150d346cc1cSGreg Roach        // Sorting
15154c1ab5eSGreg Roach        if ($order !== []) {
152d346cc1cSGreg Roach            foreach ($order as $value) {
153d346cc1cSGreg Roach                // Columns in datatables are numbered from zero.
154d346cc1cSGreg Roach                // Columns in MySQL are numbered starting with one.
1558a22b886SGreg Roach                // If not specified, the Nth table column maps onto the Nth query column.
156a69f5655SGreg Roach                $sort_column = $sort_columns[$value['column']] ?? new Expression(1 + $value['column']);
1578a22b886SGreg Roach
1588a22b886SGreg Roach                $query->orderBy($sort_column, $value['dir']);
159d346cc1cSGreg Roach            }
160d346cc1cSGreg Roach        } else {
161a69f5655SGreg Roach            $query->orderBy(new Expression(1));
162d346cc1cSGreg Roach        }
163d346cc1cSGreg Roach
164d346cc1cSGreg Roach        // Paginating
165d346cc1cSGreg Roach        if ($length > 0) {
166d346cc1cSGreg Roach            $recordsFiltered = (clone $query)->count();
167d346cc1cSGreg Roach
168d346cc1cSGreg Roach            $query->skip($start)->limit($length);
169d346cc1cSGreg Roach            $data = $query->get();
170d346cc1cSGreg Roach        } else {
171d346cc1cSGreg Roach            $data = $query->get();
172d346cc1cSGreg Roach
173d346cc1cSGreg Roach            $recordsFiltered = $data->count();
174d346cc1cSGreg Roach        }
175d346cc1cSGreg Roach
176d346cc1cSGreg Roach        $data = $data->map($callback)->all();
177d346cc1cSGreg Roach
1786ccdf4f0SGreg Roach        return response([
179d346cc1cSGreg Roach            'draw'            => $draw,
180d346cc1cSGreg Roach            'recordsTotal'    => $recordsTotal,
181d346cc1cSGreg Roach            'recordsFiltered' => $recordsFiltered,
182d346cc1cSGreg Roach            'data'            => $data,
183d346cc1cSGreg Roach        ]);
184d346cc1cSGreg Roach    }
185d346cc1cSGreg Roach}
186