<?php 
 
namespace App\Security\Voter; 
 
use App\Entity\User; 
use App\Utils\Commons; 
use LogicException; 
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\UserInterface; 
 
class BackendSuperUserVoter extends Voter 
{ 
    /** 
     * @var Security 
     */ 
    private $security; 
    /** 
     * @var Commons 
     */ 
    private $commons; 
    /** 
     * @var array 
     */ 
    private $permissions; 
 
    /** 
     * BackendSuperUserVoter constructor. 
     * @param Security $security 
     * @param Commons $commons 
     */ 
    public function __construct(Security $security, Commons $commons) 
    { 
        $this->security = $security; 
        $this->commons = $commons; 
        $this->permissions = []; 
 
    } 
 
    /** 
     * @param string $attribute 
     * @param mixed $subject 
     * @return bool 
     */ 
    protected function supports($attribute, $subject): bool 
    { 
        if (!in_array($attribute, 
            ['SUPER_USER_RIGHTS'] 
        )) { 
            return false; 
        } 
        return true; 
    } 
 
    /** 
     * @param string $attribute 
     * @param mixed $subject 
     * @param TokenInterface $token 
     * @return bool 
     */ 
    protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool 
    { 
 
        /** @var User $user */ 
        $user = $token->getUser(); 
        // if the user is anonymous, do not grant access 
        if (!$user instanceof UserInterface) { 
            return false; 
        } 
        $this->permissions = $this->commons->getBackendPermissions($user); 
 
        switch ($attribute) { 
            case 'SUPER_USER_RIGHTS': 
                return $this->canHave(); 
        } 
 
        throw new  LogicException('Invalid attribute: ' . $attribute); 
    } 
 
    /** 
     * Return True if have Super View Permission else return false 
     * @return bool 
     */ 
    private function canHave(): bool 
    { 
        if (array_key_exists('superUser', $this->permissions)) { 
            if (in_array('Yes', $this->permissions['superUser'])) { 
                return true; 
            } 
        } 
 
        return false; 
 
    } 
}