<?php
namespace App\Http\Customer\Voter;
use App\Domain\Project\Entity\Annotation;
use App\Domain\User\Entity\User;
use JetBrains\PhpStorm\Pure;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
class AnnotationVoter extends Voter
{
const ADD = 'ADD_ANNOTATION';
const EDIT = 'EDIT_ANNOTATION';
const REMOVE = 'REMOVE_ANNOTATION';
const VALIDATE = 'VALIDATE_ANNOTATION';
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
if(!($subject instanceof Annotation)) return false;
/** @var User $user */
$user = $token->getUser();
return match ($attribute) {
self::ADD => $this->canAddAnnotation($subject, $user),
self::EDIT, self::VALIDATE, self::REMOVE => $this->canEditAnnotation($subject, $user),
default => false
};
}
private function canAddAnnotation(Annotation $annotation, User $user): bool
{
return $annotation->getProject()->getCompany() === $user->getCompany();
}
private function canEditAnnotation(Annotation $annotation, User $user): bool
{
return $annotation->getAuthor() === $user || in_array('ROLE_ADMIN', $user->getRoles());
}
protected function supports(string $attribute, mixed $subject): bool
{
return in_array($attribute, [self::ADD, self::EDIT, self::VALIDATE, self::REMOVE]);
}
}