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

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