<?php
namespace App\Security\Voter;
use App\Entity\User;
use App\Entity\Commande;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
class CommandeVoter extends Voter
{
public const EDIT = 'COMMANDE_EDIT';
public const VIEW = 'COMMANDE_VIEW';
public const DELETE = 'COMMANDE_DELETE';
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports(string $attribute, $commande): bool
{
// replace with your own logic
// https://symfony.com/doc/current/security/voters.html
return in_array($attribute, [self::EDIT, self::VIEW, self::DELETE])
&& $commande instanceof \App\Entity\Commande;
}
protected function voteOnAttribute(string $attribute, $commande, TokenInterface $token): bool
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
//On vérifie si l'utilisateur est admin
if($this->security->isGranted('ROLE_ADMIN'))
{
return true;
}
// ... (check conditions and return true to grant permission) ...
switch ($attribute) {
case self::EDIT:
// on vérifie si on peut éditer
return $this->canEdit($commande, $user);
break;
case self::VIEW:
// on vérifie si on peut visualiser
return $this->canView($commande, $user);
break;
case self::DELETE:
// on vérifie si on peut supprimer
return $this->canDelete($commande, $user);
break;
}
return false;
}
public function canEdit(Commande $commande, User $user)
{
if($this->security->isGranted('ROLE_FOODTRUCK'))
{
return in_array($commande->getService()->getFoodtruck(), $user->getFoodtrucks()->toArray());
}
return false;
}
public function canView(Commande $commande, User $user)
{
if($this->security->isGranted('ROLE_FOODTRUCK'))
{
return in_array($commande->getService()->getFoodtruck(), $user->getFoodtrucks()->toArray());
}
if($this->security->isGranted('ROLE_USER'))
{
return $user === $commande->getUser();
}
return false;
}
public function canDelete(Commande $commande, User $user)
{
if($this->security->isGranted('ROLE_FOODTRUCK'))
{
return in_array($commande->getService()->getFoodtruck(), $user->getFoodtrucks()->toArray());
}
return false;
}
}