Completed
Push — experimental/sf ( 5e64e6...ff63f8 )
by Kiyotaka
488:25 queued 479:20
created

ShoppingController::afterComplete()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 48

Duplication

Lines 8
Ratio 16.67 %

Code Coverage

Tests 20
CRAP Score 3.0416

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 1
dl 8
loc 48
rs 9.1344
c 0
b 0
f 0
ccs 20
cts 24
cp 0.8333
crap 3.0416
1
<?php
2
3
/*
4
 * This file is part of EC-CUBE
5
 *
6
 * Copyright(c) LOCKON CO.,LTD. All Rights Reserved.
7
 *
8
 * http://www.lockon.co.jp/
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Eccube\Controller;
15
16
use Eccube\Annotation\ForwardOnly;
17
use Eccube\Entity\BaseInfo;
18
use Eccube\Entity\Customer;
19
use Eccube\Entity\CustomerAddress;
20
use Eccube\Entity\Master\OrderStatus;
21
use Eccube\Entity\Order;
22
use Eccube\Entity\Shipping;
23
use Eccube\Event\EccubeEvents;
24
use Eccube\Event\EventArgs;
25
use Eccube\Exception\CartException;
26
use Eccube\Exception\ShoppingException;
27
use Eccube\Form\Type\Front\CustomerLoginType;
28
use Eccube\Form\Type\Front\ShoppingShippingType;
29
use Eccube\Form\Type\Shopping\CustomerAddressType;
30
use Eccube\Form\Type\Shopping\OrderType;
31
use Eccube\Repository\CustomerAddressRepository;
32
use Eccube\Repository\OrderRepository;
33
use Eccube\Service\CartService;
34
use Eccube\Service\OrderHelper;
35
use Eccube\Service\Payment\PaymentDispatcher;
36
use Eccube\Service\ShoppingService;
37
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
38
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
39
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
40
use Symfony\Component\Form\FormError;
41
use Symfony\Component\Form\FormInterface;
42
use Symfony\Component\HttpFoundation\ParameterBag;
43
use Symfony\Component\HttpFoundation\Request;
44
use Symfony\Component\HttpFoundation\Response;
45
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
46
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
47
48
class ShoppingController extends AbstractShoppingController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
49
{
50
    /**
51
     * @var BaseInfo
52
     */
53
    protected $BaseInfo;
54
55
    /**
56
     * @var OrderHelper
57
     */
58
    protected $orderHelper;
59
60
    /**
61
     * @var CartService
62
     */
63
    protected $cartService;
64
65
    /**
66
     * @var ShoppingService
67
     */
68
    protected $shoppingService;
69
70
    /**
71
     * @var CustomerAddressRepository
72
     */
73
    protected $customerAddressRepository;
74
75
    /**
76
     * @var ParameterBag
77
     */
78
    protected $parameterBag;
79
80
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$orderRepository" missing
Loading history...
81
     * ShoppingController constructor.
82
     *
83
     * @param BaseInfo $BaseInfo
0 ignored issues
show
introduced by
Expected 18 spaces after parameter type; 1 found
Loading history...
84
     * @param OrderHelper $orderHelper
0 ignored issues
show
introduced by
Expected 15 spaces after parameter type; 1 found
Loading history...
85
     * @param CartService $cartService
0 ignored issues
show
introduced by
Expected 15 spaces after parameter type; 1 found
Loading history...
86
     * @param ShoppingService $shoppingService
0 ignored issues
show
introduced by
Expected 11 spaces after parameter type; 1 found
Loading history...
87
     * @param CustomerAddressRepository $customerAddressRepository
88
     * @param ParameterBag $parameterBag
0 ignored issues
show
introduced by
Expected 14 spaces after parameter type; 1 found
Loading history...
introduced by
Doc comment for parameter $parameterBag does not match actual variable name $orderRepository
Loading history...
89
     */
90 59 View Code Duplication
    public function __construct(
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
91
        BaseInfo $BaseInfo,
92
        OrderHelper $orderHelper,
93
        CartService $cartService,
94
        ShoppingService $shoppingService,
95
        CustomerAddressRepository $customerAddressRepository,
96
        OrderRepository $orderRepository,
97
        ParameterBag $parameterBag
98
    ) {
99 59
        $this->BaseInfo = $BaseInfo;
100 59
        $this->orderHelper = $orderHelper;
101 59
        $this->cartService = $cartService;
102 59
        $this->shoppingService = $shoppingService;
103 59
        $this->customerAddressRepository = $customerAddressRepository;
104 59
        $this->orderRepository = $orderRepository;
105 59
        $this->parameterBag = $parameterBag;
106
    }
