<?php
namespace App\Security\Voter;
use App\Entity\Company;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Security;
class CompanyVoter extends Voter
{
const VIEW ="ver";
const EDIT ="editar";
const DELETE = "eliminar";
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports($attribute, $subject)
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::VIEW, self::EDIT])) {
return false;
}
// only vote on `Company` objects
if (!$subject instanceof Company) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
// ROLE_ADMIN can do anything! The power!
if ($this->security->isGranted('ROLE_ADMIN')) {
return true;
}
// ... (check conditions and return true to grant permission) ...
switch ($attribute) {
case self::VIEW:
return $this->canView($subject, $user);
case self::EDIT:
return $this->canEdit($subject, $user);
case self::DELETE:
return $this->canDelete($subject, $user);
break;
}
return false;
}
private function canView(Company $company, User $user)
{
return $user === $company->getUser();
}
private function canEdit(Company $company, User $user)
{
return $user === $company->getUser();
}
private function canDelete(Company $company, User $user)
{
return $user === $company->getUser();
}
}