SecurityExtension.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Bridge\Twig\Extension;
  11. use Symfony\Component\Security\Acl\Voter\FieldVote;
  12. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  13. use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
  14. use Twig\Extension\AbstractExtension;
  15. use Twig\TwigFunction;
  16. /**
  17. * SecurityExtension exposes security context features.
  18. *
  19. * @author Fabien Potencier <fabien@symfony.com>
  20. */
  21. class SecurityExtension extends AbstractExtension
  22. {
  23. private $securityChecker;
  24. public function __construct(AuthorizationCheckerInterface $securityChecker = null)
  25. {
  26. $this->securityChecker = $securityChecker;
  27. }
  28. public function isGranted($role, $object = null, $field = null)
  29. {
  30. if (null === $this->securityChecker) {
  31. return false;
  32. }
  33. if (null !== $field) {
  34. $object = new FieldVote($object, $field);
  35. }
  36. try {
  37. return $this->securityChecker->isGranted($role, $object);
  38. } catch (AuthenticationCredentialsNotFoundException $e) {
  39. return false;
  40. }
  41. }
  42. /**
  43. * {@inheritdoc}
  44. */
  45. public function getFunctions()
  46. {
  47. return array(
  48. new TwigFunction('is_granted', array($this, 'isGranted')),
  49. );
  50. }
  51. /**
  52. * {@inheritdoc}
  53. */
  54. public function getName()
  55. {
  56. return 'security';
  57. }
  58. }