KarlComSe /
mvc-report
| 1 | <?php |
||
| 2 | // api/src/Doctrine/CurrentUserExtension.php |
||
| 3 | |||
| 4 | namespace App\Doctrine; |
||
| 5 | |||
| 6 | use ApiPlatform\Doctrine\Orm\Extension\QueryCollectionExtensionInterface; |
||
| 7 | use ApiPlatform\Doctrine\Orm\Extension\QueryItemExtensionInterface; |
||
| 8 | use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface; |
||
| 9 | use ApiPlatform\Metadata\Operation; |
||
| 10 | use App\Entity\Organization; |
||
| 11 | use Doctrine\ORM\QueryBuilder; |
||
| 12 | use Symfony\Bundle\SecurityBundle\Security; |
||
| 13 | |||
| 14 | final readonly class CurrentUserExtension implements QueryCollectionExtensionInterface, QueryItemExtensionInterface |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 15 | { |
||
| 16 | public function __construct( |
||
| 17 | private Security $security, |
||
| 18 | ) { |
||
| 19 | } |
||
| 20 | |||
| 21 | public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, Operation $operation = null, array $context = []): void |
||
| 22 | { |
||
| 23 | $this->addWhere($queryBuilder, $resourceClass); |
||
| 24 | } |
||
| 25 | |||
| 26 | public function applyToItem(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, Operation $operation = null, array $context = []): void |
||
| 27 | { |
||
| 28 | $this->addWhere($queryBuilder, $resourceClass); |
||
| 29 | } |
||
| 30 | |||
| 31 | private function addWhere(QueryBuilder $queryBuilder, string $resourceClass): void |
||
| 32 | { |
||
| 33 | if (null === $user = $this->security->getUser()) { |
||
| 34 | $queryBuilder->andWhere('1 = 0'); |
||
| 35 | return; |
||
| 36 | } |
||
| 37 | if (Organization::class !== $resourceClass || $this->security->isGranted('ROLE_ADMIN')) { |
||
| 38 | return; |
||
| 39 | } |
||
| 40 | $rootAlias = $queryBuilder->getRootAliases()[0]; |
||
| 41 | $queryBuilder->andWhere(sprintf(':current_user MEMBER OF o.users', $rootAlias)); |
||
| 42 | $queryBuilder->setParameter('current_user', $user->getId()); |
||
| 43 | } |
||
| 44 | } |