src/Security/Voter/DeductionVoter.php line 13
<?php
namespace App\Security\Voter;
use App\Entity\Deductions;
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 DeductionVoter 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])
&& $subject instanceof \App\Entity\Deductions;
}
// protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
$user = $token->getUser();
/** @var Deductions $deduction */
$deduction = $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());
if ($deduction->getDeductionType() == Deductions::DEDUCTION_TYPE_DEDUCTION) {
if ($deduction->getOrderID() == null) {
return in_array($deduction->getRestaurantId()->getCityId()->getId(), $cityIds);
} else {
return in_array($deduction->getOrderID()->getCityId()->getId(), $cityIds);
}
}
}
break;
}
return false;
}
}