<?php
namespace App\Security;
use App\Entity\User;
use App\Entity\Company;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
class CompanyVoter extends Voter
{
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
// these strings are just invented: you can use anything
const VIEW = 'view';
const EDIT = 'edit';
const NEW = 'create';
protected function supports(string $attribute, $subject): bool
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::VIEW, self::EDIT, self::NEW])) {
return false;
}
// only vote on `Post` objects
if (!$subject instanceof Company) {
return false;
}
return true;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
// the user must be logged in; if not, deny access
return false;
}
if ($this->security->isGranted('ROLE_SUPER_ADMIN')) {
return true;
}
if ($this->security->isGranted('KOBEN_1_SUPER ADMIN')) {
return true;
}
// you know $subject is a Post object, thanks to `supports()`
/** @var Company $post */
$company = $subject;
switch ($attribute) {
case self::VIEW:
return $this->canView($company, $user);
case self::EDIT:
return $this->canEdit($company, $user);
case self::NEW:
return $this->canCreate($user);
}
throw new \LogicException('This code should not be reached!');
}
private function canView(Company $company, User $user): bool
{
// if they can edit, they can view
if ($this->canEdit($company, $user)) {
return true;
}
$userCompaniesRet = $user->getCompanies();
$userCompanies = [];
foreach ($userCompaniesRet as $foo){
$userCompanies[] = $foo->getId();
}
return in_array($company->getId(), $userCompanies);
}
private function canEdit(Company $company, User $user): bool
{
if ($this->security->isGranted('KOBEN_2_MANAGEMENT')) {
return true;
}
$userCompaniesRet = $user->getCompanies();
$userCompanies = [];
foreach ($userCompaniesRet as $foo){
$userCompanies[] = $foo->getId();
}
return in_array($company->getId(), $userCompanies);
}
private function canCreate(User $user): bool
{
if ($this->security->isGranted('KOBEN_2_MANAGEMENT')) {
return true;
}
return false;
}
}