<?php
namespace App\Security\Voter;
use App\Entity\Company;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class CompanyVoter extends Voter
{
protected function supports(string $attribute, $subject): bool
{
// replace with your own logic
// https://symfony.com/doc/current/security/voters.html
return in_array($attribute, ['COMPANY_UPLOAD', 'COMPANY_UPDATE'], true) && $subject instanceof Company;
}
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;
}
/** @var Company $company */
$company = $subject;
// ... (check conditions and return true to grant permission) ...
switch ($attribute) {
case 'COMPANY_UPLOAD':
// logic to determine if the user can EDIT
// return true or false
return ($company->getUser() === $user)
|| in_array('ROLE_ADMIN', $user->getRoles(), true);
case 'COMPANY_UPDATE':
// logic to determine if the user can VIEW
// return true or false
return $company->getUser() === $user;
}
return false;
}
}