Completed
Push — checkout-optimisation ( 756f29...9f37be )
by Kamil
27:45 queued 09:46
created

OrderController   C

Complexity

Total Complexity 28

Size/Duplication

Total Lines 211
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 24

Importance

Changes 0
Metric Value
wmc 28
c 0
b 0
f 0
lcom 1
cbo 24
dl 0
loc 211
rs 5.238

10 Methods

Rating   Name   Duplication   Size   Complexity  
B summaryAction() 0 25 3
A widgetAction() 0 17 2
B saveAction() 0 57 9
C clearAction() 0 33 7
A redirectToCartSummary() 0 8 2
A getCartSummaryRoute() 0 4 1
A getCurrentCart() 0 4 1
A getContext() 0 4 1
A getOrderRepository() 0 4 1
A getEventDispatcher() 0 4 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\OrderBundle\Controller;
13
14
use Doctrine\ORM\EntityManager;
15
use FOS\RestBundle\View\View;
16
use Payum\Core\Registry\RegistryInterface;
17
use Sylius\Bundle\ResourceBundle\Controller\RequestConfiguration;
18
use Sylius\Bundle\ResourceBundle\Controller\ResourceController;
19
use Sylius\Component\Core\Repository\OrderRepositoryInterface;
20
use Sylius\Component\Order\Context\CartContextInterface;
21
use Sylius\Component\Order\Model\OrderInterface;
22
use Sylius\Component\Order\SyliusCartEvents;
23
use Sylius\Component\Resource\ResourceActions;
24
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
25
use Symfony\Component\EventDispatcher\GenericEvent;
26
use Symfony\Component\HttpFoundation\RedirectResponse;
27
use Symfony\Component\HttpFoundation\Request;
28
use Symfony\Component\HttpFoundation\Response;
29
use Symfony\Component\HttpKernel\Exception\HttpException;
30
use Webmozart\Assert\Assert;
31
32
class OrderController extends ResourceController
33
{
34
    /**
35
     * @param Request $request
36
     *
37
     * @return Response
38
     */
39
    public function summaryAction(Request $request)
40
    {
41
        $configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
42
43
        $cart = $this->getCurrentCart();
44
        if (null !== $cart->getId()) {
45
            $cart = $this->getOrderRepository()->findCartForSummary($cart->getId());
46
        }
47
48
        if (!$configuration->isHtmlRequest()) {
49
            return $this->viewHandler->handle($configuration, View::create($cart));
50
        }
51
52
        $form = $this->resourceFormFactory->create($configuration, $cart);
0 ignored issues
show
Bug introduced by
It seems like $cart defined by $this->getOrderRepositor...Summary($cart->getId()) on line 45 can be null; however, Sylius\Bundle\ResourceBu...toryInterface::create() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
53
54
        $view = View::create()
55
            ->setTemplate($configuration->getTemplate('summary.html'))
56
            ->setData([
57
                'cart' => $cart,
58
                'form' => $form->createView(),
59
            ])
60
        ;
61
62
        return $this->viewHandler->handle($configuration, $view);
63
    }
64
    /**
65
     * @param Request $request
66
     *
67
     * @return Response
68
     */
69
    public function widgetAction(Request $request)
70
    {
71
        $configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
72
73
        $cart = $this->getCurrentCart();
74
75
        if (!$configuration->isHtmlRequest()) {
76
            return $this->viewHandler->handle($configuration, View::create($cart));
77
        }
78
79
        $view = View::create()
80
            ->setTemplate($configuration->getTemplate('summary.html'))
81
            ->setData(['cart' => $cart])
82
        ;
83
84
        return $this->viewHandler->handle($configuration, $view);
85
    }
86
87
    /**
88
     * @param Request $request
89
     *
90
     * @return Response
91
     */
92
    public function saveAction(Request $request)
93
    {
94
        $configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
95
96
        $this->isGrantedOr403($configuration, ResourceActions::UPDATE);
97
        $resource = $this->getCurrentCart();
98
99
        $form = $this->resourceFormFactory->create($configuration, $resource);
100
101
        if (in_array($request->getMethod(), ['POST', 'PUT', 'PATCH'], true) && $form->handleRequest($request)->isValid()) {
102
            $resource = $form->getData();
103
104
            $event = $this->eventDispatcher->dispatchPreEvent(ResourceActions::UPDATE, $configuration, $resource);
105
106
            if ($event->isStopped() && !$configuration->isHtmlRequest()) {
107
                throw new HttpException($event->getErrorCode(), $event->getMessage());
108
            }
109
            if ($event->isStopped()) {
110
                $this->flashHelper->addFlashFromEvent($configuration, $event);
111
112
                return $this->redirectHandler->redirectToResource($configuration, $resource);
113
            }
114
115
            if ($configuration->hasStateMachine()) {
116
                $this->stateMachine->apply($configuration, $resource);
117
            }
118
119
            $this->eventDispatcher->dispatchPostEvent(ResourceActions::UPDATE, $configuration, $resource);
120
121
            if (!$configuration->isHtmlRequest()) {
122
                return $this->viewHandler->handle($configuration, View::create(null, Response::HTTP_NO_CONTENT));
123
            }
124
125
            $this->getEventDispatcher()->dispatch(SyliusCartEvents::CART_CHANGE, new GenericEvent($resource));
126
            $this->manager->flush();
127
128
            $this->flashHelper->addSuccessFlash($configuration, ResourceActions::UPDATE, $resource);
129
130
            return $this->redirectHandler->redirectToResource($configuration, $resource);
131
        }
132
133
        if (!$configuration->isHtmlRequest()) {
134
            return $this->viewHandler->handle($configuration, View::create($form, Response::HTTP_BAD_REQUEST));
135
        }
136
137
        $view = View::create()
138
            ->setData([
139
                'configuration' => $configuration,
140
                $this->metadata->getName() => $resource,
141
                'form' => $form->createView(),
142
                'cart' => $resource,
143
            ])
144
            ->setTemplate($configuration->getTemplate(ResourceActions::UPDATE . '.html'))
145
        ;
146
147
        return $this->viewHandler->handle($configuration, $view);
148
    }
149
150
    /**
151
     * @param Request $request
152
     *
153
     * @return Response
154
     */
155
    public function clearAction(Request $request)
156
    {
157
        $configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
158
159
        $this->isGrantedOr403($configuration, ResourceActions::DELETE);
160
        $resource = $this->getCurrentCart();
161
162
        if ($configuration->isCsrfProtectionEnabled() && !$this->isCsrfTokenValid($resource->getId(), $request->get('_csrf_token'))) {
163
            throw new HttpException(Response::HTTP_FORBIDDEN, 'Invalid csrf token.');
164
        }
165
166
        $event = $this->eventDispatcher->dispatchPreEvent(ResourceActions::DELETE, $configuration, $resource);
167
168
        if ($event->isStopped() && !$configuration->isHtmlRequest()) {
169
            throw new HttpException($event->getErrorCode(), $event->getMessage());
170
        }
171
        if ($event->isStopped()) {
172
            $this->flashHelper->addFlashFromEvent($configuration, $event);
173
174
            return $this->redirectHandler->redirectToIndex($configuration, $resource);
175
        }
176
177
        $this->repository->remove($resource);
178
        $this->eventDispatcher->dispatchPostEvent(ResourceActions::DELETE, $configuration, $resource);
179
180
        if (!$configuration->isHtmlRequest()) {
181
            return $this->viewHandler->handle($configuration, View::create(null, Response::HTTP_NO_CONTENT));
182
        }
183
184
        $this->flashHelper->addSuccessFlash($configuration, ResourceActions::DELETE, $resource);
185
186
        return $this->redirectHandler->redirectToIndex($configuration, $resource);
187
    }
188
189
    /**
190
     * @param RequestConfiguration $configuration
191
     *
192
     * @return RedirectResponse
193
     */
194
    protected function redirectToCartSummary(RequestConfiguration $configuration)
195
    {
196
        if (null === $configuration->getParameters()->get('redirect')) {
197
            return $this->redirectHandler->redirectToRoute($configuration, $this->getCartSummaryRoute());
198
        }
199
200
        return $this->redirectHandler->redirectToRoute($configuration, $configuration->getParameters()->get('redirect'));
201
    }
202
203
    /**
204
     * @return string
205
     */
206
    protected function getCartSummaryRoute()
207
    {
208
        return 'sylius_cart_summary';
209
    }
210
211
    /**
212
     * @return OrderInterface
213
     */
214
    protected function getCurrentCart()
215
    {
216
        return $this->getContext()->getCart();
217
    }
218
219
    /**
220
     * @return CartContextInterface
221
     */
222
    protected function getContext()
223
    {
224
        return $this->get('sylius.context.cart');
225
    }
226
227
    /**
228
     * @return OrderRepositoryInterface
229
     */
230
    protected function getOrderRepository()
231
    {
232
        return $this->get('sylius.repository.order');
233
    }
234
235
    /**
236
     * @return EventDispatcherInterface
237
     */
238
    protected function getEventDispatcher()
239
    {
240
        return $this->container->get('event_dispatcher');
241
    }
242
}
243