FlashMessageListener::onKernelResponse()   B
last analyzed

Complexity

Conditions 7
Paths 11

Size

Total Lines 49

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 7.025

Importance

Changes 0
Metric Value
dl 0
loc 49
ccs 23
cts 25
cp 0.92
rs 8.1793
c 0
b 0
f 0
cc 7
nc 11
nop 1
crap 7.025
1
<?php
2
3
/*
4
 * This file is part of the FOSHttpCacheBundle package.
5
 *
6
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace FOS\HttpCacheBundle\EventListener;
13
14
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
15
use Symfony\Component\HttpFoundation\Cookie;
16
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
17
use Symfony\Component\HttpFoundation\Session\Session;
18
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
19
use Symfony\Component\HttpKernel\Event\ResponseEvent;
20
use Symfony\Component\HttpKernel\HttpKernel;
21
use Symfony\Component\HttpKernel\Kernel;
22
use Symfony\Component\HttpKernel\KernelEvents;
23
use Symfony\Component\OptionsResolver\OptionsResolver;
24
25 1 View Code Duplication
if (Kernel::MAJOR_VERSION >= 5) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
26 1
    class_alias(ResponseEvent::class, 'FOS\HttpCacheBundle\EventListener\FlashMessageResponseEvent');
27
} else {
28
    class_alias(FilterResponseEvent::class, 'FOS\HttpCacheBundle\EventListener\FlashMessageResponseEvent');
29
}
30
31
/**
32
 * This event handler reads all flash messages and moves them into a cookie.
33
 *
34
 * @author Lukas Kahwe Smith <[email protected]>
35
 */
36
final class FlashMessageListener implements EventSubscriberInterface
37
{
38
    /**
39
     * @var array
40
     */
41
    private $options;
42
43
    /**
44
     * @var Session
45
     */
46
    private $session;
47
48
    /**
49
     * @param Session $session A session instance
50
     */
51
    public function __construct($session, array $options = [])
52 20
    {
53
        $this->session = $session;
54 20
55
        $resolver = new OptionsResolver();
56 20
        $resolver->setRequired(['name', 'path', 'host', 'secure']);
57 20
        $resolver->setAllowedTypes('name', 'string');
58 20
        $resolver->setAllowedTypes('path', 'string');
59 20
        $resolver->setAllowedTypes('host', ['string', 'null']);
60 20
        $resolver->setAllowedTypes('secure', 'bool');
61 20
        $this->options = $resolver->resolve($options);
62 20
    }
63 20
64
    /**
65
     * {@inheritdoc}
66
     */
67
    public static function getSubscribedEvents()
68 2
    {
69
        return [
70
            KernelEvents::RESPONSE => 'onKernelResponse',
71 2
        ];
72
    }
73
74
    /**
75
     * Moves flash messages from the session to a cookie inside a Response Kernel listener.
76
     */
77
    public function onKernelResponse(FlashMessageResponseEvent $event)
78 19
    {
79
        if (HttpKernel::MASTER_REQUEST !== $event->getRequestType()) {
80 19
            return;
81 1
        }
82
83
        // Flash messages are stored in the session. If there is none, there
84
        // can't be any flash messages in it. $session->getFlashBag() would
85
        // create a session, we need to avoid that.
86
        if (!$this->session->isStarted()) {
87 19
            return;
88 15
        }
89
90
        $flashBag = $this->session->getFlashBag();
91 4
        $flashes = $flashBag->all();
92 4
93
        if (empty($flashes)) {
94 4
            return;
95 3
        }
96
97
        $response = $event->getResponse();
98 1
99
        $cookies = $response->headers->getCookies(ResponseHeaderBag::COOKIES_ARRAY);
100 1
        $host = (null === $this->options['host']) ? '' : $this->options['host'];
101 1
        if (isset($cookies[$host][$this->options['path']][$this->options['name']])) {
102 1
            $rawCookie = $cookies[$host][$this->options['path']][$this->options['name']]->getValue();
103
            $flashes = array_merge_recursive($flashes, json_decode($rawCookie, true));
104
        }
105
106
        // Preserve existing flash message cookie from previous redirect if there was one.
107 1
        // This covers multiple redirects where each redirect adds flash messages.
108 1
        $request = $event->getRequest();
109 1
        if ($request->cookies->has($this->options['name'])) {
110 1
            $rawCookie = $request->cookies->get($this->options['name']);
111 1
            $flashes = array_merge_recursive($flashes, json_decode($rawCookie, true));
112 1
        }
113 1
114 1
        $cookie = new Cookie(
115
            $this->options['name'],
116
            json_encode($flashes),
117 1
            0,
118 1
            $this->options['path'],
119
            $this->options['host'],
120
            $this->options['secure'],
121
            false
122
        );
123
124
        $response->headers->setCookie($cookie);
125
    }
126
}
127