Skip to content

Instantly share code, notes, and snippets.

@vjnrv
Created March 15, 2013 19:11
Show Gist options
  • Save vjnrv/5172283 to your computer and use it in GitHub Desktop.
Save vjnrv/5172283 to your computer and use it in GitHub Desktop.
Exposes Symfony2 Security Context
<?php
use ZZZ\Component\Security;
if (Security::factory()->isGranted('ROLE_ADMIN')) {
// ...
}
<?php
namespace ZZZ\Component;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
/**
* Classe que expõe o contexto de segurança para uso fora de Controllers
*/
class Security
{
/**
* @var SecurityContextInterface
*/
protected static $context;
/**
* Factory Method
*
* @return Security
*/
public static function factory()
{
return new static();
}
/**
* Constructor
*
* @throws \LogicException quando o contexto de segurança não está iniciado
*
* @param SecurityContextInterface $context
*/
public function __construct(SecurityContextInterface $context = null)
{
if (static::$context === null) {
static::$context = $context;
}
if ( ! static::$context) {
throw new \LogicException('Security Context is not initialized.');
}
}
/**
* Retorna o Token de Autenticação
*
* @return UsernamePasswordToken
*/
public function getToken()
{
return static::$context->getToken();
}
/**
* Retorna o Usuário logado
*
* @return User
*/
public function getUser()
{
return $this->getToken()->getUser();
}
/**
* Checa permissão no Token atual
*
* @param mixed $attributes
* @param mixed|null $object
* @return Boolean
*/
public function isGranted($attributes, $object = null)
{
return static::$context->isGranted($attributes, $object);
}
}
services:
zzz.security:
class: ZZZ\Component\Security
arguments: [@security.context]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment