<?php
namespace App\Profile\Security\Voter;
use App\Horse\Service\HorseService;
use App\Profile\Model\Profile;
use App\Profile\Model\ProfileRoles;
use Pimcore\Model\DataObject\Horse;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class HorseVoter extends Voter
{
public const CREATE = 'profile.horse.create';
public function __construct(protected Security $security, protected HorseService $horseService)
{
}
protected function supports(string $attribute, $subject = null): bool
{
if (!in_array($attribute, [self::CREATE])) {
return false;
}
return true;
}
protected function voteOnAttribute(string $attribute, $subject = null, TokenInterface $token = null): bool
{
if (!$token) {
throw new \Exception('TokenInterface $token is not injected');
}
$user = $token->getUser();
if (!$user instanceof Profile) {
return false;
}
switch ($attribute) {
case self::CREATE:
return $this->canCreate($user);
}
throw new \LogicException(sprintf('Attribute `%s` not supported by horse object', $attribute));
}
protected function canCreate(Profile $profile): bool
{
// Only Horse Club Members can create Horses
if (!$this->security->isGranted(ProfileRoles::ROLE_CLUB_HORSE)) {
return false;
}
return true;
}
}