make csrf_token() usable without forms

The Twig function `csrf_token()` is currently only registered when the
Form component is installed. However, this function is also useful, for
example, when creating simple login forms for which you do not need the
full Form component.
This commit is contained in:
Christian Flothmann 2017-11-28 18:56:57 +01:00
parent 22192b16d8
commit 709efa30fc
2 changed files with 49 additions and 0 deletions

View File

@ -0,0 +1,44 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\Twig\Extension;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
/**
* @author Christian Flothmann <christian.flothmann@sensiolabs.de>
*/
class CsrfExtension extends AbstractExtension
{
private $csrfTokenManager;
public function __construct(CsrfTokenManagerInterface $csrfTokenManager)
{
$this->csrfTokenManager = $csrfTokenManager;
}
/**
* {@inheritdoc}
*/
public function getFunctions(): array
{
return array(
new TwigFunction('csrf_token', array($this, 'getCsrfToken')),
);
}
public function getCsrfToken(string $tokenId): string
{
return $this->csrfTokenManager->getToken($tokenId)->getValue();
}
}

View File

@ -21,5 +21,10 @@
<argument type="service" id="request_stack" on-invalid="ignore" />
</service>
<service id="Symfony\Component\Security\Csrf\CsrfTokenManagerInterface" alias="security.csrf.token_manager" />
<service id="twig.extension.security_csrf" class="Symfony\Bridge\Twig\Extension\CsrfExtension">
<tag name="twig.extension" />
<argument type="service" id="security.csrf.token_manager" />
</service>
</services>
</container>