107
108
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
109
     * 購入画面表示
110
     *
111
     * @Route("/shopping", name="shopping")
112
     * @Template("Shopping/index.twig")
113
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
114 51
    public function index(Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
115
    {
116
        // カートチェック
117 51
        $response = $this->forwardToRoute('shopping_check_to_cart');
118 51
        if ($response->isRedirection() || $response->getContent()) {
119 1
            return $response;
120
        }
121
122
        // 受注情報を初期化
123 50
        $response = $this->forwardToRoute('shopping_initialize_order');
124 50
        if ($response->isRedirection() || $response->getContent()) {
125
            return $response;
126
        }
127
128
        /** @var Order $Order */
129 50
        $Order = $this->parameterBag->get('Order');
130
131
        // 単価集計
132 50
        $flowResult = $this->validatePurchaseFlow($Order);
133
134
        // 明細が丸められる場合に, カートから注文画面へ遷移できなくなるため, 集計の結果を保存する
135 50
        $this->entityManager->flush();
136
137
        // フォームを生成する
138 50
        $this->forwardToRoute('shopping_create_form');
139
140 50
        if ($flowResult->hasWarning() || $flowResult->hasError()) {
141 10
            return $this->redirectToRoute('cart');
142
        }
143
144 45
        $form = $this->parameterBag->get(OrderType::class);
145
146
        return [
147 45
            'form' => $form->createView(),
148 45
            'Order' => $Order,
149
        ];
150
    }
151
152
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
153
     * 購入確認画面から, 他の画面へのリダイレクト.
154
     * 配送業者や支払方法、お問い合わせ情報をDBに保持してから遷移する.
155
     *
156
     * @Route("/shopping/redirect", name="shopping_redirect_to")
157
     * @Template("Shopping/index.twig")
158
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
159 20
    public function redirectTo(Request $request)
160
    {
161
        // カートチェック
162 20
        $response = $this->forwardToRoute('shopping_check_to_cart');
163 20
        if ($response->isRedirection() || $response->getContent()) {
164
            return $response;
165
        }
166
167
        // 受注の存在チェック
168 20
        $response = $this->forwardToRoute('shopping_exists_order');
169 20
        if ($response->isRedirection() || $response->getContent()) {
170
            return $response;
171
        }
172
173
        // フォームの生成
174 20
        $this->forwardToRoute('shopping_create_form');
175 20
        $form = $this->parameterBag->get(OrderType::class);
176 20
        $form->handleRequest($request);
177
178
        // 各種変更ページへリダイレクトする
179 20
        $response = $this->forwardToRoute('shopping_redirect_to_change');
180 20
        if ($response->isRedirection() || $response->getContent()) {
181 8
            return $response;
182
        }
183 12
        $form = $this->parameterBag->get(OrderType::class);
184 12
        $Order = $this->parameterBag->get('Order');
185
186
        return [
187 12
            'form' => $form->createView(),
188 12
            'Order' => $Order,
189
        ];
190
    }
191
192
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
193
     * 購入処理
194
     *
195
     * @Route("/shopping/confirm", name="shopping_confirm")
196
     * @Method("POST")
197
     * @Template("Shopping/confirm.twig")
198
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
199 5
    public function confirm(Request $request)
200
    {
201
        // カートチェック
202 5
        $response = $this->forwardToRoute('shopping_check_to_cart');
203 5
        if ($response->isRedirection() || $response->getContent()) {
204
            return $response;
205
        }
206
207
        // 受注の存在チェック
208 5
        $response = $this->forwardToRoute('shopping_exists_order');
209 5
        if ($response->isRedirection() || $response->getContent()) {
210
            return $response;
211
        }
212
213
        // フォームの生成
214 5
        $this->forwardToRoute('shopping_create_form');
215 5
        $form = $this->parameterBag->get(OrderType::class);
216 5
        $form->handleRequest($request);
217
218 5
        $form = $this->parameterBag->get(OrderType::class);
219 5
        $Order = $this->parameterBag->get('Order');
220
221 5
        $flowResult = $this->validatePurchaseFlow($Order);
222 5
        if ($flowResult->hasWarning() || $flowResult->hasError()) {
223
            return $this->redirectToRoute('shopping_error');
224
        }
225
226 5
        $paymentMethod = $this->createPaymentMethod($Order, $form);
227
228 5
        $PaymentResult = $paymentMethod->verify();
229
        // エラーの場合は注文入力画面に戻す?
230 5
        if ($PaymentResult instanceof PaymentResult) {
231
            if (!$PaymentResult->isSuccess()) {
232
                $this->entityManager->getConnection()->rollback();
233
234
                $this->addError($PaymentResult->getErrors());
235
            }
236
237
            $response = $PaymentResult->getResponse();
238
            if ($response && ($response->isRedirection() || $response->getContent())) {
239
                $this->entityManager->flush();
240
241
                return $response;
242
            }
243
        }
244 5
        $this->entityManager->flush();
245
246
        return [
247 5
            'form' => $form->createView(),
248 5
            'Order' => $Order,
249
        ];
250
    }
251
252
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
253
     * 購入処理
254
     *
255
     * @Route("/shopping/order", name="shopping_order")
256
     * @Method("POST")
257
     * @Template("Shopping/index.twig")
258
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
259 6
    public function order(Request $request)
260
    {
261
        // カートチェック
262 6
        $response = $this->forwardToRoute('shopping_check_to_cart');
263 6
        if ($response->isRedirection() || $response->getContent()) {
264
            return $response;
265
        }
266
267
        // 受注の存在チェック
268 6
        $response = $this->forwardToRoute('shopping_exists_order');
269 6
        if ($response->isRedirection() || $response->getContent()) {
270
            return $response;
271
        }
272
273
        // form作成
274
        // FIXME イベントハンドラを外から渡したい
275 6
        $this->forwardToRoute('shopping_create_form');
276
277 6
        $form = $this->parameterBag->get(OrderType::class);
278 6
        $Order = $this->parameterBag->get('Order');
279 6
        $usePoint = $Order->getUsePoint();
280
281 6
        $form->handleRequest($request);
282 6
        $Order->setUsePoint($usePoint);
283
284
        // 受注処理
285 6
        $response = $this->forwardToRoute('shopping_complete_order');
286 6
        if ($response->isRedirection() || $response->getContent()) {
287 6
            return $response;
288
        }
289
290
        log_info('購入チェックエラー', [$Order->getId()]);
291
292
        return [
293
            'form' => $form->createView(),
294
            'Order' => $Order,
295
        ];
296
    }
297
298
    /**
299
     * 支払方法バーリデト
300
     */
301
    private function isValidPayment(Application $app, $form)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
302
    {
303
        $data = $form->getData();
304
        $paymentId = $data['payment']->getId();
305
        $shippings = $data['shippings'];
306
        $validCount = count($shippings);
307
        foreach ($shippings as $Shipping) {
308
            $payments = $app['eccube.repository.payment']->findPayments($Shipping->getDelivery());
309
            if ($payments == null) {
310
                continue;
311
            }
312
            foreach ($payments as $payment) {
313
                if ($payment['id'] == $paymentId) {
314
                    $validCount--;
315
                    continue;
316
                }
317
            }
318
        }
319
        if ($validCount == 0) {
320
            return true;
321
        }
322
        $form->get('payment')->addError(new FormError('front.shopping.payment.error'));
323
324
        return false;
325
    }
326
327
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
328
     * 購入完了画面表示
329
     *
330
     * @Route("/shopping/complete", name="shopping_complete")
331
     * @Template("Shopping/complete.twig")
332
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
333 1
    public function complete(Request $request)
0 ignored issues
show
introduced by
Declare public methods first, then protected ones and finally private ones
Loading history...
334
    {
335
        // 受注IDを取得
336 1
        $orderId = $this->session->get($this->sessionOrderKey);
337
338 1
        if (empty($orderId)) {
339
            return $this->redirectToRoute('homepage');
340
        }
341
342 1
        $Order = $this->orderRepository->find($orderId);
343
344 1
        $event = new EventArgs(
345
            [
346 1
                'Order' => $Order,
347
            ],
348 1
            $request
349
        );
350 1
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_COMPLETE_INITIALIZE, $event);
351
352 1
        if ($event->getResponse() !== null) {
353
            return $event->getResponse();
354
        }
355
356
        // 受注に関連するセッションを削除
357 1
        $this->session->remove($this->sessionOrderKey);
358 1
        $this->session->remove($this->sessionKey);
359 1
        $this->session->remove($this->sessionCustomerAddressKey);
360
361 1
        log_info('購入処理完了', [$Order->getId()]);
362
363 1
        $hasNextCart = !empty($this->cartService->getCarts());
364
365
        return [
366 1
            'Order' => $Order,
367 1
            'hasNextCart' => $hasNextCart,
368
        ];
369
    }
