Test Setup Failed
Pull Request — develop (#17)
by Evert
04:12
created

CookieGuardExtension::getName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
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 $request = null;
16
    private RequestStack $requestStack;
17
    private Environment $twig;
18
    private string $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
        return $this->request = $this->requestStack->getMainRequest();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->request = ...Stack->getMainRequest() 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...
67
    }
68
}
69