Skip to content

Instantly share code, notes, and snippets.

@merk
Created March 23, 2014 22:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save merk/9730960 to your computer and use it in GitHub Desktop.
Save merk/9730960 to your computer and use it in GitHub Desktop.
Example Voter
<?php
/**
* This file is part of the X project.
*
* (c) Infinite Networks Pty Ltd <http://www.infinite.net.au>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace X\AppBundle\Security\Voter;
use Entity\User;
use JMS\DiExtraBundle\Annotation as DI;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
/**
* Tests is a plan is active or not.
*
* @DI\Service("x_app.security.plan_active_voter")
* @DI\Tag("security.voter")
*/
class PlanActiveVoter implements VoterInterface
{
const ATTRIBUTE_ACTIVE = 'PLAN_ACTIVE';
public function supportsAttribute($attribute)
{
return static::ATTRIBUTE_ACTIVE === $attribute;
}
public function supportsClass($class)
{
return $class instanceof User or $class instanceof Request;
}
/**
* @param TokenInterface $token
* @param \Entity\User $user
* @param array $attributes
* @return int
*/
public function vote(TokenInterface $token, $user, array $attributes)
{
if (!$this->supportsClass($user)) {
return VoterInterface::ACCESS_ABSTAIN;
}
if (!$user instanceof User) {
$user = $token->getUser();
if (!$user instanceof User) {
return VoterInterface::ACCESS_ABSTAIN;
}
}
foreach ($attributes as $attribute) {
if (!$this->supportsAttribute($attribute)) {
continue;
}
return $user->isServiceActive() ?
VoterInterface::ACCESS_GRANTED :
VoterInterface::ACCESS_DENIED;
}
return VoterInterface::ACCESS_ABSTAIN;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment