vendor/symfony/twig-bridge/Extension/SecurityExtension.php line 41

Open in your IDE?
  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 Symfony\Component\Security\Http\Impersonate\ImpersonateUrlGenerator;
  15. use Twig\Extension\AbstractExtension;
  16. use Twig\TwigFunction;
  17. /**
  18.  * SecurityExtension exposes security context features.
  19.  *
  20.  * @author Fabien Potencier <fabien@symfony.com>
  21.  */
  22. final class SecurityExtension extends AbstractExtension
  23. {
  24.     private $securityChecker;
  25.     private $impersonateUrlGenerator;
  26.     public function __construct(AuthorizationCheckerInterface $securityChecker nullImpersonateUrlGenerator $impersonateUrlGenerator null)
  27.     {
  28.         $this->securityChecker $securityChecker;
  29.         $this->impersonateUrlGenerator $impersonateUrlGenerator;
  30.     }
  31.     /**
  32.      * @param mixed $object
  33.      */
  34.     public function isGranted($role$object nullstring $field null): bool
  35.     {
  36.         if (null === $this->securityChecker) {
  37.             return false;
  38.         }
  39.         if (null !== $field) {
  40.             $object = new FieldVote($object$field);
  41.         }
  42.         try {
  43.             return $this->securityChecker->isGranted($role$object);
  44.         } catch (AuthenticationCredentialsNotFoundException $e) {
  45.             return false;
  46.         }
  47.     }
  48.     public function getImpersonateExitUrl(string $exitTo null): string
  49.     {
  50.         if (null === $this->impersonateUrlGenerator) {
  51.             return '';
  52.         }
  53.         return $this->impersonateUrlGenerator->generateExitUrl($exitTo);
  54.     }
  55.     public function getImpersonateExitPath(string $exitTo null): string
  56.     {
  57.         if (null === $this->impersonateUrlGenerator) {
  58.             return '';
  59.         }
  60.         return $this->impersonateUrlGenerator->generateExitPath($exitTo);
  61.     }
  62.     /**
  63.      * {@inheritdoc}
  64.      */
  65.     public function getFunctions(): array
  66.     {
  67.         return [
  68.             new TwigFunction('is_granted', [$this'isGranted']),
  69.             new TwigFunction('impersonation_exit_url', [$this'getImpersonateExitUrl']),
  70.             new TwigFunction('impersonation_exit_path', [$this'getImpersonateExitPath']),
  71.         ];
  72.     }
  73. }