<?php
namespace App\Security\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class UserVoter extends Voter
{
public const EDIT = 'USER_EDIT';
public const VIEW = 'USER_VIEW';
protected function supports(string $attribute, $profil): bool
{
// replace with your own logic
// https://symfony.com/doc/current/security/voters.html
return in_array($attribute, [self::EDIT, self::VIEW])
&& $profil instanceof \App\Entity\User;
}
protected function voteOnAttribute(string $attribute, $profil, TokenInterface $token): bool
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
// ... (check conditions and return true to grant permission) ...
switch ($attribute) {
case self::EDIT:
// logic to determine if the user can EDIT
// return true or false
return $this->canEdit($profil,$user);
break;
case self::VIEW:
// logic to determine if the user can VIEW
// return true or false
return $this->canView($profil,$user);
break;
}
return false;
}
public function canEdit($profil,$user)
{
//Si le user veux consulter son profil
if($user === $profil){
return true;
}
//Si le user veut consulter le profil d'un client
$commandes = $profil->getCommandes();
foreach ($commandes as $key => $commande) {
//Si le client a déjà passé une commande auprès de ce foodtruck
if(in_array($commande->getService()->getFoodtruck(),$user->getFoodtrucks()->toArray())){
return true;
}
}
}
public function canView($profil,$user)
{
//Si le user veux consulter son profil
if($user === $profil){
return true;
}
//Si le user veut consulter le profil d'un client
$commandes = $profil->getCommandes();
foreach ($commandes as $key => $commande) {
//Si le client a déjà passé une commande auprès de ce foodtruck
if(in_array($commande->getService()->getFoodtruck(),$user->getFoodtrucks()->toArray())){
return true;
}
}
}
}