<?php
namespace App\Security;
use App\Entity\Employee;
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\Security;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
class EmployeeVoter extends Voter
{
// these strings are just invented: you can use anything
const VIEW = 'view';
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
/**
* @inheritDoc
*/
protected function supports(string $attribute, $subject)
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::VIEW]))
return false;
// only vote on `Post` objects
if (!$subject instanceof Employee)
return false;
return true;
}
/**
* @inheritDoc
*/
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token)
{
if ($this->security->isGranted('ROLE_SUPER_ADMIN'))
return true;
if ($this->security->isGranted('ROLE_ADMIN'))
return true;
/** @var User $user */
$user = $token->getUser();
if (!$user instanceof User)
return false;
// you know $subject is a Post object, thanks to `supports()`
/** @var Employee $employee */
$employee = $subject;
switch ($attribute) {
case self::VIEW:
$userVisiblitaUnitaOrganizzativa = $user->getVisibilitaUnitaOrganizzativa();
$employeeAttualeUnitaOrganizzativa = $employee->getAttualeUnitaOrganizzativa();
if (str_contains($employeeAttualeUnitaOrganizzativa, $userVisiblitaUnitaOrganizzativa))
return true;
return false;
}
throw new \LogicException('This code should not be reached!');
}
}