xref: /webtrees/app/Services/DatatablesService.php (revision b5961194694c0b5b2dc4269689207eb972e3b20c)
1d346cc1cSGreg Roach<?php
23976b470SGreg Roach
3d346cc1cSGreg Roach/**
4d346cc1cSGreg Roach * webtrees: online genealogy
5*b5961194SGreg Roach * Copyright (C) 2020 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
15d346cc1cSGreg Roach * along with this program. If not, see <http://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;
23d346cc1cSGreg Roachuse Illuminate\Database\Query\Builder;
24a69f5655SGreg Roachuse Illuminate\Database\Query\Expression;
2513aa75d8SGreg Roachuse Illuminate\Support\Collection;
266ccdf4f0SGreg Roachuse Psr\Http\Message\ResponseInterface;
276ccdf4f0SGreg Roachuse Psr\Http\Message\ServerRequestInterface;
28d346cc1cSGreg Roach
29*b5961194SGreg Roachuse function addcslashes;
30*b5961194SGreg Roachuse function strtr;
31*b5961194SGreg Roach
32d346cc1cSGreg Roach/**
33d346cc1cSGreg Roach * Paginate and search queries for datatables.
3413aa75d8SGreg Roach *
3513aa75d8SGreg Roach * @link http://www.datatables.net/usage/server-side
36d346cc1cSGreg Roach */
37d346cc1cSGreg Roachclass DatatablesService
38d346cc1cSGreg Roach{
39d346cc1cSGreg Roach    /**
4013aa75d8SGreg Roach     * Apply filtering and pagination to a collection, and generate a response suitable for datatables.
41d346cc1cSGreg Roach     *
426ccdf4f0SGreg Roach     * @param ServerRequestInterface $request        Includes the datatables request parameters.
4313aa75d8SGreg Roach     * @param Collection             $collection     All the data.
4413aa75d8SGreg Roach     * @param string[]|int[]         $search_columns The names of searchable columns.
4513aa75d8SGreg Roach     * @param string[]|int[]         $sort_columns   Sort column mapping.
46d346cc1cSGreg Roach     * @param Closure                $callback       Converts a row-object to an array-of-columns.
47d346cc1cSGreg Roach     *
486ccdf4f0SGreg Roach     * @return ResponseInterface
49d346cc1cSGreg Roach     */
5013aa75d8SGreg Roach    public function handleCollection(ServerRequestInterface $request, Collection $collection, array $search_columns, array $sort_columns, Closure $callback): ResponseInterface
5113aa75d8SGreg Roach    {
5213aa75d8SGreg Roach        $search = $request->getQueryParams()['search']['value'] ?? '';
5313aa75d8SGreg Roach        $start  = (int) ($request->getQueryParams()['start'] ?? 0);
5413aa75d8SGreg Roach        $length = (int) ($request->getQueryParams()['length'] ?? 0);
5513aa75d8SGreg Roach        $order  = $request->getQueryParams()['order'] ?? [];
5613aa75d8SGreg Roach        $draw   = (int) ($request->getQueryParams()['draw'] ?? 0);
5713aa75d8SGreg Roach
5813aa75d8SGreg Roach        // Count unfiltered records
5913aa75d8SGreg Roach        $recordsTotal = $collection->count();
6013aa75d8SGreg Roach
6113aa75d8SGreg Roach        // Filtering
6213aa75d8SGreg Roach        if ($search !== '') {
6313aa75d8SGreg Roach            $collection = $collection->filter(static function (array $row) use ($search, $search_columns): bool {
6413aa75d8SGreg Roach                foreach ($search_columns as $search_column) {
6513aa75d8SGreg Roach                    if (stripos($row[$search_column], $search) !== false) {
6613aa75d8SGreg Roach                        return true;
6713aa75d8SGreg Roach                    }
6813aa75d8SGreg Roach                }
6913aa75d8SGreg Roach
7013aa75d8SGreg Roach                return false;
7113aa75d8SGreg Roach            });
7213aa75d8SGreg Roach        }
7313aa75d8SGreg Roach
7413aa75d8SGreg Roach        // Sorting
7513aa75d8SGreg Roach        if ($order !== []) {
7613aa75d8SGreg Roach            $collection = $collection->sort(static function (array $row1, array $row2) use ($order, $sort_columns): int {
7713aa75d8SGreg Roach                foreach ($order as $column) {
7813aa75d8SGreg Roach                    $key = $sort_columns[$column['column']];
7913aa75d8SGreg Roach                    $dir = $column['dir'];
8013aa75d8SGreg Roach
8113aa75d8SGreg Roach                    if ($dir === 'asc') {
8213aa75d8SGreg Roach                        $comparison = $row1[$key] <=> $row2[$key];
8313aa75d8SGreg Roach                    } else {
8413aa75d8SGreg Roach                        $comparison = $row2[$key] <=> $row1[$key];
8513aa75d8SGreg Roach                    }
8613aa75d8SGreg Roach
8713aa75d8SGreg Roach                    if ($comparison !== 0) {
8813aa75d8SGreg Roach                        return $comparison;
8913aa75d8SGreg Roach                    }
9013aa75d8SGreg Roach                }
9113aa75d8SGreg Roach
9213aa75d8SGreg Roach                return 0;
9313aa75d8SGreg Roach            });
9413aa75d8SGreg Roach        }
9513aa75d8SGreg Roach
9613aa75d8SGreg Roach        // Paginating
9713aa75d8SGreg Roach        if ($length > 0) {
9813aa75d8SGreg Roach            $recordsFiltered = $collection->count();
9913aa75d8SGreg Roach
10013aa75d8SGreg Roach            $data = $collection->slice($start, $length);
10113aa75d8SGreg Roach        } else {
10213aa75d8SGreg Roach            $recordsFiltered = $collection->count();
10313aa75d8SGreg Roach
10413aa75d8SGreg Roach            $data = $collection;
10513aa75d8SGreg Roach        }
10613aa75d8SGreg Roach
10713aa75d8SGreg Roach        $data = $data->map($callback)->values()->all();
10813aa75d8SGreg Roach
10913aa75d8SGreg Roach        return response([
11013aa75d8SGreg Roach            'draw'            => $draw,
11113aa75d8SGreg Roach            'recordsTotal'    => $recordsTotal,
11213aa75d8SGreg Roach            'recordsFiltered' => $recordsFiltered,
11313aa75d8SGreg Roach            'data'            => $data,
11413aa75d8SGreg Roach        ]);
11513aa75d8SGreg Roach    }
11613aa75d8SGreg Roach
11713aa75d8SGreg Roach    /**
11813aa75d8SGreg Roach     * Apply filtering and pagination to a database query, and generate a response suitable for datatables.
11913aa75d8SGreg Roach     *
12013aa75d8SGreg Roach     * @param ServerRequestInterface $request        Includes the datatables request parameters.
12113aa75d8SGreg Roach     * @param Builder                $query          A query to fetch the unfiltered rows and columns.
12213aa75d8SGreg Roach     * @param string[]               $search_columns The names of searchable columns.
12313aa75d8SGreg Roach     * @param string[]               $sort_columns   Sort column mapping.
12413aa75d8SGreg Roach     * @param Closure                $callback       Converts a row-object to an array-of-columns.
12513aa75d8SGreg Roach     *
12613aa75d8SGreg Roach     * @return ResponseInterface
12713aa75d8SGreg Roach     */
12813aa75d8SGreg Roach    public function handleQuery(ServerRequestInterface $request, Builder $query, array $search_columns, array $sort_columns, Closure $callback): ResponseInterface
129d346cc1cSGreg Roach    {
1306ccdf4f0SGreg Roach        $search = $request->getQueryParams()['search']['value'] ?? '';
1316ccdf4f0SGreg Roach        $start  = (int) ($request->getQueryParams()['start'] ?? 0);
1326ccdf4f0SGreg Roach        $length = (int) ($request->getQueryParams()['length'] ?? 0);
1336ccdf4f0SGreg Roach        $order  = $request->getQueryParams()['order'] ?? [];
1346ccdf4f0SGreg Roach        $draw   = (int) ($request->getQueryParams()['draw'] ?? 0);
135d346cc1cSGreg Roach
136d346cc1cSGreg Roach        // Count unfiltered records
137d346cc1cSGreg Roach        $recordsTotal = (clone $query)->count();
138d346cc1cSGreg Roach
139d346cc1cSGreg Roach        // Filtering
140d346cc1cSGreg Roach        if ($search !== '') {
1410b5fd0a6SGreg Roach            $query->where(static function (Builder $query) use ($search, $search_columns): void {
142*b5961194SGreg Roach                $like = '%' . addcslashes($search, '\\%_') . '%';
143*b5961194SGreg Roach                $like = strtr($like, [' ' => '%']);
144*b5961194SGreg Roach
145d346cc1cSGreg Roach                foreach ($search_columns as $search_column) {
146*b5961194SGreg Roach                    $query->orWhere($search_column, 'LIKE', $like);
147d346cc1cSGreg Roach                }
148d346cc1cSGreg Roach            });
149d346cc1cSGreg Roach        }
150d346cc1cSGreg Roach
151d346cc1cSGreg Roach        // Sorting
15254c1ab5eSGreg Roach        if ($order !== []) {
153d346cc1cSGreg Roach            foreach ($order as $value) {
154d346cc1cSGreg Roach                // Columns in datatables are numbered from zero.
155d346cc1cSGreg Roach                // Columns in MySQL are numbered starting with one.
1568a22b886SGreg Roach                // If not specified, the Nth table column maps onto the Nth query column.
157a69f5655SGreg Roach                $sort_column = $sort_columns[$value['column']] ?? new Expression(1 + $value['column']);
1588a22b886SGreg Roach
1598a22b886SGreg Roach                $query->orderBy($sort_column, $value['dir']);
160d346cc1cSGreg Roach            }
161d346cc1cSGreg Roach        } else {
162a69f5655SGreg Roach            $query->orderBy(new Expression(1));
163d346cc1cSGreg Roach        }
164d346cc1cSGreg Roach
165d346cc1cSGreg Roach        // Paginating
166d346cc1cSGreg Roach        if ($length > 0) {
167d346cc1cSGreg Roach            $recordsFiltered = (clone $query)->count();
168d346cc1cSGreg Roach
169d346cc1cSGreg Roach            $query->skip($start)->limit($length);
170d346cc1cSGreg Roach            $data = $query->get();
171d346cc1cSGreg Roach        } else {
172d346cc1cSGreg Roach            $data = $query->get();
173d346cc1cSGreg Roach
174d346cc1cSGreg Roach            $recordsFiltered = $data->count();
175d346cc1cSGreg Roach        }
176d346cc1cSGreg Roach
177d346cc1cSGreg Roach        $data = $data->map($callback)->all();
178d346cc1cSGreg Roach
1796ccdf4f0SGreg Roach        return response([
180d346cc1cSGreg Roach            'draw'            => $draw,
181d346cc1cSGreg Roach            'recordsTotal'    => $recordsTotal,
182d346cc1cSGreg Roach            'recordsFiltered' => $recordsFiltered,
183d346cc1cSGreg Roach            'data'            => $data,
184d346cc1cSGreg Roach        ]);
185d346cc1cSGreg Roach    }
186d346cc1cSGreg Roach}
187