<?php
namespace App\Security\Voter;
use App\Entity\User;
use App\Utils\Commons;
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 ChangePlanVoter extends Voter
{
const CHANGE_PLAN = 'CHANGE_PLAN';
private $commons;
private $security;
public function __construct(Security $security, Commons $commons)
{
$this->security = $security;
$this->commons = $commons;
}
/**
* @param string $attribute
* @param mixed $subject
* @return bool
*/
protected function supports($attribute, $subject): bool
{
if (!in_array($attribute,
[self::CHANGE_PLAN]
)) {
return false;
}
return true;
}
/**
* @param string $attribute
* @param mixed $subject
* @param TokenInterface $token
* @return bool
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
if ($this->security->isGranted('ROLE_ADMIN')) {
return true;
}
/** @var User $user */
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return false;
}
switch ($attribute) {
case 'CHANGE_PLAN':
return $this->canChangePlan($user);
}
return false;
}
/** Return True if have Buy Permission else return false */
private function canChangePlan(User $user): bool
{
$permissions = $this->commons->getUserPermissions($user);
if ($permissions) {
if (array_key_exists('changePlan', $permissions)) {
if (in_array('Change', $permissions['changePlan'])) {
return true;
}
}
}
return false;
}
}