src/Security/Voter/RestaurantsVoter.php line 13
<?php
namespace App\Security\Voter;
use App\Entity\Restaurants;
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;
class RestaurantsVoter 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\Restaurants;
}
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
// protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$user = $token->getUser();
/** @var Restaurants $restaurants */
$restaurants = $subject;
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface || $restaurants->getDeleted()) {
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' => $user->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());
return in_array($restaurants->getCityId()->getId(), $cityIds);
} elseif ($this->security->isGranted('ROLE_OWNER')) {
return $user === $restaurants->getUserId();
}
break;
case self::VIEW:
if ($this->security->isGranted('ROLE_CONTRACTOR')) {
$cityIds = [];
$city = $this->em->getRepository(City::class)->findOneBy(['contractor' => $user->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());
return in_array($restaurants->getCityId()->getId(), $cityIds);
} elseif ($this->security->isGranted('ROLE_OWNER')) {
return $user === $restaurants->getUserId();
}
break;
}
return false;
}
}