<?php
namespace App\Security\Voter;
use App\Entity\JobOffer;
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 JobOfferVoter extends Voter
{
public const EDIT = 'OFFER_EDIT';
public const VIEW = 'OFFER_VIEW';
public const CAN_SEE_CANDIDACIES = 'CAN_SEE_CANDIDACIES';
public function __construct(private Security $security)
{
}
protected function supports(string $attribute, mixed $subject): bool
{
// replace with your own logic
// https://symfony.com/doc/current/security/voters.html
return in_array($attribute, [
self::EDIT,
self::VIEW,
self::CAN_SEE_CANDIDACIES,
])
&& $subject instanceof \App\Entity\JobOffer;
}
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return false;
}
if($this->security->isGranted('ROLE_MANAGER')) {
return true;
}
// ... (check conditions and return true to grant permission) ...
switch ($attribute) {
case self::EDIT:
return $this->canEdit($subject, $user);
case self::VIEW:
return $this->canView();
case self::CAN_SEE_CANDIDACIES:
return $this->canSeeCandidacies($subject, $user);
}
return false;
}
private function canView(): bool
{
return true;
}
private function canEdit(JobOffer $jobOffer, UserInterface $user)
{
if($jobOffer->getCandidacies()->count() > 0) {
return false;
}
if($jobOffer->getCreatedBy() === $user) {
return true;
}
$userCenters = $user->getCentre();
return $userCenters->contains($jobOffer->getCenter());
}
private function canSeeCandidacies(JobOffer $jobOffer, UserInterface $user): bool
{
if($jobOffer->getCreatedBy() === $user) {
return true;
}
$userCenters = $user->getCentre();
return $userCenters->contains($jobOffer->getCenter());
}
}