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

  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. class PropelQuerySubscriber implements EventSubscriberInterface
  9. {
  10.     private ArgumentAccessInterface $argumentAccess;
  11.     public function __construct(ArgumentAccessInterface $argumentAccess)
  12.     {
  13.         $this->argumentAccess $argumentAccess;
  14.     }
  15.     public function items(ItemsEvent $event): void
  16.     {
  17.         // Check if the result has already been sorted by another sort subscriber
  18.         $customPaginationParameters $event->getCustomPaginationParameters();
  19.         if (!empty($customPaginationParameters['sorted']) ) {
  20.             return;
  21.         }
  22.         $query $event->target;
  23.         if ($query instanceof \ModelCriteria) {
  24.             $event->setCustomPaginationParameter('sorted'true);
  25.             $sortField $event->options[PaginatorInterface::SORT_FIELD_PARAMETER_NAME];
  26.             $sortDir $event->options[PaginatorInterface::SORT_DIRECTION_PARAMETER_NAME];
  27.             if (null !== $sortField && $this->argumentAccess->has($sortField)) {
  28.                 $part $this->argumentAccess->get($sortField);
  29.                 $direction = (null !== $sortDir && $this->argumentAccess->has($sortDir) && strtolower($this->argumentAccess->get($sortDir)) === 'asc')
  30.                                 ? 'asc' 'desc';
  31.                 if (isset($event->options[PaginatorInterface::SORT_FIELD_ALLOW_LIST])) {
  32.                     if (!in_array($this->argumentAccess->get($sortField), $event->options[PaginatorInterface::SORT_FIELD_ALLOW_LIST])) {
  33.                         throw new InvalidValueException("Cannot sort by: [{$this->argumentAccess->get($sortField)}] this field is not in allow list.");
  34.                     }
  35.                 }
  36.                 $query->orderBy($part$direction);
  37.             }
  38.         }
  39.     }
  40.     public static function getSubscribedEvents(): array
  41.     {
  42.         return [
  43.             'knp_pager.items' => ['items'1],
  44.         ];
  45.     }
  46. }