<?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\ShopModulesBundle\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 ShopModuleVoter extends Voter
{
public const ACCESS = 'SHOP_MODULES_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__SHOP_MODULES__ADMIN')) {
return true;
}
if (!$this->security->isGranted('ROLE__SHOP_MODULES__SMALL_ADMIN')) {
return false;
}
if (method_exists($subject, 'getCreatedBy') && $subject->getCreatedBy()) {
return $user === $subject->getCreatedBy();
} else {
return true;
}
}
}