xref: /webtrees/app/Services/DatatablesService.php (revision c88a5019dff7bc89d58039dfe7af14f8446e6384)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2019 webtrees development team
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16declare(strict_types=1);
17
18namespace Fisharebest\Webtrees\Services;
19
20use Closure;
21use Illuminate\Database\Capsule\Manager as DB;
22use Illuminate\Database\Query\Builder;
23use Symfony\Component\HttpFoundation\JsonResponse;
24use Symfony\Component\HttpFoundation\Request;
25use function strtr;
26
27/**
28 * Paginate and search queries for datatables.
29 */
30class DatatablesService
31{
32    /**
33     * Apply filtering and pagination to a query, and generate a response suitable for datatables.
34     *
35     * @link http://www.datatables.net/usage/server-side
36     *
37     * @param Request  $request        Includes the datatables request parameters.
38     * @param Builder  $query          A query to fetch the unfiltered rows and columns.
39     * @param string[] $search_columns The names of searchable columns.
40     * @param Closure  $callback       Converts a row-object to an array-of-columns.
41     *
42     * @return JsonResponse
43     */
44    public function handle(Request $request, Builder $query, array $search_columns, Closure $callback): JsonResponse
45    {
46        $search = $request->get('search', [])['value'] ?? '';
47        $start  = (int) $request->get('start');
48        $length = (int) $request->get('length');
49        $order  = $request->get('order', []);
50        $draw   = (int) $request->get('draw');
51
52        // Count unfiltered records
53        $recordsTotal = (clone $query)->count();
54
55        // Filtering
56        if ($search !== '') {
57            $query->where(function (Builder $query) use ($search, $search_columns): void {
58                foreach ($search_columns as $search_column) {
59                    $query->orWhereContains($search_column, $search);
60                }
61            });
62        }
63
64        // Sorting
65        if (!empty($order)) {
66            foreach ($order as $value) {
67                // Columns in datatables are numbered from zero.
68                // Columns in MySQL are numbered starting with one.
69                $query->orderBy(DB::raw(1 + $value['column']), $value['dir']);
70            }
71        } else {
72            $query->orderBy(DB::raw(1));
73        }
74
75        // Paginating
76        if ($length > 0) {
77            $recordsFiltered = (clone $query)->count();
78
79            $query->skip($start)->limit($length);
80            $data = $query->get();
81        } else {
82            $data = $query->get();
83
84            $recordsFiltered = $data->count();
85        }
86
87        $data = $data->map($callback)->all();
88
89        return new JsonResponse([
90            'draw'            => $draw,
91            'recordsTotal'    => $recordsTotal,
92            'recordsFiltered' => $recordsFiltered,
93            'data'            => $data,
94        ]);
95    }
96}
97