<?php
namespace App\Security\Voter;
use App\Entity\Absence;
use App\Entity\Project;
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 ProjectVoter extends Voter
{
const CAN_SHOW_PROJECT = "CAN_SHOW_PROJECT";
/**
* @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 Project) {
return false;
}
if (!in_array($attribute, [self::CAN_SHOW_PROJECT])) {
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_SHOW_PROJECT:
return $this->canShowProject($user, $subject);
}
return false;
}
/**
* @param User|UserInterface $user
* @param Project $project
*
* @return bool
*/
private function canShowProject(User $user, Project $project): bool
{
return $this->isAdminOrOwner($user, $project);
}
/**
* @param User $user
* @param Project $project
*
* @return bool
*/
private function isAdminOrOwner(User $user, Project $project): bool
{
if ($this->security->isGranted("ROLE_ADMIN") || $this->security->isGranted("ROLE_EMPLOYER")) {
return true;
}
if($project->getClient()->contains($user)) {
return true;
}
return false;
}
}