<?php
namespace App\EventSubscriber;
use Doctrine\ORM\Query;
use Knp\Component\Pager\Event\ItemsEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
class PaginateSubscriber implements EventSubscriberInterface
{
public const ALIASSES = ['applicant', 'vacancy'];
/**
* @var AuthorizationCheckerInterface
*/
private $authorizationChecker;
/**
* PaginateApplicantSubscriber constructor.
*/
public function __construct(AuthorizationCheckerInterface $authorizationChecker)
{
$this->authorizationChecker = $authorizationChecker;
}
/**
* {@inheritdoc}
*/
public function items(ItemsEvent $event)
{
if (!isset($event->options['alias']) || !\in_array($event->options['alias'], self::ALIASSES, true)) {
return;
}
/** @var Query $query */
$query = $event->target;
$collection = $query->getResult();
$collection = array_filter($collection, function ($entity) {
return $this->authorizationChecker->isGranted('view', $entity);
});
$event->count = \count($collection);
$event->items = \array_slice($collection, $event->getOffset(), $event->getLimit());
$event->stopPropagation();
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return ['knp_pager.items' => ['items', 1]];
}
}