<?php
namespace App\Security\Voter;
use App\Entity\User;
use App\Entity\Foodtruck;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
class FoodtruckVoter extends Voter
{
public const EDIT = 'FOODTRUCK_EDIT';
public const VIEW = 'FOODTRUCK_VIEW';
public const DELETE = 'FOODTRUCK_DELETE';
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports(string $attribute, $foodtruck): bool
{
// replace with your own logic
// https://symfony.com/doc/current/security/voters.html
return in_array($attribute, [self::EDIT, self::VIEW, self::DELETE])
&& $foodtruck instanceof \App\Entity\Foodtruck;
}
protected function voteOnAttribute(string $attribute, $foodtruck, 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;
}
// On vérifie si le foodtruck a un propriétaire
if(null === $foodtruck->getUsers()){
return false;
}
// ... (check conditions and return true to grant permission) ...
switch ($attribute) {
case self::EDIT:
// on vérifie si on peut éditer
return $this->canEdit($foodtruck, $user);
break;
case self::VIEW:
// on vérifie si on peut visualiser
return $this->canView($foodtruck, $user);
break;
case self::DELETE:
// on vérifie si on peut supprimer
return $this->canDelete($foodtruck, $user);
break;
}
return false;
}
private function canEdit(Foodtruck $foodtruck, User $user){
// Le propriétaire du foodtruck peut le modifier
// return $user === $foodtruck->getUsers();
return in_array($foodtruck, $user->getFoodtrucks()->getValues());
// if(in_array($foodtruck,$this->getUser()->getFoodtrucks()->getValues()) OR $this->isGranted('ROLE_ADMIN')){
// return true;
// } else {
// return false;
// }
}
private function canView(Foodtruck $foodtruck, User $user){
return in_array($foodtruck, $user->getFoodtrucks()->getValues());
}
private function canDelete(Foodtruck $foodtruck, User $user){
// Le propriétaire du foodtruck peut le supprimer
return in_array($foodtruck, $user->getFoodtrucks()->getValues());
}
}