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

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 ?AuthorizationCheckerInterface $securityChecker;
  25.     private ?ImpersonateUrlGenerator $impersonateUrlGenerator;
  26.     public function __construct(AuthorizationCheckerInterface $securityChecker nullImpersonateUrlGenerator $impersonateUrlGenerator null)
  27.     {
  28.         $this->securityChecker $securityChecker;
  29.         $this->impersonateUrlGenerator $impersonateUrlGenerator;
  30.     }
  31.     public function isGranted(mixed $rolemixed $object nullstring $field null): bool
  32.     {
  33.         if (null === $this->securityChecker) {
  34.             return false;
  35.         }
  36.         if (null !== $field) {
  37.             $object = new FieldVote($object$field);
  38.         }
  39.         try {
  40.             return $this->securityChecker->isGranted($role$object);
  41.         } catch (AuthenticationCredentialsNotFoundException) {
  42.             return false;
  43.         }
  44.     }
  45.     public function getImpersonateExitUrl(string $exitTo null): string
  46.     {
  47.         if (null === $this->impersonateUrlGenerator) {
  48.             return '';
  49.         }
  50.         return $this->impersonateUrlGenerator->generateExitUrl($exitTo);
  51.     }
  52.     public function getImpersonateExitPath(string $exitTo null): string
  53.     {
  54.         if (null === $this->impersonateUrlGenerator) {
  55.             return '';
  56.         }
  57.         return $this->impersonateUrlGenerator->generateExitPath($exitTo);
  58.     }
  59.     public function getFunctions(): array
  60.     {
  61.         return [
  62.             new TwigFunction('is_granted'$this->isGranted(...)),
  63.             new TwigFunction('impersonation_exit_url'$this->getImpersonateExitUrl(...)),
  64.             new TwigFunction('impersonation_exit_path'$this->getImpersonateExitPath(...)),
  65.         ];
  66.     }
  67. }