feature #25197 [FrameworkBundle][TwigBridge] make csrf_token() usable without forms (xabbuh)

This PR was merged into the 4.1-dev branch.

Discussion
----------

[FrameworkBundle][TwigBridge] make csrf_token() usable without forms

| Q             | A
| ------------- | ---
| Branch?       | master
| Bug fix?      | no
| New feature?  | yes
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets |
| License       | MIT
| Doc PR        |

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.

Commits
-------

709efa30fc make csrf_token() usable without forms
This commit is contained in:
Fabien Potencier 2018-03-21 10:10:25 +01:00
commit a1b1a44a7b
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>