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

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