<?php
namespace App\Security\Voter;
use App\Entity\Absence;
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 AbsenceVoter
*
* @package App\Security\Voter
* @author Lukasz Krakowiak <lukasz94krakowiak@gmail.com>
*/
class AbsenceVoter extends Voter
{
const CAN_EDIT_ABSENCE = "CAN_EDIT_ABSENCE";
const CAN_REMOVE_ABSENCE = "CAN_REMOVE_ABSENCE";
/**
* @var Security
*/
private Security $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 Absence) {
return false;
}
if (!in_array($attribute, [self::CAN_EDIT_ABSENCE, self::CAN_REMOVE_ABSENCE])) {
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::CAN_EDIT_ABSENCE:
return $this->canEditAbsence($user, $subject);
case self::CAN_REMOVE_ABSENCE:
return $this->canRemoveAbsence($user, $subject);
}
return false;
}
/**
* @param User|UserInterface $user
* @param Absence $absence
* @return bool
*/
private function canEditAbsence(User $user, Absence $absence): bool
{
return $this->isAdminOrOwner($user, $absence);
}
/**
* @param User|UserInterface $user
* @param Absence $absence
* @return bool
*/
private function canRemoveAbsence(User $user, Absence $absence): bool
{
return $this->isAdminOrOwner($user, $absence);
}
/**
* @param User $user
* @param Absence $absence
* @return bool
*/
private function isAdminOrOwner(User $user, Absence $absence): bool
{
if ($this->security->isGranted("ROLE_ADMIN")) {
return true;
}
if($absence->getUser() === $user) {
return true;
}
return false;
}
}