<?php
namespace App\Security\Voter;
use App\Constant\Features;
use App\Entity\User;
use App\Service\Api\Subscription\FeatureService;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class FeatureVoter extends Voter
{
private $featureService;
public function __construct(FeatureService $featureService)
{
$this->featureService = $featureService;
}
protected function supports(string $attribute, $subject): bool
{
// Check if the attribute is a feature name or role
return (Features::findByName($attribute) || Features::findByRole($attribute)) !== null;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
// Get feature data
$feature = Features::findByName($attribute) ?? Features::findByRole($attribute);
if (!$feature) {
return false;
}
// First check if user has the required role
$requiredRole = $feature['role'];
if (!in_array($requiredRole, $user->getRoles())) {
return false;
}
// Then check feature access and limits using FeatureService
return $this->featureService->hasAccess($user, $attribute);
}
}