<?php
/*
* Disclaimer: This source code is protected by copyright law and by
* international conventions.
*
* Any reproduction or partial or total distribution of the source code, by any
* means whatsoever, is strictly forbidden.
*
* Anyone not complies with these provisions will be guilty of the offense of
* infringement and the penal sanctions provided for by law.
*
* © 2022 All rights reserved.
*/
namespace App\Security\Voter;
use App\Entity\Permission;
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 UserVoter
*
* @author Rémy P. <r.peyron@ingeno.eu>
* @package App\Security\Voter
*/
class GroupVoter extends Voter implements GroupVoterInterface
{
/**
* @var Security
*/
private $security;
public function __construct (Security $security)
{
$this->security = $security;
}
static function getAttributes (): array
{
return [self::SHOW, self::EDIT, self::DELETE, self::VIEW, self::CREATE];
}
protected function supports (string $attribute, $subject): bool
{
if (!in_array($attribute, self::getAttributes())) {
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 (!$user->isActive()) return false;
if ($this->security->isGranted(User::ROLE_SUPER_ADMIN)) return true;
/** @var Permission $permission */
foreach ($user->getUserGroup()->getPermissions()->toArray() as $permission) {
$match = $permission->getModule()->getName() === $subject;
if (!$match) continue;
switch ($attribute) {
case self::VIEW:
return $permission->getCanView();
case self::CREATE:
return $permission->getCanCreate();
case self::SHOW:
return $permission->getCanShow();
case self::EDIT:
return $permission->getCanEdit();
case self::DELETE:
return $permission->getCanDelete();
default:
return false;
}
}
throw new \LogicException('This code should not be reached!');
}
}