<?php
namespace App\Security\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use App\Entity\Accessmeister\User;
use App\Entity\Taskmeister\Task;
class TaskVoter extends Voter
{
private const VIEW = 'view';
private const EDIT = 'edit';
protected function supports(string $attribute, $subject): bool
{
return in_array($attribute, [self::VIEW, self::EDIT])
&& $subject instanceof Task;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
/**
* @var Task $subject
*/
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof User) {
return false;
}
$task = $subject;
switch ($attribute) {
case self::VIEW:
return $this->canView($task, $user);
case self::EDIT:
return $this->canEdit($task, $user);
}
return false;
}
// TODO: This doesn't account for subcompanies and other complexities.
// Go through main.php 'case "task_edit":' and 'case "task_view"'
// and create correct voting logic here.
private function canView(Task $task, User $user): bool
{
// If they can edit, they can view
if ($this->canEdit($task, $user)) {
return true;
}
return $user->getCompany() === $subject->getCompany();
}
private function canEdit(Task $task, User $user): bool
{
if (
$user === $task->getAssignedToUser()
|| $user === $task->getAssignedByUser()
) {
return true;
}
return false;
}
}