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

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