PHP code example of sebk / swoft-voter
1. Go to this page and download the library: Download sebk/swoft-voter library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
sebk / swoft-voter example snippets
return [
'path' => [
__DIR__ . '/../app/Security/Voter',
__DIR__ . '/../app/Security/ModelVoter',
],
];
namespace Sebk\SwoftVoter\VoterManager;
interface VoterInterface
{
// Responses
const ACCESS_GRANTED = 1;
const ACCESS_ABSTAIN = 0;
const ACCESS_DENIED = -1;
// Attributes
const ATTRIBUTE_READ = "READ";
const ATTRIBUTE_WRITE = "WRITE";
const ATTRIBUTE_UPDATE = "UPDATE";
const ATTRIBUTE_DELETE = "DELETE";
/**
* Is voter sopported by vote ?
* @param $subject
* @param $attibutes
* @return bool
*/
function support($subject, array $attibutes);
/**
* Vote
* @param $user
* @param $subject
* @param array $attributes
* @return int
*/
function voteOnAttribute($user, $subject, array $attributes);
}
namespace App\Security\Voter;
use App\Http\Controller\Abstract\TokenSecuredController;
use Sebk\SwoftVoter\VoterManager\VoterInterface;
class ControllerVoter implements VoterInterface
{
/**
* Is voter sopported by vote ?
* @param \stdClass $subject
* @param array $attibutes
* @return bool
*/
public function support($subject, array $attibutes)
{
$result = false;
// Check attributes
foreach ($attibutes as $attibute) {
switch ($attibute) {
case VoterInterface::ATTRIBUTE_READ:
case VoterInterface::ATTRIBUTE_UPDATE:
$result = true;
}
}
// If attributes checked, check subject
if ($result) {
if (!$subject instanceof TokenSecuredController) {
$result = false;
}
}
return $result;
}
/**
* Vote
* @param $user
* @param $subject
* @param array $attributes
* @return int
*/
public function voteOnAttribute($user, $subject, array $attributes)
{
if ($user->getLogin() == "KS" && in_array(VoterInterface::ATTRIBUTE_READ, $attributes)) {
return VoterInterface::ACCESS_GRANTED;
}
return VoterInterface::ACCESS_DENIED;
}
}
use Sebk\SwoftVoter\VoterManager\VoterInterface;
$subject = $this->objectToVote;
$attributes = [
VoterInterface::ATTRIBUTE_READ,
VoterInterface::ATTRIBUTE_WRITE,
];
$voteResult = $this->voterManager->vote($this->getUser(), $subject, $attributes);
if ($voteResult != VoterInterface::ACCESS_GRANTED) {
// And deny access if not granted
throw new AccessDeniedException("Forbidden access");
}