Completed
Push — master ( 43ae25...bc0bf7 )
by Paweł
27:13 queued 11:59
created

SessionCartSubscriber::onKernelResponse()   C

Complexity

Conditions 7
Paths 5

Size

Total Lines 26
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 26
rs 6.7272
cc 7
eloc 14
nc 5
nop 1
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
namespace Sylius\Bundle\CartBundle\EventListener;
13
14
use Sylius\Component\Cart\Context\CartContextInterface;
15
use Sylius\Component\Cart\Context\CartNotFoundException;
16
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
17
use Symfony\Component\HttpFoundation\Request;
18
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
19
use Symfony\Component\HttpKernel\KernelEvents;
20
21
/**
22
 * @author Paweł Jędrzejewski <[email protected]>
23
 */
24
final class SessionCartSubscriber implements EventSubscriberInterface
25
{
26
    /**
27
     * @var CartContextInterface
28
     */
29
    private $cartContext;
30
31
    /**
32
     * @var string
33
     */
34
    private $sessionKeyName;
35
36
    /**
37
     * @param CartContextInterface $cartContext
38
     * @param string $sessionKeyName
39
     */
40
    public function __construct(CartContextInterface $cartContext, $sessionKeyName)
41
    {
42
        $this->cartContext = $cartContext;
43
        $this->sessionKeyName = $sessionKeyName;
44
    }
45
46
    /**
47
     * {@inheritdoc}
48
     */
49
    public static function getSubscribedEvents()
50
    {
51
        return [
52
            KernelEvents::RESPONSE => ['onKernelResponse'],
53
        ];
54
    }
55
56
    /**
57
     * @param FilterResponseEvent $event
58
     */
59
    public function onKernelResponse(FilterResponseEvent $event)
60
    {
61
        if (!$event->isMasterRequest()) {
62
            return;
63
        }
64
65
        /** @var Request $request */
66
        $request = $event->getRequest();
67
        // Hacky hack. Until there is a better solution.
68
        if (!$this->isHtmlRequest($request)) {
69
            return;
70
        }
71
72
        try {
73
            $cart = $this->cartContext->getCart();
74
        } catch (CartNotFoundException $exception) {
75
            return;
76
        }
77
78
        if (null !== $cart && null !== $cart->getId() && null !== $cart->getChannel()) {
79
            $request->getSession()->set(
80
                sprintf('%s.%s', $this->sessionKeyName, $cart->getChannel()->getCode()),
81
                $cart->getId()
82
            );
83
        }
84
    }
85
86
    /**
87
     * @param Request $request
88
     *
89
     * @return bool
90
     */
91
    private function isHtmlRequest(Request $request)
92
    {
93
        return 'html' === $request->getRequestFormat();
94
    }
95
}
96