Code Coverage
 
Classes and Traits
Functions and Methods
Lines
Total
0.00% covered (danger)
0.00%
0 / 1
50.00% covered (danger)
50.00%
2 / 4
CRAP
84.21% covered (warning)
84.21%
16 / 19
TaskVoter
0.00% covered (danger)
0.00%
0 / 1
50.00% covered (danger)
50.00%
2 / 4
10.39
84.21% covered (warning)
84.21%
16 / 19
 __construct
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
2 / 2
 supports
100.00% covered (success)
100.00%
1 / 1
3
100.00% covered (success)
100.00%
5 / 5
 voteOnAttribute
0.00% covered (danger)
0.00%
0 / 1
3.21
71.43% covered (warning)
71.43%
5 / 7
 canDelete
0.00% covered (danger)
0.00%
0 / 1
3.07
80.00% covered (warning)
80.00%
4 / 5
<?php
namespace App\Security\Voter;
use App\Entity\Tasktodo;
use App\Entity\Usertodo;
// use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Security;
class TaskVoter extends Voter
{
    const DELETE = 'delete';
    /**
     * @var Security
     */
    private $security;
    public function __construct(Security $security)
    {
        $this->security = $security;
    }
    protected function supports($attribute, $subject): bool
    {
        // if the attribute isn't one we support, return false
        if (!in_array($attribute, [self::DELETE])) {
            return false;
        }
        // only vote on `Tasktodo` objects
        if (!$subject instanceof Tasktodo) {
            return false;
        }
        return true;
    }
    protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
    {
        $user = $token->getUser();
        if (!$user instanceof Usertodo) {
            // the user must be logged in; if not, deny access
            return false;
        }
        // $subject is a Tasktodo object
        /** @var Tasktodo $task */
        $task = $subject;
        switch ($attribute) {
            case self::DELETE:
                return $this->canDelete($task /* , $user */ );
        }
        throw new \LogicException('This code should not be reached!');
    }
    private function canDelete(Tasktodo $task /* , User $user */ )
    {
        // ON AUTORISE LA SUPPRESSION SI L'AUTEUR DE LA TÂCHE ÉQUIVAUT À L'UTILISATEUR CONNECTÉ
        // On vérifie : si l'utilisateur connecté est équivaut à l'auteur de la tâche
        if($this->security->getUser() === $task->getUsertodo()) {
            return true;
        } else {
            // On vérifie : si l'utilisateur connecté est différent de l'auteur de la tâche
            // Mais si l'utilisateur connecté a le rôle ADMIN, alors on autorise la suppression
            if($this->security->isGranted('ROLE_ADMIN')){
                return true;
            }
        }
    }
    
}