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

Open in your IDE?
  1. <?php
  2. namespace Knp\Component\Pager\Event\Subscriber\Sortable;
  3. use Elastica\Query;
  4. use Elastica\SearchableInterface;
  5. use Knp\Component\Pager\Event\ItemsEvent;
  6. use Knp\Component\Pager\PaginatorInterface;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpFoundation\Request;
  9. class ElasticaQuerySubscriber implements EventSubscriberInterface
  10. {
  11.     private Request $request;
  12.     public function __construct(Request $request)
  13.     {
  14.         $this->request $request;
  15.     }
  16.     public function items(ItemsEvent $event): void
  17.     {
  18.         // Check if the result has already been sorted by an other sort subscriber
  19.         $customPaginationParameters $event->getCustomPaginationParameters();
  20.         if (!empty($customPaginationParameters['sorted']) ) {
  21.             return;
  22.         }
  23.         if (is_array($event->target) && === count($event->target) && reset($event->target) instanceof SearchableInterface && end($event->target) instanceof Query) {
  24.             [$searchable$query] = $event->target;
  25.             $event->setCustomPaginationParameter('sorted'true);
  26.             $sortField $event->options[PaginatorInterface::SORT_FIELD_PARAMETER_NAME];
  27.             $sortDir $event->options[PaginatorInterface::SORT_DIRECTION_PARAMETER_NAME];
  28.             if (null !== $sortField && $this->request->query->has($sortField)) {
  29.                 $field $this->request->query->get($sortField);
  30.                 $dir   null !== $sortDir && $this->request->query->has($sortDir) && strtolower($this->request->query->get($sortDir)) === 'asc' 'asc' 'desc';
  31.                 if (isset($event->options[PaginatorInterface::SORT_FIELD_ALLOW_LIST]) && !in_array($field$event->options[PaginatorInterface::SORT_FIELD_ALLOW_LIST])) {
  32.                     throw new \UnexpectedValueException(sprintf('Cannot sort by: [%s] this field is not in allow list.'$field));
  33.                 }
  34.                 $query->setSort([
  35.                     $field => ['order' => $dir],
  36.                 ]);
  37.             }
  38.         }
  39.     }
  40.     public static function getSubscribedEvents(): array
  41.     {
  42.         return [
  43.             'knp_pager.items' => ['items'1],
  44.         ];
  45.     }
  46. }