Created
March 23, 2014 22:40
-
-
Save merk/9730960 to your computer and use it in GitHub Desktop.
Example Voter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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