<?php
namespace App\Security;
use App\Entity\Assignment;
use App\Modules\Chat\Entity\Project\Board;
use App\Entity\User;
use App\Repository\AssignmentRepository;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class ProjectBoardChatVoter extends Voter
{
const ATTRIBUTES = [self::ATTR_ASSIGNED, self::ATTR_WRITE];
const ATTR_ASSIGNED = 'CHAT_ASSIGNED';
const ATTR_WRITE = 'CHAT_WRITE';
/**
* @var AssignmentRepository
*/
private $assignmentRepository;
public function __construct(AssignmentRepository $assignmentRepository)
{
$this->assignmentRepository = $assignmentRepository;
}
/**
* Determines if the attribute and subject are supported by this voter.
*
* @param string $attribute An attribute
* @param mixed $subject The subject to secure, e.g. an object the user wants to access or any other PHP type
*
* @return bool True if the attribute and subject are supported, false otherwise
*/
protected function supports($attribute, $subject)
{
return $subject instanceof Board && in_array($attribute, static::ATTRIBUTES);
}
/**
* Perform a single access check operation on a given attribute, subject and token.
* It is safe to assume that $attribute and $subject already passed the "supports()" method check.
*
* @param string $attribute
* @param mixed $subject
* @param TokenInterface $token
*
* @return bool
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
/**
* @var Board $subject
* @var User $user
*/
$user = $token->getUser();
switch ($attribute) {
case static::ATTR_ASSIGNED:
$vote = ($user === $subject->getClient() or $this->isAssigned($subject, $user));
break;
case static::ATTR_WRITE:
// $vote = ($user === $subject->getClient());
$vote = ($user === $subject->getClient() or $this->isAssigned($subject, $user));
break;
default:
$vote = false;
}
return $vote;
}
/**
* @param Board $chat
* @param User $user
*
* @return bool
*/
private function isAssigned(Board $chat, User $user): bool
{
$assignment = $this->assignmentRepository->findOneBy(
[
'task' => $chat->getProject()
->getTasks()
->toArray(),
'user' => $user,
'status' => [
Assignment::STATUS_COMPLETED,
Assignment::STATUS_PROGRESS,
Assignment::STATUS_REQUEST,
Assignment::STATUS_REJECTED,
Assignment::STATUS_REVIEW,
],
]
);
return !empty($assignment);
}
}