src/Security/Voter/OrderVoter.php line 14
<?php
namespace App\Security\Voter;
use App\Entity\Orders;
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 OrderVoter 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::VIEW])
&& $subject instanceof \App\Entity\Orders;
}
// protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
// dump("ddd");
// die();
$user = $token->getUser();
/** @var Orders $order */
$order = $subject;
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface || $order->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::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($order->getCityId()->getId(), $cityIds);
}
elseif ($this->security->isGranted('ROLE_OWNER')) {
$restaurants = $this->em->getRepository(Restaurants::class)->findOneBy(['userId'=>$user->getId()]);
if($restaurants!=null)
{
return $order->getRestaurantId()->getId() === $restaurants->getId();
}
}
break;
}
return false;
}
}