370
371
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$Shipping" missing
Loading history...
372
     * お届け先の設定一覧からの選択
373
     *
374
     * @Route("/shopping/shipping/{id}", name="shopping_shipping", requirements={"id" = "\d+"})
375
     * @Template("Shopping/shipping.twig")
376
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
377
    public function shipping(Request $request, Shipping $Shipping)
378
    {
379
        // カートチェック
380
        $response = $this->forwardToRoute('shopping_check_to_cart');
381
        if ($response->isRedirection() || $response->getContent()) {
382
            return $response;
383
        }
384
385
        // 受注の存在チェック
386
        $response = $this->forwardToRoute('shopping_exists_order');
387
        if ($response->isRedirection() || $response->getContent()) {
388
            return $response;
389
        }
390
391
        // 受注に紐づくShippingかどうかのチェック.
392
        /** @var Order $Order */
393
        $Order = $this->parameterBag->get('Order');
394
        if (!$Order->findShipping($Shipping->getId())) {
395
            throw new NotFoundHttpException();
396
        }
397
398
        $builder = $this->formFactory->createBuilder(CustomerAddressType::class, null, [
399
            'customer' => $this->getUser(),
400
            'shipping' => $Shipping,
401
        ]);
402
403
        $form = $builder->getForm();
404
        $form->handleRequest($request);
405
406
        if ($form->isSubmitted() && $form->isValid()) {
407
            log_info('お届先情報更新開始', [$Shipping->getId()]);
408
409
            /** @var CustomerAddress $CustomerAddress */
410
            $CustomerAddress = $form['addresses']->getData();
411
412
            // お届け先情報を更新
413
            $Shipping->setFromCustomerAddress($CustomerAddress);
414
415
            // 合計金額の再計算
416
            $flowResult = $this->validatePurchaseFlow($Order);
417
            if ($flowResult->hasWarning() || $flowResult->hasError()) {
418
                return $this->redirectToRoute('shopping_error');
419
            }
420
421
            // 配送先を更新
422
            $this->entityManager->flush();
423
424
            $event = new EventArgs(
425
                [
426
                    'Order' => $Order,
427
                    'Shipping' => $Shipping,
428
                ],
429
                $request
430
            );
431
            $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_COMPLETE, $event);
432
433
            log_info('お届先情報更新完了', [$Shipping->getId()]);
434
435
            return $this->redirectToRoute('shopping');
436
        }
