<?php
namespace App\Security;
use App\Entity\AppActions;
use App\Entity\AppUser;
use App\Entity\Employee;
use App\Entity\RoleAction;
use App\Entity\UserRole;
use App\Entity\Vacation;
use App\Utils\Consts;
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\Security;
use Symfony\Component\Security\Core\User\UserInterface;
class VacationRouteVoter extends Voter
{
public const CREATE = 'CREATE';
public const VIEW = 'VIEW';
public const EDIT = 'EDIT';
protected function supports(string $attribute, $subject): bool
{
// replace with your own logic
// https://symfony.com/doc/current/security/voters.html
return in_array($attribute, [self::CREATE, self::VIEW, self::EDIT])
&& $subject instanceof \App\Entity\Vacation;
}
private $entityManager;
private $security;
public function __construct(EntityManagerInterface $entityManager,Security $security)
{
$this->entityManager = $entityManager;
$this->security = $security;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof AppUser) {
// the user must be logged in; if not, deny access
return false;
}
// you know $subject is a Post object, thanks to `supports()`
/** @var Vacation $vacation */
$vacation = $subject;
switch ($attribute) {
case self::VIEW:
return $this->canView($vacation, $user);
case self::EDIT:
return $this->canEdit($vacation, $user);
case self::CREATE:
return $this->canCreate($vacation, $user);
}
return false;
}
private function canView(Vacation $vacation, AppUser $user): bool
{
// if they can edit, they can view
return $this->entityManager->getRepository(RoleAction::class)->
hasRoleActionWithReadPermission($user,'Vacation');
}
private function canEdit(Vacation $vacation, AppUser $user): bool
{
// this assumes that the Vacation object has a `getOwner()` method
return $this->entityManager->getRepository(RoleAction::class)->
hasRoleActionWithEditPermission($user,'Vacation');
}
private function canCreate(Vacation $vacation, AppUser $user): bool
{
// this assumes that the Vacation object has a `getOwner()` method
return $this->entityManager->getRepository(RoleAction::class)->
hasRoleActionWithCreatePermission($user,'Vacation');
}
}