Completed
Push — master ( c02c99...521b85 )
by Paweł
66:22 queued 55:17
created

SessionCartSubscriber::getSubscribedEvents()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 0
1
<?php
2
3
/*
4
 * This file is part of the Sylius package.
5
 *
6
 * (c) Paweł Jędrzejewski
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
declare(strict_types=1);
13
14
namespace Sylius\Bundle\ShopBundle\EventListener;
15
16
use Sylius\Component\Order\Context\CartContextInterface;
17
use Sylius\Component\Order\Context\CartNotFoundException;
18
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
19
use Symfony\Component\HttpFoundation\Request;
20
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
21
use Symfony\Component\HttpKernel\KernelEvents;
22
23
/**
24
 * @author Paweł Jędrzejewski <[email protected]>
25
 */
26
final class SessionCartSubscriber implements EventSubscriberInterface
27
{
28
    /**
29
     * @var CartContextInterface
30
     */
31
    private $cartContext;
32
33
    /**
34
     * @var string
35
     */
36
    private $sessionKeyName;
37
38
    /**
39
     * @param CartContextInterface $cartContext
40
     * @param string $sessionKeyName
41
     */
42
    public function __construct(CartContextInterface $cartContext, string $sessionKeyName)
43
    {
44
        $this->cartContext = $cartContext;
45
        $this->sessionKeyName = $sessionKeyName;
46
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51
    public static function getSubscribedEvents(): array
52
    {
53
        return [
54
            KernelEvents::RESPONSE => ['onKernelResponse'],
55
        ];
56
    }
57
58
    /**
59
     * @param FilterResponseEvent $event
60
     */
61
    public function onKernelResponse(FilterResponseEvent $event): void
62
    {
63
        if (!$event->isMasterRequest()) {
64
            return;
65
        }
66
67
        /** @var Request $request */
68
        $request = $event->getRequest();
69
70
        try {
71
            $cart = $this->cartContext->getCart();
72
        } catch (CartNotFoundException $exception) {
73
            return;
74
        }
75
76
        if (null !== $cart && null !== $cart->getId() && null !== $cart->getChannel()) {
77
            $session = $request->getSession();
78
79
            $session->set(
80
                sprintf('%s.%s', $this->sessionKeyName, $cart->getChannel()->getCode()),
81
                $cart->getId()
82
            );
83
        }
84
    }
85
}
86