Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
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
-------

709efa3 make csrf_token() usable without forms
  • Loading branch information
fabpot committed Mar 21, 2018
2 parents d4bfbb8 + 709efa3 commit a1b1a44
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
44 changes: 44 additions & 0 deletions src/Symfony/Bridge/Twig/Extension/CsrfExtension.php
@@ -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();
}
}
Expand Up @@ -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>

0 comments on commit a1b1a44

Please sign in to comment.