437
438
        return [
439
            'form' => $form->createView(),
440
            'Customer' => $this->getUser(),
441
            'shippingId' => $Shipping->getId(),
442
        ];
443
    }
444
445
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$id" missing
Loading history...
446
     * お届け先の設定(非会員でも使用する)
447
     *
448
     * @Route("/shopping/shipping_edit/{id}", name="shopping_shipping_edit", requirements={"id" = "\d+"})
449
     * @Template("Shopping/shipping_edit.twig")
450
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
451
    public function shippingEdit(Request $request, $id)
452
    {
453
        // 配送先住所最大値判定
454
        $Customer = $this->getUser();
455
        if ($this->isGranted('IS_AUTHENTICATED_FULLY')) {
456
            $addressCurrNum = count($this->getUser()->getCustomerAddresses());
457
            $addressMax = $this->eccubeConfig['eccube_deliv_addr_max'];
458
            if ($addressCurrNum >= $addressMax) {
459
                throw new NotFoundHttpException(trans('shoppingcontroller.text.error.number_of_address'));
460
            }
461
        }
462
463
        // カートチェック
464
        $response = $this->forwardToRoute('shopping_check_to_cart');
465
        if ($response->isRedirection() || $response->getContent()) {
466
            return $response;
467
        }
468
469
        // 受注の存在チェック
470
        $response = $this->forwardToRoute('shopping_exists_order');
471
        if ($response->isRedirection() || $response->getContent()) {
472
            return $response;
473
        }
474
475
        /** @var Order $Order */
476
        $Order = $this->parameterBag->get('Order');
477
478
        $Shipping = $Order->findShipping($id);
479
        if (!$Shipping) {
480
            throw new NotFoundHttpException(trans('shoppingcontroller.text.error.set_address'));
481
        }
482
        if ($this->isGranted('IS_AUTHENTICATED_FULLY')) {
483
            $Shipping->clearCustomerAddress();
484
        }
485
486
        $CustomerAddress = new CustomerAddress();
487
        if ($this->isGranted('IS_AUTHENTICATED_FULLY')) {
488
            $CustomerAddress->setCustomer($Customer);
489
        } else {
490
            $CustomerAddress->setFromShipping($Shipping);
491
        }
492
493
        $builder = $this->formFactory->createBuilder(ShoppingShippingType::class, $CustomerAddress);
494
495
        $event = new EventArgs(
496
            [
497
                'builder' => $builder,
498
                'Order' => $Order,
499
                'Shipping' => $Shipping,
500
                'CustomerAddress' => $CustomerAddress,
501
            ],
502
            $request
503
        );
504
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_EDIT_INITIALIZE, $event);
505
506
        $form = $builder->getForm();
507
508
        $form->handleRequest($request);
509
510
        if ($form->isSubmitted() && $form->isValid()) {
511
            log_info('お届け先追加処理開始', ['id' => $Order->getId(), 'shipping' => $id]);
512
513
            // 会員の場合、お届け先情報を新規登録
514
            $Shipping->setFromCustomerAddress($CustomerAddress);
515
516
            if ($Customer instanceof Customer) {
517
                $this->entityManager->persist($CustomerAddress);
518
                log_info(
519
                    '新規お届け先登録',
520
                    [
521
                        'id' => $Order->getId(),
522
                        'shipping' => $id,
523
                        'customer address' => $CustomerAddress->getId(),
524
                    ]
525
                );
526
            }
527
528
            // 配送料金の設定
529
            $this->shoppingService->setShippingDeliveryFee($Shipping);
530
531
            // 合計金額の再計算
532
            $flowResult = $this->validatePurchaseFlow($Order);
533
            if ($flowResult->hasWarning() || $flowResult->hasError()) {
534
                return $this->redirectToRoute('shopping_error');
535
            }
536
537
            // 配送先を更新
538
            $this->entityManager->flush();
539
540
            $event = new EventArgs(
541
                [
542
                    'form' => $form,
543
                    'Shipping' => $Shipping,
544
                    'CustomerAddress' => $CustomerAddress,
545
                ],
546
                $request
547
            );
548
            $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_EDIT_COMPLETE, $event);
549
550
            log_info('お届け先追加処理完了', ['id' => $Order->getId(), 'shipping' => $id]);
551
552
            return $this->redirectToRoute('shopping');
553
        }
554
555
        return [
556
            'form' => $form->createView(),
557
            'shippingId' => $id,
558
        ];
559
    }
560
561
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$authenticationUtils" missing
Loading history...
562
     * ログイン
563
     *
564
     * @Route("/shopping/login", name="shopping_login")
565
     * @Template("Shopping/login.twig")
566
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
567 2
    public function login(Request $request, AuthenticationUtils $authenticationUtils)
568
    {
569 2
        if ($this->isGranted('IS_AUTHENTICATED_FULLY')) {
570
            return $this->redirectToRoute('shopping');
571
        }
572
573
        /* @var $form \Symfony\Component\Form\FormInterface */
574 2
        $builder = $this->formFactory->createNamedBuilder('', CustomerLoginType::class);
575
576 2
        if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
577
            $Customer = $this->getUser();
578
            if ($Customer) {
579
                $builder->get('login_email')->setData($Customer->getEmail());
580
            }
581
        }
582
583 2
        $event = new EventArgs(
584
            [
585 2
                'builder' => $builder,
586
            ],
587 2
            $request
588
        );
589 2
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_LOGIN_INITIALIZE, $event);
590
591 2
        $form = $builder->getForm();
592
593
        return [
594 2
            'error' => $authenticationUtils->getLastAuthenticationError(),
595 2
            'form' => $form->createView(),
596
        ];
597
    }
598
599
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
600
     * 購入エラー画面表示
601
     *
602
     * @Route("/shopping/error", name="shopping_error")
603
     * @Template("Shopping/shopping_error.twig")
604
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
605 1
    public function shoppingError(Request $request)
606
    {
607 1
        $event = new EventArgs(
608 1
            [],
609 1
            $request
610
        );
611 1
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_ERROR_COMPLETE, $event);
612
613 1
        if ($event->getResponse() !== null) {
614
            return $event->getResponse();
615
        }
616
617 1
        return [];
618
    }
619
620
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
621
     * カート画面のチェック
622
     *
623
     * @ForwardOnly
624
     * @Route("/shopping/check_to_cart", name="shopping_check_to_cart")
625
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
626 55
    public function checkToCart(Request $request)
627
    {
628 55
        $Cart = $this->cartService->getCart();
629 55
        if ($Cart && count($Cart->getCartItems()) > 0) {
630 53
            $divide = $request->getSession()->get('cart.divide');
631 53
            if ($divide) {
632
                log_info('種別が異なる商品がカートと結合されたためカート画面にリダイレクト');
633
634
                return $this->redirectToRoute('cart');
635
            }
636
637 53
            return new Response();
638
        }
639 2
        log_info('カートに商品が入っていないためショッピングカート画面にリダイレクト');
640
641
        // カートが存在しない時はエラー
642 2
        return $this->redirectToRoute('cart');
643
    }
644
645
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
646
     * 受注情報を初期化する.
647
     *
648
     * @ForwardOnly
649
     * @Route("/shopping/initialize_order", name="shopping_initialize_order")
650
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
651 50
    public function initializeOrder(Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
652
    {
653
        // 購入処理中の受注情報を取得
654 50
        $Order = $this->shoppingService->getOrder(OrderStatus::PROCESSING);
655
656
        // 初回アクセス(受注情報がない)の場合は, 受注情報を作成
657 50
        if (is_null($Order)) {
658
            // 未ログインの場合, ログイン画面へリダイレクト.
659 34
            if (!$this->isGranted('IS_AUTHENTICATED_FULLY')) {
660
                // 非会員でも一度会員登録されていればショッピング画面へ遷移
661
                $Customer = $this->shoppingService->getNonMember($this->sessionKey);
662
663
                if (is_null($Customer)) {
664
                    log_info('未ログインのためログイン画面にリダイレクト');
665
666
                    return $this->redirectToRoute('shopping_login');
667
                }
668
            } else {
669 34
                $Customer = $this->getUser();
670
            }
671
672
            try {
673
                // 受注情報を作成
674
                //$Order = $app['eccube.service.shopping']->createOrder($Customer);
675 34
                $Order = $this->orderHelper->createProcessingOrder(
676 34
                    $Customer,
677 34
                    $this->cartService->getCart()->getCartItems()
678
                );
679 34
                $this->cartService->setPreOrderId($Order->getPreOrderId());
680 34
                $this->cartService->save();
681
            } catch (CartException $e) {
682
                log_error('初回受注情報作成エラー', [$e->getMessage()]);
683
                $this->addRequestError($e->getMessage());
684
685
                return $this->redirectToRoute('cart');
686
            }
687
688
            // セッション情報を削除
689 34
            $this->session->remove($this->sessionOrderKey);
690
        }
691
692
        // 受注関連情報を最新状態に更新
693 50
        $this->entityManager->refresh($Order);
694
695 50
        $this->parameterBag->set('Order', $Order);
696
697 50
        return new Response();
698
    }
699
700
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
701
     * フォームを作成し, イベントハンドラを設定する
702
     *
703
     * @ForwardOnly
704
     * @Route("/shopping/create_form", name="shopping_create_form")
705
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
706 50
    public function createShoppingForm(Request $request)
707
    {
708 50
        $Order = $this->parameterBag->get('Order');
709
        // フォームの生成
710 50
        $builder = $this->formFactory->createBuilder(OrderType::class, $Order);
711
712 50
        $event = new EventArgs(
713
             [
714 50
                 'builder' => $builder,
715 50
                 'Order' => $Order,
716
             ],
717 50
             $request
718
         );
719 50
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_INDEX_INITIALIZE, $event);
720
721 50
        $form = $builder->getForm();
722
723 50
        $this->parameterBag->set(OrderType::class, $form);
724
725 50
        return new Response();
726
    }
727
728
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
729
     * mode に応じて各変更ページへリダイレクトする.
730
     *
731
     * @ForwardOnly
732
     * @Route("/shopping/redirect_to_change", name="shopping_redirect_to_change")
733
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
734 20
    public function redirectToChange(Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
735
    {
736 20
        $form = $this->parameterBag->get(OrderType::class);
737
738
        // requestのバインド後、Calculatorに再集計させる
739
        //$app['eccube.service.calculate']($Order, $Order->getCustomer())->calculate();
740
741
        // 支払い方法の変更や配送業者の変更があった場合はDBに保持する.
742 20
        if ($form->isSubmitted() && $form->isValid()) {
743
            // POSTされたデータをDBに保持.
744 8
            $this->entityManager->flush();
745
746 8
            $mode = $form['mode']->getData();
747 8
            switch ($mode) {
748 7
                case 'shipping_change':
749
                    // お届け先設定一覧へリダイレクト
750 1
                    $param = $form['param']->getData();
751
752 1
                    return $this->redirectToRoute('shopping_shipping', ['id' => $param]);
753 7
                case 'shipping_edit_change':
754
                    // お届け先設定一覧へリダイレクト
755
                    $param = $form['param']->getData();
756
757
                    return $this->redirectToRoute('shopping_shipping_edit', ['id' => $param]);
758 7
                case 'shipping_multiple_change':
759
                    // 複数配送設定へリダイレクト
760
                    return $this->redirectToRoute('shopping_shipping_multiple');
761 7
                case 'payment':
762 7
                case 'delivery':
763
                default:
764 7
                    return $this->redirectToRoute('shopping');
765
            }
766
        }
767
768 12
        return new Response();
769
    }
770
771
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
772
     * 受注の存在チェック
773
     *
774
     * @ForwardOnly
775
     * @Route("/shopping/exists_order", name="shopping_exists_order")
776
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
777 26
    public function existsOrder(Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
778
    {
779 26
        $Order = $this->shoppingService->getOrder(OrderStatus::PROCESSING);
780 26
        if (!$Order) {
781
            log_info('購入処理中の受注情報がないため購入エラー');
782
            $this->addError('front.shopping.order.error');
783
784
            return $this->redirectToRoute('shopping_error');
785
        }
786 26
        $this->parameterBag->set('Order', $Order);
787
788 26
        return new Response();
789
    }
790
791
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
792
     * 受注完了処理
793
     *
794
     * @ForwardOnly
795
     * @Route("/shopping/complete_order", name="shopping_complete_order")
796
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
797 6
    public function completeOrder(Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
798
    {
799 6
        $form = $this->parameterBag->get(OrderType::class);
800
801 6
        if ($form->isSubmitted() && $form->isValid()) {
802
            /** @var Order $Order */
803 6
            $Order = $form->getData();
804 6
            log_info('購入処理開始', [$Order->getId()]);
805
806
            // トランザクション制御
807 6
            $em = $this->entityManager;
808 6
            $em->getConnection()->beginTransaction();
809
            try {
810
                // お問い合わせ、配送時間などのフォーム項目をセット
811
                // FormTypeで更新されるため不要
812
                //$app['eccube.service.shopping']->setFormData($Order, $data);
813
814 6
                $flowResult = $this->validatePurchaseFlow($Order);
815 6
                if ($flowResult->hasWarning() || $flowResult->hasError()) {
816
                    // TODO エラーメッセージ
817
                    throw new ShoppingException();
818
                }
819
820 6
                $paymentMethod = $this->createPaymentMethod($Order, $form);
821
822
                // 必要に応じて別のコントローラへ forward or redirect(移譲)
823 6
                $dispatcher = $paymentMethod->apply(); // 決済処理中.
824
                // 一旦、決済処理中になった後は、購入処理中に戻せない。キャンセル or 購入完了の仕様とする
825
                // ステータス履歴も保持しておく? 在庫引き当ての仕様もセットで。
826 6
                if ($dispatcher instanceof PaymentDispatcher) {
827
                    $response = $dispatcher->getResponse();
828
                    $this->entityManager->flush();
829
                    $this->entityManager->commit();
830
831
                    if ($response && ($response->isRedirection() || $response->getContent())) {
832
                        return $response;
833
                    }
834
835
                    if ($dispatcher->isForward()) {
836
                        return $this->forwardToRoute($dispatcher->getRoute(), $dispatcher->getPathParameters(), $dispatcher->getQueryParameters());
837
                    } else {
838
                        return $this->redirectToRoute($dispatcher->getRoute(), array_merge($dispatcher->getPathParameters(), $dispatcher->getQueryParameters()));
839
                    }
840
                }
841
842
                // 決済実行
843 6
                $response = $this->forwardToRoute('shopping_do_checkout_order');
844 6
                $this->entityManager->flush();
845 6
                $this->entityManager->commit();
846
847 6
                if ($response->isRedirection() || $response->getContent()) {
848
                    return $response;
849
                }
850
851 6
                log_info('購入処理完了', [$Order->getId()]);
852
            } catch (ShoppingException $e) {
853
                log_error('購入エラー', [$e->getMessage()]);
854
855
                $this->entityManager->getConnection()->rollback();
856
857
                $this->log($e);
0 ignored issues
show
Bug introduced by
The method log() does not seem to exist on object<Eccube\Controller\ShoppingController>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
858
                $this->addError($e->getMessage());
859
860
                return $this->redirectToRoute('shopping_error');
861
            } catch (\Exception $e) {
862
                log_error('予期しないエラー', [$e->getMessage()]);
863
864
                $this->entityManager->getConnection()->rollback();
865
866
                $this->addError('front.shopping.system.error');
867
868
                return $this->redirectToRoute('shopping_error');
869
            }
870
871 6
            return $this->forwardToRoute('shopping_after_complete');
872
        }
873
874
        return new Response();
875
    }
876
877
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
878
     * 決済完了処理
879
     *
880
     * @ForwardOnly
881
     * @Route("/shopping/do_checkout_order", name="shopping_do_checkout_order")
882
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
883 6
    public function doCheckoutOrder(Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
884
    {
885 6
        $form = $this->parameterBag->get(OrderType::class);
886 6
        $Order = $this->parameterBag->get('Order');
887
888 6
        $paymentMethod = $this->createPaymentMethod($Order, $form);
889
890
        // 決済実行
891 6
        $PaymentResult = $paymentMethod->checkout();
892 6
        $response = $PaymentResult->getResponse();
893 6
        if ($response && ($response->isRedirection() || $response->getContent())) {
894
            return $response;
895
        }
896
897 6
        if (!$PaymentResult->isSuccess()) {
898
            $this->entityManager->getConnection()->rollback();
899
900
            $this->addError($PaymentResult->getErrors());
901
        }
902
903 6
        return new Response();
904
    }
905
906
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
907
     * 受注完了の後処理
908
     *
909
     * @ForwardOnly
910
     * @Route("/shopping/after_complete", name="shopping_after_complete")
911
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
912 6
    public function afterComplete(Request $request)
913
    {
914 6
        $form = $this->parameterBag->get(OrderType::class);
915 6
        $Order = $this->parameterBag->get('Order');
916
917
        // カート削除
918 6
        $this->cartService->clear();
919
920 6
        $event = new EventArgs(
921
            [
922 6
                'form' => $form,
923 6
                'Order' => $Order,
924
            ],
925 6
            $request
926
        );
927 6
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_CONFIRM_PROCESSING, $event);
928
929 6 View Code Duplication
        if ($event->getResponse() !== null) {
930
            log_info('イベントレスポンス返却', [$Order->getId()]);
931
932
            return $event->getResponse();
933
        }
934
935
        // 受注IDをセッションにセット
936 6
        $this->session->set($this->sessionOrderKey, $Order->getId());
937
938
        // メール送信
939 6
        $MailHistory = $this->shoppingService->sendOrderMail($Order);
940
941 6
        $event = new EventArgs(
942
            [
943 6
                'form' => $form,
944 6
                'Order' => $Order,
945 6
                'MailHistory' => $MailHistory,
946
            ],
947 6
            $request
948
        );
949 6
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_CONFIRM_COMPLETE, $event);
950
951 6 View Code Duplication
        if ($event->getResponse() !== null) {
952
            log_info('イベントレスポンス返却', [$Order->getId()]);
953
954
            return $event->getResponse();
955
        }
956
957
        // 完了画面表示
958 6
        return $this->redirectToRoute('shopping_complete');
959
    }
960
961 6
    private function createPaymentMethod(Order $Order, FormInterface $form)
962
    {
963 6
        $PaymentMethod = $this->container->get($Order->getPayment()->getMethodClass());
964 6
        $PaymentMethod->setOrder($Order);
965 6
        $PaymentMethod->setFormType($form);
966
967 6
        return $PaymentMethod;
968
    }
969
}
970