<?php
namespace App\Security\Voter;
use App\Entity\User;
use App\Entity\UserProject;
use App\Entity\UserWorkroom;
use App\Entity\Workroom;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* Class WorkroomVoter.
*/
class WorkroomVoter extends Voter
{
// Permissions.
const WORKROOM_VIEW = 'workroom_view';
// Full list.
const PERMISSIONS = [
self::WORKROOM_VIEW,
];
private EntityManagerInterface $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
/**
* {@inheritdoc}
*/
protected function supports($attribute, $subject): bool
{
return in_array($attribute, self::PERMISSIONS) && ($subject instanceof Workroom);
}
/**
* {@inheritdoc}
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
/** @var User $user */
$user = $token->getUser();
// If the user is anonymous, do not grant access.
if (!$user instanceof UserInterface) {
return false;
}
// Check conditions and provide access bases on it.
switch ($attribute) {
case self::WORKROOM_VIEW:
return $this->canView($subject, $user);
default:
break;
}
return false;
}
/**
* Check that the user can view the workroom
* If the user has UserWorkroom entity we provide access, otherwise - not !!!
*/
public function canView(Workroom $workroom, User $user): bool
{
$userProject = $this->em->getRepository(UserProject::class)->findBy([
'project' => $workroom->getProject()->getId(),
'user' => $user->getId()
]);
return !empty($userProject);
}
}