src/Security/Voter/UserVoter.php line 15
<?php
namespace App\Security\Voter;
use App\Entity\User;
use phpDocumentor\Reflection\DocBlock\Tags\Uses;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Security;
use App\Entity\City;
use Doctrine\Persistence\ManagerRegistry;
use App\Entity\Orders;
class UserVoter extends Voter
{
private $em;
// these strings are just invented: you can use anything
const VIEW = 'view';
const EDIT = 'edit';
public function __construct(protected Security $security, protected ManagerRegistry $doctrine)
{
$this->em = $this->doctrine->getManager();
}
// protected function supports($attribute, $subject)
protected function supports(string $attribute, mixed $subject): bool
{
// replace with your own logic
// https://symfony.com/doc/current/security/voters.html
return in_array($attribute, [self::EDIT, self::VIEW])
&& $subject instanceof \App\Entity\User;
}
// protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
$loginUser = $token->getUser();
/** @var Uses $user */
$user = $subject;
// if the user is anonymous, do not grant access
if (!$loginUser instanceof UserInterface) {
return false;
}
// ROLE_ADMIN can do anything! The power!
if ($this->security->isGranted('ROLE_ADMIN')) {
return true;
}
// ... (check conditions and return true to grant permission) ...
switch ($attribute) {
case self::EDIT:
if ($this->security->isGranted('ROLE_CONTRACTOR')) {
$cityIds = [];
$city = $this->em->getRepository(City::class)->findOneBy(['contractor' => $loginUser->getId()]);
if ($city->getSuburb() == null) {
$cityIdStr = $this->em->getRepository(City::class)->getSubCityIds($city->getId());
$cityIds = [];
if ($cityIdStr) {
$cityIds = explode(',', $cityIdStr);
}
}
array_push($cityIds, $city->getId());
$orderUserId = [];
$orderUserStr = $this->em->getRepository(Orders::class)->getOrderUserByCity($cityIds);
if ($orderUserStr) {
$orderUserId = explode(',', $orderUserStr);
}
return in_array($user->getId(), $orderUserId);
}
break;
case self::VIEW:
if ($this->security->isGranted('ROLE_CONTRACTOR')) {
$cityIds = [];
$city = $this->em->getRepository(City::class)->findOneBy(['contractor' => $loginUser->getId()]);
if ($city->getSuburb() == null) {
$cityIdStr = $this->em->getRepository(City::class)->getSubCityIds($city->getId());
$cityIds = [];
if ($cityIdStr) {
$cityIds = explode(',', $cityIdStr);
}
}
array_push($cityIds, $city->getId());
$orderUserId = [];
$orderUserStr = $this->em->getRepository(Orders::class)->getOrderUserByCity($cityIds);
if ($orderUserStr) {
$orderUserId = explode(',', $orderUserStr);
}
return in_array($user->getId(), $orderUserId);
}
break;
}
return false;
}
}