Created
March 15, 2013 19:11
-
-
Save vjnrv/5172283 to your computer and use it in GitHub Desktop.
Exposes Symfony2 Security Context
This file contains 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 | |
use ZZZ\Component\Security; | |
if (Security::factory()->isGranted('ROLE_ADMIN')) { | |
// ... | |
} |
This file contains 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 | |
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); | |
} | |
} |
This file contains 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
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