Skip to content

Instantly share code, notes, and snippets.

@romaricdrigon
Last active January 14, 2020 07:22
Show Gist options
  • Save romaricdrigon/88cc8c9f5cb20e84c0ebc8c472bd5b7e to your computer and use it in GitHub Desktop.
Save romaricdrigon/88cc8c9f5cb20e84c0ebc8c472bd5b7e to your computer and use it in GitHub Desktop.
<?php
namespace App\Filter;
use App\Entity\Blog;
use App\Entity\User;
use Doctrine\ORM\Mapping\ClassMetaData;
use Doctrine\ORM\Query\Filter\SQLFilter;
class BlogFilter extends SQLFilter
{
public function addFilterConstraint(ClassMetadata $entityMetadata, $alias)
{
if (Blog::class !== $entityMetadata->reflClass->getName()) {
return '';
}
$userId = $this->getParameter('user');
if (null === $userId) {
throw new \Exception('User was not set!');
}
return $alias.'.owner_id = '.$userId; // This SQL will be injected in 'WHERE'
}
}
# config/packages/doctrine.yaml
orm:
entity_managers:
default:
filters:
blog_filter:
class: App\Filter\BlogFilter
enabled: false
<?php
namespace App\EventSubscriber;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class InitUserFilterSubscriber implements EventSubscriberInterface
{
private $tokenStorage;
private $entityManager;
public function __construct(TokenStorageInterface $tokenStorage, EntityManagerInterface $entityManager)
{
$this->tokenStorage = $tokenStorage;
$this->entityManager = $entityManager;
}
public function onRequest()
{
if (!$this->tokenStorage->getToken() || !$user = $this->tokenStorage->getToken()->getUser()) {
return;
}
if (!$user instanceof User) {
return;
}
$this->entityManager->getFilters()->enable('blog_filter');
$this->entityManager->getFilters()->getFilter('blog_filter')->setParameter('user', $user->getId());
}
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => 'onRequest',
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment