<?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 ProjectListVoter
*
* @package App\Security\Voter
* @author Lukasz Krakowiak <lukasz94krakowiak@gmail.com>
*/
class ProjectListVoter extends Voter
{
const CAN_SHOW_PROJECT_LIST = "CAN_SHOW_LIST";
/**
* @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) {
return true;
}
if(!$subject instanceof Project) {
return false;
}
if (!in_array($attribute, [self::CAN_SHOW_PROJECT_LIST])) {
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_LIST:
return $this->canShowProjectList($user, $subject);
}
return false;
}
/**
* @param User|UserInterface $user
* @param Project $project
*
* @return bool
*/
private function canShowProjectList(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")) {
return true;
}
if(in_array($user->getId(), [211,365,366,364])) {
return true;
}
return false;
}
}