Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
0.00% |
0 / 20 |
|
0.00% |
0 / 3 |
CRAP | |
0.00% |
0 / 1 |
ServersideDatatablesTrait | |
0.00% |
0 / 20 |
|
0.00% |
0 / 3 |
42 | |
0.00% |
0 / 1 |
getCorrespondingLabelFromKey | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
6 | |||
listDataTables | n/a |
0 / 0 |
n/a |
0 / 0 |
0 | |||||
getBaseDataTablesResponse | |
0.00% |
0 / 8 |
|
0.00% |
0 / 1 |
2 | |||
getResults | |
0.00% |
0 / 11 |
|
0.00% |
0 / 1 |
12 | |||
getLabelAndKeysArray | n/a |
0 / 0 |
n/a |
0 / 0 |
0 |
1 | <?php |
2 | |
3 | namespace App\Application\Traits; |
4 | |
5 | use App\Application\Doctrine\Repository\DataTablesRepository; |
6 | use Doctrine\ORM\Tools\Pagination\Paginator; |
7 | use Symfony\Component\HttpFoundation\JsonResponse; |
8 | use Symfony\Component\HttpFoundation\Request; |
9 | |
10 | trait ServersideDatatablesTrait |
11 | { |
12 | /** |
13 | * @var DataTablesRepository |
14 | */ |
15 | protected $repository; |
16 | |
17 | /** |
18 | * Get the label of the column corresponding to the specified key. |
19 | * |
20 | * @param string $key The column number of the column |
21 | */ |
22 | protected function getCorrespondingLabelFromKey(string $key) |
23 | { |
24 | return \array_key_exists($key, $this->getLabelAndKeysArray()) ? $this->getLabelAndKeysArray()[$key] : null; |
25 | } |
26 | |
27 | /** |
28 | * The function called with AJAX by the datatables to retrieve data |
29 | * Manage order, filters and so on. |
30 | */ |
31 | abstract public function listDataTables(Request $request): JsonResponse; |
32 | |
33 | protected function getBaseDataTablesResponse(Request $request, $results, array $criteria = []) |
34 | { |
35 | $draw = $request->request->get('draw'); |
36 | |
37 | $reponse = [ |
38 | 'draw' => $draw, |
39 | 'recordsTotal' => $this->repository->count($criteria), |
40 | 'recordsFiltered' => count($results), |
41 | 'data' => [], |
42 | ]; |
43 | |
44 | return $reponse; |
45 | } |
46 | |
47 | protected function getResults(Request $request, array $criteria = []): ?Paginator |
48 | { |
49 | $first = $request->request->get('start'); |
50 | $maxResults = $request->request->get('length'); |
51 | $orders = $request->request->get('order'); |
52 | $columns = $request->request->get('columns'); |
53 | |
54 | $orderColumn = $this->getCorrespondingLabelFromkey($orders[0]['column']); |
55 | $orderDir = $orders[0]['dir']; |
56 | |
57 | $searches = []; |
58 | foreach ($columns as $column) { |
59 | if ('' !== $column['search']['value']) { |
60 | $searches[$column['data']] = $column['search']['value']; |
61 | } |
62 | } |
63 | |
64 | return $this->repository->findPaginated($first, $maxResults, $orderColumn, $orderDir, $searches, $criteria); |
65 | } |
66 | |
67 | /** |
68 | * Return an array containing the correspondance between key (column number) |
69 | * and column label. |
70 | */ |
71 | abstract protected function getLabelAndKeysArray(): array; |
72 | } |