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

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.     /**
  12.      * @var Request
  13.      */
  14.     private $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) && reset($event->target) instanceof SearchableInterface && end($event->target) instanceof Query) {
  27.             [$searchable$query] = $event->target;
  28.             $event->setCustomPaginationParameter('sorted'true);
  29.             $sortField $event->options[PaginatorInterface::SORT_FIELD_PARAMETER_NAME];
  30.             $sortDir $event->options[PaginatorInterface::SORT_DIRECTION_PARAMETER_NAME];
  31.             if (null !== $sortField && $this->request->query->has($sortField)) {
  32.                 $field $this->request->query->get($sortField);
  33.                 $dir   null !== $sortDir && $this->request->query->has($sortDir) && strtolower($this->request->query->get($sortDir)) === 'asc' 'asc' 'desc';
  34.                 if (isset($event->options[PaginatorInterface::SORT_FIELD_ALLOW_LIST]) && !in_array($field$event->options[PaginatorInterface::SORT_FIELD_ALLOW_LIST])) {
  35.                     throw new \UnexpectedValueException(sprintf('Cannot sort by: [%s] this field is not in allow list.'$field));
  36.                 }
  37.                 $query->setSort([
  38.                     $field => ['order' => $dir],
  39.                 ]);
  40.             }
  41.         }
  42.     }
  43.     public static function getSubscribedEvents(): array
  44.     {
  45.         return [
  46.             'knp_pager.items' => ['items'1],
  47.         ];
  48.     }
  49. }