<?php
/**
* @author Thomas HERISSON (contact@scaledev.fr)
* @copyright 2021 - ScaleDEV SAS, 12 RUE CHARLES MORET, 10120 ST ANDRE LES VERGERS
* @license commercial
*/
declare(strict_types=1);
namespace Bluue\SuppliersBundle\Security;
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;
class SuppliersVoter extends Voter
{
public const ACCESS = 'SUPPLIERS_ACCESS';
/**
* @var Security
*/
private Security $security;
/**
* @param Security $security
*/
public function __construct(Security $security)
{
$this->security = $security;
}
/**
* @param string $attribute
* @param mixed $subject
* @return bool
*/
protected function supports(string $attribute, $subject): bool
{
if ($attribute != self::ACCESS) {
return false;
}
if (!is_object($subject)) {
return false;
}
return true;
}
/**
* @param string $attribute
* @param mixed $subject
* @param TokenInterface $token
* @return bool
*/
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
if ($this->security->isGranted('ROLE__SUPPLIERS__ADMIN')) {
return true;
}
if (!$this->security->isGranted('ROLE__SUPPLIERS__SMALL_ADMIN')) {
return false;
}
if (method_exists($subject, 'getCreatedBy') && $subject->getCreatedBy()) {
return $user->getId() == $subject->getCreatedBy()->getId();
} else {
return true;
}
}
}