<?php
namespace App\Modules\User\Security;
use App\Modules\User\Entity\Partner;
use App\Modules\User\Entity\User;
use App\Modules\User\Entity\UserContract;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class PartnerVoter extends Voter
{
const CREATE_PARTNER = 'create_partner';
const UPDATE_PARTNER = 'update_partner';
const DELETE_PARTNER = 'delete_partner';
static $access = [
self::CREATE_PARTNER,
self::UPDATE_PARTNER,
self::DELETE_PARTNER,
];
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
/**
* Determines if the attribute and subject are supported by this voter.
*
* @param string $attribute An attribute
* @param mixed $subject The subject to secure, e.g. an object the user wants to access or any other PHP type
*
* @return bool True if the attribute and subject are supported, false otherwise
*/
protected function supports($attribute, $subject)
{
if (!in_array($attribute, self::$access)) {
return false;
}
return true;
}
/**
* Perform a single access check operation on a given attribute, subject and token.
* It is safe to assume that $attribute and $subject already passed the "supports()" method check.
*
* @param string $attribute
* @param mixed $subject
*
* @param TokenInterface $token
*
* @return bool
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$loginedUser = $token->getUser();
if (!$loginedUser instanceof UserContract) {
// the user must be logged in; if not, deny access
return false;
}
$partner = $subject;
switch ($attribute) {
case self::CREATE_PARTNER:
return $this->canCreate();
case self::UPDATE_PARTNER:
return $this->canUpdate($partner, $loginedUser);
case self::DELETE_PARTNER:
return $this->canDelete();
}
}
private function canCreate()
{
if ($this->security->isGranted('ROLE_ADMIN')) {
return true;
}
return false;
}
private function canUpdate(Partner $partner, User $loggedInUser)
{
if ($this->security->isGranted('ROLE_ADMIN') ||
$partner->hasAdministrator($loggedInUser)
) {
return true;
}
return false;
}
private function canDelete()
{
if ($this->security->isGranted('ROLE_ADMIN')) {
return true;
}
return false;
}
}