src/Application/Traits/ServersideDatatablesTrait.php line 47

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