<?php
namespace App\Security\Voter;
use App\Entity\Task;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
class UserVoter extends Voter
{
const USER_CAN_EDIT_TASK = "USER_CAN_EDIT_TASK";
/**
* @var Security
*/
private $security;
/**
* @param Security $security
*/
public function __construct(Security $security)
{
$this->security = $security;
}
/**
* @param string $attribute
* @param $subject
* @return bool
*/
protected function supports(string $attribute, $subject): bool
{
if(!$subject instanceof Task) {
return false;
}
if (!in_array($attribute, [self::USER_CAN_EDIT_TASK])) {
return false;
}
return true;
}
/**
* @param string $attribute
* @param $subject
* @param TokenInterface $token
* @return bool
*/
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return false;
}
switch ($attribute) {
case self::USER_CAN_EDIT_TASK:
return $this->canEditTask($user, $subject);
break;
}
return false;
}
/**
* @param User|UserInterface $user
* @param Task $task
* @return bool
*/
private function canEditTask(User $user, Task $task): bool
{
if ($this->security->isGranted("ROLE_ADMIN")) {
return true;
}
foreach($task->getUsers() as $taskUser) {
if ($user === $taskUser) {
return true;
}
}
return false;
}
}