Completed
Push — master ( 165cff...1212b8 )
by Paweł
23:36 queued 13:31
created

OrderItemController::getCartItemErrors()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
rs 9.4285
cc 1
eloc 4
nc 1
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\OrderBundle\Controller;
13
14
use Doctrine\Common\Persistence\ObjectRepository;
15
use Doctrine\ORM\EntityManagerInterface;
16
use FOS\RestBundle\View\View;
17
use Sylius\Bundle\ResourceBundle\Controller\RequestConfiguration;
18
use Sylius\Bundle\ResourceBundle\Controller\ResourceController;
19
use Sylius\Component\Order\CartActions;
20
use Sylius\Component\Order\Context\CartContextInterface;
21
use Sylius\Component\Order\Model\OrderInterface;
22
use Sylius\Component\Order\Model\OrderItemInterface;
23
use Sylius\Component\Order\Modifier\OrderItemQuantityModifierInterface;
24
use Sylius\Component\Order\Modifier\OrderModifierInterface;
25
use Symfony\Component\Form\FormError;
26
use Symfony\Component\Form\FormFactoryInterface;
27
use Symfony\Component\Form\FormInterface;
28
use Symfony\Component\HttpFoundation\RedirectResponse;
29
use Symfony\Component\HttpFoundation\Request;
30
use Symfony\Component\HttpFoundation\Response;
31
use Symfony\Component\HttpKernel\Exception\HttpException;
32
use Symfony\Component\Validator\ConstraintViolationListInterface;
33
34
/**
35
 * @author Paweł Jędrzejewski <[email protected]>
36
 */
37
class OrderItemController extends ResourceController
38
{
39
    /**
40
     * @param Request $request
41
     *
42
     * @return Response
43
     */
44
    public function addAction(Request $request)
45
    {
46
        $cart = $this->getCurrentCart();
47
        $configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
48
49
        $this->isGrantedOr403($configuration, CartActions::ADD);
50
        /** @var OrderItemInterface $orderItem */
51
        $orderItem = $this->newResourceFactory->create($configuration, $this->factory);
52
53
        $this->getQuantityModifier()->modify($orderItem, 1);
54
55
        $form = $this->getFormFactory()->create(
56
            $configuration->getFormType(),
57
            $this->createAddToCartCommand($cart, $orderItem),
58
            $configuration->getFormOptions()
59
        );
60
61
        if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
62
            /** @var AddToCartCommandInterface $addCartItemCommand */
63
            $addToCartCommand = $form->getData();
64
65
            $errors = $this->getCartItemErrors($addToCartCommand->getCartItem());
66
            if (0 < count($errors)) {
67
                $form = $this->getAddToCartFormWithErrors($errors, $form);
68
69
                return $this->handleBadAjaxRequestView($configuration, $form);
70
            }
71
72
            $event = $this->eventDispatcher->dispatchPreEvent(CartActions::ADD, $configuration, $orderItem);
73
74
            if ($event->isStopped() && !$configuration->isHtmlRequest()) {
75
                throw new HttpException($event->getErrorCode(), $event->getMessage());
76
            }
77
            if ($event->isStopped()) {
78
                $this->flashHelper->addFlashFromEvent($configuration, $event);
79
80
                return $this->redirectHandler->redirectToIndex($configuration, $orderItem);
81
            }
82
83
            $this->getOrderModifier()->addToOrder($addToCartCommand->getCart(), $addToCartCommand->getCartItem());
84
85
            $cartManager = $this->getCartManager();
86
            $cartManager->persist($cart);
87
            $cartManager->flush();
88
89
            $resourceControllerEvent = $this->eventDispatcher->dispatchPostEvent(CartActions::ADD, $configuration, $orderItem);
90
            if ($resourceControllerEvent->hasResponse()) {
91
                return $resourceControllerEvent->getResponse();
92
            }
93
94
            $this->flashHelper->addSuccessFlash($configuration, CartActions::ADD, $orderItem);
95
96
            if ($request->isXmlHttpRequest()) {
97
                return $this->viewHandler->handle($configuration, View::create([], Response::HTTP_CREATED));
98
            }
99
100
            return $this->redirectHandler->redirectToResource($configuration, $orderItem);
101
        }
102
103
        if (!$configuration->isHtmlRequest()) {
104
            return $this->handleBadAjaxRequestView($configuration, $form);
105
        }
106
107
        $view = View::create()
108
            ->setData([
109
                'configuration' => $configuration,
110
                $this->metadata->getName() => $orderItem,
111
                'form' => $form->createView(),
112
            ])
113
            ->setTemplate($configuration->getTemplate(CartActions::ADD . '.html'))
114
        ;
115
116
        return $this->viewHandler->handle($configuration, $view);
117
    }
118
119
    /**
120
     * @param Request $request
121
     *
122
     * @return Response
123
     */
124
    public function removeAction(Request $request)
125
    {
126
        $configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
127
128
        $this->isGrantedOr403($configuration, CartActions::REMOVE);
129
        $orderItem = $this->findOr404($configuration);
130
131
        $event = $this->eventDispatcher->dispatchPreEvent(CartActions::REMOVE, $configuration, $orderItem);
132
133
        if ($configuration->isCsrfProtectionEnabled() && !$this->isCsrfTokenValid($orderItem->getId(), $request->request->get('_csrf_token'))) {
134
            throw new HttpException(Response::HTTP_FORBIDDEN, 'Invalid csrf token.');
135
        }
136
137
        if ($event->isStopped() && !$configuration->isHtmlRequest()) {
138
            throw new HttpException($event->getErrorCode(), $event->getMessage());
139
        }
140
        if ($event->isStopped()) {
141
            $this->flashHelper->addFlashFromEvent($configuration, $event);
142
143
            return $this->redirectHandler->redirectToIndex($configuration, $orderItem);
144
        }
145
146
        $cart = $this->getCurrentCart();
147
        $this->getOrderModifier()->removeFromOrder($cart, $orderItem);
0 ignored issues
show
Compatibility introduced by
$orderItem of type object<Sylius\Component\...odel\ResourceInterface> is not a sub-type of object<Sylius\Component\...del\OrderItemInterface>. It seems like you assume a child interface of the interface Sylius\Component\Resource\Model\ResourceInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
148
149
        $this->repository->remove($orderItem);
150
151
        $cartManager = $this->getCartManager();
152
        $cartManager->persist($cart);
153
        $cartManager->flush();
154
155
        $this->eventDispatcher->dispatchPostEvent(CartActions::REMOVE, $configuration, $orderItem);
156
157
        if (!$configuration->isHtmlRequest()) {
158
            return $this->viewHandler->handle($configuration, View::create(null, Response::HTTP_NO_CONTENT));
159
        }
160
161
        $this->flashHelper->addSuccessFlash($configuration, CartActions::REMOVE, $orderItem);
162
163
        return $this->redirectHandler->redirectToIndex($configuration, $orderItem);
164
    }
165
166
    /**
167
     * @return ObjectRepository
168
     */
169
    protected function getOrderRepository()
170
    {
171
        return $this->get('sylius.repository.order');
172
    }
173
174
    /**
175
     * @param RequestConfiguration $configuration
176
     *
177
     * @return RedirectResponse
178
     */
179
    protected function redirectToCartSummary(RequestConfiguration $configuration)
180
    {
181
        if (null === $configuration->getParameters()->get('redirect')) {
182
            return $this->redirectHandler->redirectToRoute($configuration, $this->getCartSummaryRoute());
183
        }
184
185
        return $this->redirectHandler->redirectToRoute($configuration, $configuration->getParameters()->get('redirect'));
186
    }
187
188
    /**
189
     * @return string
190
     */
191
    protected function getCartSummaryRoute()
192
    {
193
        return 'sylius_cart_summary';
194
    }
195
196
    /**
197
     * @return OrderInterface
198
     */
199
    protected function getCurrentCart()
200
    {
201
        return $this->getContext()->getCart();
202
    }
203
204
    /**
205
     * @return CartContextInterface
206
     */
207
    protected function getContext()
208
    {
209
        return $this->get('sylius.context.cart');
210
    }
211
212
    /**
213
     * @param OrderInterface $cart
214
     * @param OrderItemInterface $cartItem
215
     *
216
     * @return AddToCartCommandInterface
217
     */
218
    protected function createAddToCartCommand(OrderInterface $cart, OrderItemInterface $cartItem)
219
    {
220
        return $this->get('sylius.factory.add_to_cart_command')->createWithCartAndCartItem($cart, $cartItem);
221
    }
222
223
    /**
224
     * @return FormFactoryInterface
225
     */
226
    protected function getFormFactory()
227
    {
228
        return $this->get('form.factory');
229
    }
230
231
    /**
232
     * @return OrderItemQuantityModifierInterface
233
     */
234
    protected function getQuantityModifier()
235
    {
236
        return $this->get('sylius.order_item_quantity_modifier');
237
    }
238
239
    /**
240
     * @return OrderModifierInterface
241
     */
242
    protected function getOrderModifier()
243
    {
244
        return $this->get('sylius.order_modifier');
245
    }
246
247
    /**
248
     * @return EntityManagerInterface
249
     */
250
    protected function getCartManager()
251
    {
252
        return $this->get('sylius.manager.order');
253
    }
254
255
    /**
256
     * @param OrderItemInterface $orderItem
257
     *
258
     * @return ConstraintViolationListInterface
259
     */
260
    private function getCartItemErrors(OrderItemInterface $orderItem)
261
    {
262
        return $this
263
            ->get('validator')
264
            ->validate($orderItem, null, $this->getParameter('sylius.form.type.order_item.validation_groups'))
265
        ;
266
    }
267
268
    /**
269
     * @param ConstraintViolationListInterface $errors
270
     * @param FormInterface $form
271
     *
272
     * @return FormInterface
273
     */
274
    private function getAddToCartFormWithErrors(ConstraintViolationListInterface $errors, FormInterface $form)
275
    {
276
        foreach ($errors as $error) {
277
            $form->get('cartItem')->get($error->getPropertyPath())->addError(new FormError($error->getMessage()));
278
        }
279
280
        return $form;
281
    }
282
283
    /**
284
     * @param RequestConfiguration $configuration
285
     * @param FormInterface $form
286
     *
287
     * @return Response
288
     */
289
    private function handleBadAjaxRequestView(RequestConfiguration $configuration, FormInterface $form)
290
    {
291
        return $this->viewHandler->handle(
292
            $configuration,
293
            View::create($form, Response::HTTP_BAD_REQUEST)->setData(['errors' => $form->getErrors(true, true)])
294
        );
295
    }
296
}
297