vendor/knplabs/knp-components/src/Knp/Component/Pager/Event/Subscriber/Sortable/SolariumQuerySubscriber.php line 24

Open in your IDE?
  1. <?php
  2. namespace Knp\Component\Pager\Event\Subscriber\Sortable;
  3. use Knp\Component\Pager\Event\ItemsEvent;
  4. use Knp\Component\Pager\PaginatorInterface;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\Request;
  7. /**
  8.  * Solarium query sorting
  9.  *
  10.  * @author Marek Kalnik <marekk@theodo.fr>
  11.  */
  12. class SolariumQuerySubscriber implements EventSubscriberInterface
  13. {
  14.     private Request $request;
  15.     public function __construct(Request $request)
  16.     {
  17.         $this->request $request;
  18.     }
  19.     public function items(ItemsEvent $event): void
  20.     {
  21.         // Check if the result has already been sorted by an other sort subscriber
  22.         $customPaginationParameters $event->getCustomPaginationParameters();
  23.         if (!empty($customPaginationParameters['sorted']) ) {
  24.             return;
  25.         }
  26.         if (is_array($event->target) && === count($event->target)) {
  27.             $values array_values($event->target);
  28.             [$client$query] = $values;
  29.             if ($client instanceof \Solarium\Client && $query instanceof \Solarium\QueryType\Select\Query\Query) {
  30.                 $event->setCustomPaginationParameter('sorted'true);
  31.                 $sortField $event->options[PaginatorInterface::SORT_FIELD_PARAMETER_NAME];
  32.                 if (null !== $sortField && $this->request->query->has($sortField)) {
  33.                     if (isset($event->options[PaginatorInterface::SORT_FIELD_ALLOW_LIST])) {
  34.                         if (!in_array($this->request->query->get($sortField), $event->options[PaginatorInterface::SORT_FIELD_ALLOW_LIST])) {
  35.                             throw new \UnexpectedValueException("Cannot sort by: [{$this->request->query->get($sortField)}] this field is not in allow list.");
  36.                         }
  37.                     }
  38.                     $query->addSort($this->request->query->get($sortField), $this->getSortDirection($event));
  39.                 }
  40.             }
  41.         }
  42.     }
  43.     public static function getSubscribedEvents(): array
  44.     {
  45.         return [
  46.             // trigger before the pagination subscriber
  47.             'knp_pager.items' => ['items'1],
  48.         ];
  49.     }
  50.     private function getSortDirection($event): string
  51.     {
  52.         $sortDir $event->options[PaginatorInterface::SORT_DIRECTION_PARAMETER_NAME];
  53.         return null !== $sortDir && $this->request->query->has($sortDir) &&
  54.             strtolower($this->request->query->get($sortDir)) === 'asc' 'asc' 'desc';
  55.     }
  56. }