<?php
/*
* Created on Fri Dec 02 2022
*
* DAVID-OLIVIER DESCOMBES
*
* @licence
* You may not sell, sub-license, rent or lease any portion of the Software or Documentation to anyone.
*
* Copyright (c) 2022 dodarchitecte.com (https://dodarchitecte.com)
*
* Developed by developpeur-informatique.ma (https://www.developpeur-informatique.ma)
*/
namespace App\Security\Voter;
use App\Entity\Project\Project;
use App\Handler\Project\UserAccessProjectHandler;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Security;
class ProjectVoter extends Voter
{
public const EDIT = 'POST_EDIT';
public const VIEW = 'POST_VIEW';
public function __construct(
private Security $security,
private UserAccessProjectHandler $userAccessProjectHandler
)
{
}
protected function supports(string $attribute, $subject): bool
{
return in_array($attribute, [self::EDIT, self::VIEW])
&& $subject instanceof Project;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
// ... (check conditions and return true to grant permission) ...
switch ($attribute) {
case self::EDIT:
// logic to determine if the user can EDIT
// return true or false
return true;
break;
case self::VIEW:
return
$this->canView($user, $subject);
true;
break;
}
return false;
}
//check if the user can view the specific project
private function canView($user, $subject): bool
{
$own = (($user->getEnterprise() ?? null) == ($subject->getEnterprise() ?? null));
$discarded = $subject->isDiscarded();
$ended = $subject->getStatus() == 'Terminé';
return ($this->userAccessProjectHandler->hasAccessToProject($subject)) || ($own && !$discarded && !$ended);
}
}