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

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