Issues (3)

Twig/CookieGuardExtension.php (1 issue)

1
<?php
2
declare(strict_types=1);
3
4
namespace FH\Bundle\CookieGuardBundle\Twig;
5
6
use Symfony\Component\HttpFoundation\Request;
7
use Symfony\Component\HttpFoundation\RequestStack;
8
use Twig\Environment;
9
use Twig\Extension\AbstractExtension;
10
use Twig\TwigFilter;
11
use Twig\TwigFunction;
12
13
class CookieGuardExtension extends AbstractExtension
14
{
15
    private $request;
16
    private $requestStack;
17
    private $twig;
18
    private $cookieName;
19
20
    public function __construct(RequestStack $requestStack, Environment $twig, string $cookieName)
21
    {
22
        $this->requestStack = $requestStack;
23
        $this->twig = $twig;
24
        $this->cookieName = $cookieName;
25
    }
26
27
    public function getFilters(): array
28
    {
29
        return [
30
            new TwigFilter('cookie_guard', [$this, 'showIfCookieAccepted'], ['pre_escape' => 'html', 'is_safe' => ['html']])
31
        ];
32
    }
33
34
    public function getFunctions(): array
35
    {
36
        return [
37
            new TwigFunction('cookie_settings_submitted', [$this, 'cookieSettingsSubmitted'], ['is_safe' => ['html']]),
38
            new TwigFunction('cookie_settings_accepted', [$this, 'cookieSettingsAreAccepted'])
39
        ];
40
    }
41
42
    public function showIfCookieAccepted(string $content): string
43
    {
44
        return $this->twig->render('@FHCookieGuard/CookieGuard/cookieGuardedContent.html.twig', [
45
            'content' => $content,
46
            'show' => $this->cookieSettingsAreAccepted()
47
        ]);
48
    }
49
50
    public function cookieSettingsAreAccepted(): bool
51
    {
52
        return (bool) $this->getRequest()->cookies->get($this->cookieName, false);
53
    }
54
55
    public function cookieSettingsSubmitted(): bool
56
    {
57
        return $this->getRequest()->cookies->has($this->cookieName);
58
    }
59
60
    private function getRequest(): Request
61
    {
62
        if ($this->request instanceof Request) {
63
            return $this->request;
64
        }
65
66
        $this->request = $this->requestStack->getMasterRequest();
67
68
        return $this->request;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->request could return the type null which is incompatible with the type-hinted return Symfony\Component\HttpFoundation\Request. Consider adding an additional type-check to rule them out.
Loading history...
69
    }
70
71
    public function getName(): string
72
    {
73
        return get_class($this);
74
    }
75
}
76