<?php
namespace App\ApiPlatform\Filter;
use ApiPlatform\Api\FilterInterface;
use ApiPlatform\Core\Bridge\Doctrine\Common\Filter\BooleanFilterTrait;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\AbstractFilter;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use App\Entity\Agent;
use App\Entity\Manager;
use Doctrine\ORM\QueryBuilder;
use Doctrine\Persistence\ManagerRegistry;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
class CurrentUserFilter extends AbstractFilter implements FilterInterface
{
use BooleanFilterTrait;
private const FIELD_NAME = 'currentUser';
private TokenStorageInterface $tokenStorage;
public function __construct(
TokenStorageInterface $tokenStorage,
ManagerRegistry $managerRegistry,
?RequestStack $requestStack = null,
LoggerInterface $logger = null,
array $properties = null,
NameConverterInterface $nameConverter = null
) {
parent::__construct($managerRegistry, $requestStack, $logger, $properties, $nameConverter);
$this->tokenStorage = $tokenStorage;
}
protected function filterProperty(
string $property,
$value,
QueryBuilder $queryBuilder,
QueryNameGeneratorInterface $queryNameGenerator,
string $resourceClass,
string $operationName = null
): void {
if (self::FIELD_NAME !== $property) {
return;
}
$value = $this->normalizeValue($value, $property);
if (null === $value || $value === false) {
return;
}
if ($this->tokenStorage->getToken() !== null && $this->tokenStorage->getToken()->getUser() instanceof Manager) {
return;
}
$valueParameter = $queryNameGenerator->generateParameterName(self::FIELD_NAME);
$alias = $queryBuilder->getRootAliases()[0];
$queryBuilder->andWhere(sprintf(
'%s.id != :%s ',
$alias,
$valueParameter,
))->setParameter($valueParameter, $this->getUser()->getId());
}
public function getDescription(string $resourceClass): array
{
return [
'currentUser' => [
'property' => null,
'type' => 'boolean',
'required' => false,
'swagger' => [
'description' => 'Filter current user from agents list.',
'name' => 'Custom name to use in the Swagger documentation',
'type' => 'Will appear below the name in the Swagger documentation',
],
]
];
}
private function getUser(): ?Agent
{
if (!$token = $this->tokenStorage->getToken()) {
return null;
}
$user = $token->getUser();
if (!$user instanceof Agent) {
return null;
}
return $user;
}
}