summaryrefslogtreecommitdiff
path: root/src/Renderer/Twig/Extensions/Csrf.php
blob: fee1c1f9e05842a463949396a55bfe90e2f8a383 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?php

namespace Engelsystem\Renderer\Twig\Extensions;

use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Twig\Extension\AbstractExtension as TwigExtension;
use Twig\TwigFunction;

class Csrf extends TwigExtension
{
    /** @var SessionInterface */
    protected $session;

    /**
     * @param SessionInterface $session
     */
    public function __construct(SessionInterface $session)
    {
        $this->session = $session;
    }

    /**
     * @return TwigFunction[]
     */
    public function getFunctions(): array
    {
        return [
            new TwigFunction('csrf', [$this, 'getCsrfField'], ['is_safe' => ['html']]),
            new TwigFunction('csrf_token', [$this, 'getCsrfToken']),
        ];
    }

    /**
     * @return string
     */
    public function getCsrfField(): string
    {
        return sprintf('<input type="hidden" name="_token" value="%s">', $this->getCsrfToken());
    }

    /**
     * @return string
     */
    public function getCsrfToken(): string
    {
        return $this->session->get('_token');
    }
}