src/Security/Voter/MenuSectionVoter.php line 15
<?php
namespace App\Security\Voter;
use App\Entity\MenuSections;
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;
use Symfony\Component\HttpFoundation\RequestStack;
class MenuSectionVoter extends Voter
{
private $em;
private $session;
// these strings are just invented: you can use anything
const EDIT = 'edit';
public function __construct(
protected Security $security,
protected ManagerRegistry $doctrine,
protected RequestStack $requestStack
)
{
$this->em = $this->doctrine->getManager();
$this->session = $this->requestStack->getSession();
}
// 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])
&& $subject instanceof \App\Entity\MenuSections;
}
// protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
$user = $token->getUser();
/** @var MenuSections $menuSection */
$menuSection = $subject;
// if the user is anonymous, do not grant access
if (!$user 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' => $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());
$restIdStr = $this->em->getRepository(Restaurants::class)->getRestIdsByCity($cityIds);
$restIds = [];
if ($restIdStr) {
$restIds = explode(',', $restIdStr);
}
return in_array($menuSection->getRestaurantId()->getId(),$restIds);
} elseif ($this->security->isGranted('ROLE_OWNER')) {
return $menuSection->getRestaurantId()->getId() === $this->session->get('loginRestId');
}
break;
}
return false;
}
}