<?php
namespace App\Security\Voter;
use Oz\ApiNvl\Model\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
/**
*
*/
class DatasourceVoter extends Voter
{
/**
* 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
*/
protected function supports(string $attribute, $subject): bool
{
return in_array($attribute, ['CAN_READ', 'CAN_WRITE', 'CAN_VALIDATE']) && is_string($subject);
}
/**
* 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(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
switch ($attribute) {
case 'CAN_READ':
return $this->canRead($user, $subject);
case 'CAN_WRITE':
return $this->canWrite($user, $subject);
case 'CAN_VALIDATE':
return $this->canValidate($user, $subject);
}
return false;
}
/**
* @param User $user
* @param string $subject
*
* @return bool
*/
private function canRead(User $user, string $subject): bool
{
// return false;
if (!$this->permissionExists($user, $subject)) {
return false;
}
$permission = $user->getPermissions()[$subject];
return $permission->isRead();
}
/**
* @param User $user
* @param string $subject
*
* @return bool
*/
private function canWrite(User $user, string $subject): bool
{
if (!$this->permissionExists($user, $subject)) {
return false;
}
$permission = $user->getPermissions()[$subject];
return $permission->isWrite();
}
/**
* @param User $user
* @param string $subject
*
* @return bool
*/
private function canValidate(User $user, string $subject): bool
{
if (!$this->permissionExists($user, $subject)) {
return false;
}
$permission = $user->getPermissions()[$subject];
return $permission->isValidate();
}
/**
* @param User $user
* @param string $subject
*
* @return bool
*/
private function permissionExists(User $user, string $subject): bool
{
return array_key_exists($subject, $user->getPermissions());
}
}