Failed Conditions
Pull Request — experimental/sf (#3241)
by k-yamamura
43:19 queued 23:09
created

ShoppingController::customerValidation()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 88

Duplication

Lines 16
Ratio 18.18 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
nc 4
nop 2
dl 16
loc 88
rs 8.2617
c 0
b 0
f 0
ccs 0
cts 54
cp 0
crap 12

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Service\CartService;
33
use Eccube\Service\OrderHelper;
34
use Eccube\Service\Payment\PaymentDispatcher;
35
use Eccube\Service\PurchaseFlow\PurchaseContext;
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\HttpFoundation\ParameterBag;
42
use Symfony\Component\HttpFoundation\Request;
43
use Symfony\Component\HttpFoundation\Response;
44
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
45
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
46
47
class ShoppingController extends AbstractShoppingController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
48
{
49
    /**
50
     * @var BaseInfo
51
     */
52
    protected $BaseInfo;
53
54
    /**
55
     * @var OrderHelper
56
     */
57
    protected $orderHelper;
58
59
    /**
60
     * @var CartService
61
     */
62
    protected $cartService;
63
64
    /**
65
     * @var ShoppingService
66
     */
67
    protected $shoppingService;
68
69
    /**
70
     * @var CustomerAddressRepository
71
     */
72
    protected $customerAddressRepository;
73
74
    /**
75
     * @var ParameterBag
76
     */
77
    protected $parameterBag;
78
79
    /**
80
     * ShoppingController constructor.
81
     *
82
     * @param BaseInfo $BaseInfo
0 ignored issues
show
introduced by
Expected 18 spaces after parameter type; 1 found
Loading history...
83
     * @param OrderHelper $orderHelper
0 ignored issues
show
introduced by
Expected 15 spaces after parameter type; 1 found
Loading history...
84
     * @param CartService $cartService
0 ignored issues
show
introduced by
Expected 15 spaces after parameter type; 1 found
Loading history...
85
     * @param ShoppingService $shoppingService
0 ignored issues
show
introduced by
Expected 11 spaces after parameter type; 1 found
Loading history...
86
     * @param CustomerAddressRepository $customerAddressRepository
87
     * @param ParameterBag $parameterBag
0 ignored issues
show
introduced by
Expected 14 spaces after parameter type; 1 found
Loading history...
88
     */
89 59
    public function __construct(
90
        BaseInfo $BaseInfo,
91
        OrderHelper $orderHelper,
92
        CartService $cartService,
93
        ShoppingService $shoppingService,
94
        CustomerAddressRepository $customerAddressRepository,
95
        ParameterBag $parameterBag
96
    ) {
97 59
        $this->BaseInfo = $BaseInfo;
98 59
        $this->orderHelper = $orderHelper;
99 59
        $this->cartService = $cartService;
100 59
        $this->shoppingService = $shoppingService;
101 59
        $this->customerAddressRepository = $customerAddressRepository;
102 59
        $this->parameterBag = $parameterBag;
103
    }
104
105
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
106
     * 購入画面表示
107
     *
108
     * @Route("/shopping", name="shopping")
109
     * @Template("Shopping/index.twig")
110
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
111 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...
112
    {
113
        // カートチェック
114 51
        $response = $this->forwardToRoute('shopping_check_to_cart');
115 51
        if ($response->isRedirection() || $response->getContent()) {
116 1
            return $response;
117
        }
118
119
        // 受注情報を初期化
120 50
        $response = $this->forwardToRoute('shopping_initialize_order');
121 50
        if ($response->isRedirection() || $response->getContent()) {
122
            return $response;
123
        }
124
125
        /** @var Order $Order */
126 50
        $Order = $this->parameterBag->get('Order');
127
128
        // 単価集計
129 50
        $flowResult = $this->executePurchaseFlow($Order);
130
131
        // 明細が丸められる場合に, カートから注文画面へ遷移できなくなるため, 集計の結果を保存する
132 50
        $this->entityManager->flush();
133
134
        // フォームを生成する
135 50
        $this->forwardToRoute('shopping_create_form');
136
137 50
        if ($flowResult->hasWarning() || $flowResult->hasError()) {
138 10
            return $this->redirectToRoute('cart');
139
        }
140
141 45
        $form = $this->parameterBag->get(OrderType::class);
142
143
        return [
144 45
            'form' => $form->createView(),
145 45
            'Order' => $Order,
146
        ];
147
    }
148
149
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
150
     * 購入確認画面から, 他の画面へのリダイレクト.
151
     * 配送業者や支払方法、お問い合わせ情報をDBに保持してから遷移する.
152
     *
153
     * @Route("/shopping/redirect", name="shopping_redirect_to")
154
     * @Template("Shopping/index.twig")
155
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
156 20
    public function redirectTo(Request $request)
157
    {
158
        // カートチェック
159 20
        $response = $this->forwardToRoute('shopping_check_to_cart');
160 20
        if ($response->isRedirection() || $response->getContent()) {
161
            return $response;
162
        }
163
164
        // 受注の存在チェック
165 20
        $response = $this->forwardToRoute('shopping_exists_order');
166 20
        if ($response->isRedirection() || $response->getContent()) {
167
            return $response;
168
        }
169
170
        // フォームの生成
171 20
        $this->forwardToRoute('shopping_create_form');
172 20
        $form = $this->parameterBag->get(OrderType::class);
173 20
        $form->handleRequest($request);
174
175
        // 各種変更ページへリダイレクトする
176 20
        $response = $this->forwardToRoute('shopping_redirect_to_change');
177 20
        if ($response->isRedirection() || $response->getContent()) {
178 8
            return $response;
179
        }
180 12
        $form = $this->parameterBag->get(OrderType::class);
181 12
        $Order = $this->parameterBag->get('Order');
182
183
        return [
184 12
            'form' => $form->createView(),
185 12
            'Order' => $Order,
186
        ];
187
    }
188
189
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
190
     * 購入処理
191
     *
192
     * @Route("/shopping/confirm", name="shopping_confirm")
193
     * @Method("POST")
194
     * @Template("Shopping/confirm.twig")
195
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
196 5
    public function confirm(Request $request)
197
    {
198
        // カートチェック
199 5
        $response = $this->forwardToRoute('shopping_check_to_cart');
200 5
        if ($response->isRedirection() || $response->getContent()) {
201
            return $response;
202
        }
203
204
        // 受注の存在チェック
205 5
        $response = $this->forwardToRoute('shopping_exists_order');
206 5
        if ($response->isRedirection() || $response->getContent()) {
207
            return $response;
208
        }
209
210
        // フォームの生成
211 5
        $this->forwardToRoute('shopping_create_form');
212 5
        $form = $this->parameterBag->get(OrderType::class);
213 5
        $form->handleRequest($request);
214
215 5
        $form = $this->parameterBag->get(OrderType::class);
216 5
        $Order = $this->parameterBag->get('Order');
217
218 5
        $flowResult = $this->executePurchaseFlow($Order);
219 5
        if ($flowResult->hasWarning() || $flowResult->hasError()) {
220
            return $this->redirectToRoute('shopping_error');
221
        }
222
223 5
        $paymentService = $this->createPaymentService($Order);
224 5
        $paymentMethod = $this->createPaymentMethod($Order, $form);
225
226 5
        $PaymentResult = $paymentService->doVerify($paymentMethod);
227
        // エラーの場合は注文入力画面に戻す?
228 5
        if ($PaymentResult instanceof PaymentResult) {
229
            if (!$PaymentResult->isSuccess()) {
230
                $this->entityManager->getConnection()->rollback();
231
232
                $this->addError($PaymentResult->getErrors());
233
            }
234
235
            $response = $PaymentResult->getResponse();
236
            if ($response->isRedirection() || $response->getContent()) {
237
                $this->entityManager->flush();
238
239
                return $response;
240
            }
241
        }
242 5
        $this->entityManager->flush();
243
244
        return [
245 5
            'form' => $form->createView(),
246 5
            'Order' => $Order,
247
        ];
248
    }
249
250
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
251
     * 購入処理
252
     *
253
     * @Route("/shopping/order", name="shopping_order")
254
     * @Method("POST")
255
     * @Template("Shopping/index.twig")
256
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
257 6
    public function order(Request $request)
258
    {
259
        // カートチェック
260 6
        $response = $this->forwardToRoute('shopping_check_to_cart');
261 6
        if ($response->isRedirection() || $response->getContent()) {
262
            return $response;
263
        }
264
265
        // 受注の存在チェック
266 6
        $response = $this->forwardToRoute('shopping_exists_order');
267 6
        if ($response->isRedirection() || $response->getContent()) {
268
            return $response;
269
        }
270
271
        // form作成
272
        // FIXME イベントハンドラを外から渡したい
273 6
        $this->forwardToRoute('shopping_create_form');
274
275 6
        $form = $this->parameterBag->get(OrderType::class);
276 6
        $Order = $this->parameterBag->get('Order');
277 6
        $usePoint = $Order->getUsePoint();
278
279 6
        $form->handleRequest($request);
280 6
        $Order->setUsePoint($usePoint);
281
282
        // 受注処理
283 6
        $response = $this->forwardToRoute('shopping_complete_order');
284 6
        if ($response->isRedirection() || $response->getContent()) {
285 6
            return $response;
286
        }
287
288
        log_info('購入チェックエラー', [$Order->getId()]);
289
290
        return [
291
            'form' => $form->createView(),
292
            'Order' => $Order,
293
        ];
294
    }
295
296
    /**
297
     * 支払方法バーリデト
298
     */
299
    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...
300
    {
301
        $data = $form->getData();
302
        $paymentId = $data['payment']->getId();
303
        $shippings = $data['shippings'];
304
        $validCount = count($shippings);
305
        foreach ($shippings as $Shipping) {
306
            $payments = $app['eccube.repository.payment']->findPayments($Shipping->getDelivery());
307
            if ($payments == null) {
308
                continue;
309
            }
310
            foreach ($payments as $payment) {
311
                if ($payment['id'] == $paymentId) {
312
                    $validCount--;
313
                    continue;
314
                }
315
            }
316
        }
317
        if ($validCount == 0) {
318
            return true;
319
        }
320
        $form->get('payment')->addError(new FormError('front.shopping.payment.error'));
321
322
        return false;
323
    }
324
325
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
326
     * 購入完了画面表示
327
     *
328
     * @Route("/shopping/complete", name="shopping_complete")
329
     * @Template("Shopping/complete.twig")
330
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
331 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...
332
    {
333
        // 受注IDを取得
334 1
        $orderId = $this->session->get($this->sessionOrderKey);
335
336 1
        $event = new EventArgs(
337
            [
338 1
                'orderId' => $orderId,
339
            ],
340 1
            $request
341
        );
342 1
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_COMPLETE_INITIALIZE, $event);
343
344 1
        if ($event->getResponse() !== null) {
345
            return $event->getResponse();
346
        }
347
348
        // 受注に関連するセッションを削除
349 1
        $this->session->remove($this->sessionOrderKey);
350 1
        $this->session->remove($this->sessionKey);
351 1
        $this->session->remove($this->sessionCustomerAddressKey);
352
353 1
        log_info('購入処理完了', [$orderId]);
354
355 1
        $hasNextCart = !empty($this->cartService->getCarts());
356
357
        return [
358 1
            'orderId' => $orderId,
359 1
            'hasNextCart' => $hasNextCart,
360
        ];
361
    }
362
363
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$Shipping" missing
Loading history...
364
     * お届け先の設定一覧からの選択
365
     *
366
     * @Route("/shopping/shipping/{id}", name="shopping_shipping", requirements={"id" = "\d+"})
367
     * @Template("Shopping/shipping.twig")
368
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
369
    public function shipping(Request $request, Shipping $Shipping)
370
    {
371
        // カートチェック
372
        $response = $this->forwardToRoute('shopping_check_to_cart');
373
        if ($response->isRedirection() || $response->getContent()) {
374
            return $response;
375
        }
376
377
        // 受注の存在チェック
378
        $response = $this->forwardToRoute('shopping_exists_order');
379
        if ($response->isRedirection() || $response->getContent()) {
380
            return $response;
381
        }
382
383
        // 受注に紐づくShippingかどうかのチェック.
384
        /** @var Order $Order */
385
        $Order = $this->parameterBag->get('Order');
386
        if (!$Order->findShipping($Shipping->getId())) {
387
            throw new NotFoundHttpException();
388
        }
389
390
        $builder = $this->formFactory->createBuilder(CustomerAddressType::class, null, [
391
            'customer' => $this->getUser(),
392
            'shipping' => $Shipping,
393
        ]);
394
395
        $form = $builder->getForm();
396
        $form->handleRequest($request);
397
398
        if ($form->isSubmitted() && $form->isValid()) {
399
            log_info('お届先情報更新開始', [$Shipping->getId()]);
400
401
            /** @var CustomerAddress $CustomerAddress */
402
            $CustomerAddress = $form['addresses']->getData();
403
404
            // お届け先情報を更新
405
            $Shipping->setFromCustomerAddress($CustomerAddress);
406
407
            // 合計金額の再計算
408
            $flowResult = $this->executePurchaseFlow($Order);
409
            if ($flowResult->hasWarning() || $flowResult->hasError()) {
410
                return $this->redirectToRoute('shopping_error');
411
            }
412
413
            // 配送先を更新
414
            $this->entityManager->flush();
415
416
            $event = new EventArgs(
417
                [
418
                    'Order' => $Order,
419
                    'Shipping' => $Shipping,
420
                ],
421
                $request
422
            );
423
            $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_COMPLETE, $event);
424
425
            log_info('お届先情報更新完了', [$Shipping->getId()]);
426
427
            return $this->redirectToRoute('shopping');
428
        }
429
430
        return [
431
            'form' => $form->createView(),
432
            'Customer' => $this->getUser(),
433
            'shippingId' => $Shipping->getId(),
434
        ];
435
    }
436
437
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$id" missing
Loading history...
438
     * お届け先の設定(非会員でも使用する)
439
     *
440
     * @Route("/shopping/shipping_edit/{id}", name="shopping_shipping_edit", requirements={"id" = "\d+"})
441
     * @Template("Shopping/shipping_edit.twig")
442
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
443
    public function shippingEdit(Request $request, $id)
444
    {
445
        // 配送先住所最大値判定
446
        $Customer = $this->getUser();
447
        if ($this->isGranted('IS_AUTHENTICATED_FULLY')) {
448
            $addressCurrNum = count($this->getUser()->getCustomerAddresses());
449
            $addressMax = $this->eccubeConfig['eccube_deliv_addr_max'];
450
            if ($addressCurrNum >= $addressMax) {
451
                throw new NotFoundHttpException(trans('shoppingcontroller.text.error.number_of_address'));
452
            }
453
        }
454
455
        // カートチェック
456
        $response = $this->forwardToRoute('shopping_check_to_cart');
457
        if ($response->isRedirection() || $response->getContent()) {
458
            return $response;
459
        }
460
461
        // 受注の存在チェック
462
        $response = $this->forwardToRoute('shopping_exists_order');
463
        if ($response->isRedirection() || $response->getContent()) {
464
            return $response;
465
        }
466
467
        /** @var Order $Order */
468
        $Order = $this->parameterBag->get('Order');
469
470
        $Shipping = $Order->findShipping($id);
471
        if (!$Shipping) {
472
            throw new NotFoundHttpException(trans('shoppingcontroller.text.error.set_address'));
473
        }
474
        if ($this->isGranted('IS_AUTHENTICATED_FULLY')) {
475
            $Shipping->clearCustomerAddress();
476
        }
477
478
        $CustomerAddress = new CustomerAddress();
479
        if ($this->isGranted('IS_AUTHENTICATED_FULLY')) {
480
            $CustomerAddress->setCustomer($Customer);
481
        } else {
482
            $CustomerAddress->setFromShipping($Shipping);
483
        }
484
485
        $builder = $this->formFactory->createBuilder(ShoppingShippingType::class, $CustomerAddress);
486
487
        $event = new EventArgs(
488
            [
489
                'builder' => $builder,
490
                'Order' => $Order,
491
                'Shipping' => $Shipping,
492
                'CustomerAddress' => $CustomerAddress,
493
            ],
494
            $request
495
        );
496
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_EDIT_INITIALIZE, $event);
497
498
        $form = $builder->getForm();
499
500
        $form->handleRequest($request);
501
502
        if ($form->isSubmitted() && $form->isValid()) {
503
            log_info('お届け先追加処理開始', ['id' => $Order->getId(), 'shipping' => $id]);
504
505
            // 会員の場合、お届け先情報を新規登録
506
            $Shipping->setFromCustomerAddress($CustomerAddress);
507
508
            if ($Customer instanceof Customer) {
509
                $this->entityManager->persist($CustomerAddress);
510
                log_info(
511
                    '新規お届け先登録',
512
                    [
513
                        'id' => $Order->getId(),
514
                        'shipping' => $id,
515
                        'customer address' => $CustomerAddress->getId(),
516
                    ]
517
                );
518
            }
519
520
            // 配送料金の設定
521
            $this->shoppingService->setShippingDeliveryFee($Shipping);
522
523
            // 合計金額の再計算
524
            $flowResult = $this->executePurchaseFlow($Order);
525
            if ($flowResult->hasWarning() || $flowResult->hasError()) {
526
                return $this->redirectToRoute('shopping_error');
527
            }
528
529
            // 配送先を更新
530
            $this->entityManager->flush();
531
532
            $event = new EventArgs(
533
                [
534
                    'form' => $form,
535
                    'Shipping' => $Shipping,
536
                    'CustomerAddress' => $CustomerAddress,
537
                ],
538
                $request
539
            );
540
            $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_EDIT_COMPLETE, $event);
541
542
            log_info('お届け先追加処理完了', ['id' => $Order->getId(), 'shipping' => $id]);
543
544
            return $this->redirectToRoute('shopping');
545
        }
546
547
        return [
548
            'form' => $form->createView(),
549
            'shippingId' => $id,
550
        ];
551
    }
552
553
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$authenticationUtils" missing
Loading history...
554
     * ログイン
555
     *
556
     * @Route("/shopping/login", name="shopping_login")
557
     * @Template("Shopping/login.twig")
558
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
559 2 View Code Duplication
    public function login(Request $request, AuthenticationUtils $authenticationUtils)
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...
560
    {
561 2
        if ($this->isGranted('IS_AUTHENTICATED_FULLY')) {
562
            return $this->redirectToRoute('shopping');
563
        }
564
565
        /* @var $form \Symfony\Component\Form\FormInterface */
566 2
        $builder = $this->formFactory->createNamedBuilder('', CustomerLoginType::class);
567
568 2
        if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
569
            $Customer = $this->getUser();
570
            if ($Customer) {
571
                $builder->get('login_email')->setData($Customer->getEmail());
572
            }
573
        }
574
575 2
        $event = new EventArgs(
576
            [
577 2
                'builder' => $builder,
578
            ],
579 2
            $request
580
        );
581 2
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_LOGIN_INITIALIZE, $event);
582
583 2
        $form = $builder->getForm();
584
585
        return [
586 2
            'error' => $authenticationUtils->getLastAuthenticationError(),
587 2
            'form' => $form->createView(),
588
        ];
589
    }
590
591
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
592
     * 購入エラー画面表示
593
     *
594
     * @Route("/shopping/error", name="shopping_error")
595
     * @Template("Shopping/shopping_error.twig")
596
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
597 1
    public function shoppingError(Request $request)
598
    {
599 1
        $event = new EventArgs(
600 1
            [],
601 1
            $request
602
        );
603 1
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_ERROR_COMPLETE, $event);
604
605 1
        if ($event->getResponse() !== null) {
606
            return $event->getResponse();
607
        }
608
609 1
        return [];
610
    }
611
612
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
613
     * カート画面のチェック
614
     *
615
     * @ForwardOnly
616
     * @Route("/shopping/check_to_cart", name="shopping_check_to_cart")
617
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
618 55
    public function checkToCart(Request $request)
619
    {
620 55
        $Cart = $this->cartService->getCart();
621 55
        if ($Cart && count($Cart->getCartItems()) > 0) {
622 53
            $divide = $request->getSession()->get('cart.divide');
623 53
            if ($divide) {
624
                log_info('種別が異なる商品がカートと結合されたためカート画面にリダイレクト');
625
626
                return $this->redirectToRoute('cart');
627
            }
628
629 53
            return new Response();
630
        }
631 2
        log_info('カートに商品が入っていないためショッピングカート画面にリダイレクト');
632
633
        // カートが存在しない時はエラー
634 2
        return $this->redirectToRoute('cart');
635
    }
636
637
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
638
     * 受注情報を初期化する.
639
     *
640
     * @ForwardOnly
641
     * @Route("/shopping/initialize_order", name="shopping_initialize_order")
642
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
643 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...
644
    {
645
        // 購入処理中の受注情報を取得
646 50
        $Order = $this->shoppingService->getOrder(OrderStatus::PROCESSING);
647
648
        // 初回アクセス(受注情報がない)の場合は, 受注情報を作成
649 50
        if (is_null($Order)) {
650
            // 未ログインの場合, ログイン画面へリダイレクト.
651 34
            if (!$this->isGranted('IS_AUTHENTICATED_FULLY')) {
652
                // 非会員でも一度会員登録されていればショッピング画面へ遷移
653
                $Customer = $this->shoppingService->getNonMember($this->sessionKey);
654
655
                if (is_null($Customer)) {
656
                    log_info('未ログインのためログイン画面にリダイレクト');
657
658
                    return $this->redirectToRoute('shopping_login');
659
                }
660
            } else {
661 34
                $Customer = $this->getUser();
662
            }
663
664
            try {
665
                // 受注情報を作成
666
                //$Order = $app['eccube.service.shopping']->createOrder($Customer);
667 34
                $Order = $this->orderHelper->createProcessingOrder(
668 34
                    $Customer,
669 34
                    $this->cartService->getCart()->getCartItems()
670
                );
671 34
                $this->cartService->setPreOrderId($Order->getPreOrderId());
672 34
                $this->cartService->save();
673
            } catch (CartException $e) {
674
                log_error('初回受注情報作成エラー', [$e->getMessage()]);
675
                $this->addRequestError($e->getMessage());
676
677
                return $this->redirectToRoute('cart');
678
            }
679
680
            // セッション情報を削除
681 34
            $this->session->remove($this->sessionOrderKey);
682
        }
683
684
        // 受注関連情報を最新状態に更新
685 50
        $this->entityManager->refresh($Order);
686
687 50
        $this->parameterBag->set('Order', $Order);
688
689 50
        return new Response();
690
    }
691
692
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
693
     * フォームを作成し, イベントハンドラを設定する
694
     *
695
     * @ForwardOnly
696
     * @Route("/shopping/create_form", name="shopping_create_form")
697
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
698 50
    public function createShoppingForm(Request $request)
699
    {
700 50
        $Order = $this->parameterBag->get('Order');
701
        // フォームの生成
702 50
        $builder = $this->formFactory->createBuilder(OrderType::class, $Order);
703
704 50
        $event = new EventArgs(
705
             [
706 50
                 'builder' => $builder,
707 50
                 'Order' => $Order,
708
             ],
709 50
             $request
710
         );
711 50
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_INDEX_INITIALIZE, $event);
712
713 50
        $form = $builder->getForm();
714
715 50
        $this->parameterBag->set(OrderType::class, $form);
716
717 50
        return new Response();
718
    }
719
720
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
721
     * mode に応じて各変更ページへリダイレクトする.
722
     *
723
     * @ForwardOnly
724
     * @Route("/shopping/redirect_to_change", name="shopping_redirect_to_change")
725
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
726 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...
727
    {
728 20
        $form = $this->parameterBag->get(OrderType::class);
729
730
        // requestのバインド後、Calculatorに再集計させる
731
        //$app['eccube.service.calculate']($Order, $Order->getCustomer())->calculate();
732
733
        // 支払い方法の変更や配送業者の変更があった場合はDBに保持する.
734 20
        if ($form->isSubmitted() && $form->isValid()) {
735
            // POSTされたデータをDBに保持.
736 8
            $this->entityManager->flush();
737
738 8
            $mode = $form['mode']->getData();
739 8
            switch ($mode) {
740 7
                case 'shipping_change':
741
                    // お届け先設定一覧へリダイレクト
742 1
                    $param = $form['param']->getData();
743
744 1
                    return $this->redirectToRoute('shopping_shipping', ['id' => $param]);
745 7
                case 'shipping_edit_change':
746
                    // お届け先設定一覧へリダイレクト
747
                    $param = $form['param']->getData();
748
749
                    return $this->redirectToRoute('shopping_shipping_edit', ['id' => $param]);
750 7
                case 'shipping_multiple_change':
751
                    // 複数配送設定へリダイレクト
752
                    return $this->redirectToRoute('shopping_shipping_multiple');
753 7
                case 'payment':
754 7
                case 'delivery':
755
                default:
756 7
                    return $this->redirectToRoute('shopping');
757
            }
758
        }
759
760 12
        return new Response();
761
    }
762
763
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
764
     * 受注の存在チェック
765
     *
766
     * @ForwardOnly
767
     * @Route("/shopping/exists_order", name="shopping_exists_order")
768
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
769 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...
770
    {
771 26
        $Order = $this->shoppingService->getOrder(OrderStatus::PROCESSING);
772 26
        if (!$Order) {
773
            log_info('購入処理中の受注情報がないため購入エラー');
774
            $this->addError('front.shopping.order.error');
775
776
            return $this->redirectToRoute('shopping_error');
777
        }
778 26
        $this->parameterBag->set('Order', $Order);
779
780 26
        return new Response();
781
    }
782
783
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
784
     * 受注完了処理
785
     *
786
     * @ForwardOnly
787
     * @Route("/shopping/complete_order", name="shopping_complete_order")
788
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
789 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...
790
    {
791 6
        $form = $this->parameterBag->get(OrderType::class);
792
793 6
        if ($form->isSubmitted() && $form->isValid()) {
794
            /** @var Order $Order */
795 6
            $Order = $form->getData();
796 6
            log_info('購入処理開始', [$Order->getId()]);
797
798
            // トランザクション制御
799 6
            $em = $this->entityManager;
800 6
            $em->getConnection()->beginTransaction();
801
            try {
802
                // お問い合わせ、配送時間などのフォーム項目をセット
803
                // FormTypeで更新されるため不要
804
                //$app['eccube.service.shopping']->setFormData($Order, $data);
805
806 6
                $flowResult = $this->executePurchaseFlow($Order);
807 6
                if ($flowResult->hasWarning() || $flowResult->hasError()) {
808
                    // TODO エラーメッセージ
809
                    throw new ShoppingException();
810
                }
811
                try {
812 6
                    $this->purchaseFlow->purchase($Order, new PurchaseContext($Order, $Order->getCustomer())); // TODO 変更前の Order を渡す必要がある?
813
                } catch (PurchaseException $e) {
0 ignored issues
show
Bug introduced by
The class Eccube\Controller\PurchaseException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
814
                    $this->addError($e->getMessage(), 'front');
815
                }
816
817
                // 購入処理
818 6
                $this->shoppingService->processPurchase($Order); // XXX フロント画面に依存してるので管理画面では使えない
0 ignored issues
show
Deprecated Code introduced by
The method Eccube\Service\ShoppingService::processPurchase() has been deprecated with message: PurchaseFlow::purchase() を使用してください

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
819
820
                // Order も引数で渡すのがベスト??
821 6
                $paymentService = $this->createPaymentService($Order);
822 6
                $paymentMethod = $this->createPaymentMethod($Order, $form);
823
824
                // 必要に応じて別のコントローラへ forward or redirect(移譲)
825 6
                $dispatcher = $paymentService->dispatch($paymentMethod); // 決済処理中.
826
                // 一旦、決済処理中になった後は、購入処理中に戻せない。キャンセル or 購入完了の仕様とする
827
                // ステータス履歴も保持しておく? 在庫引き当ての仕様もセットで。
828 6
                if ($dispatcher instanceof PaymentDispatcher) {
829
                    $response = $dispatcher->getResponse();
830
                    if ($response->isRedirection() || $response->getContent()) {
831
                        return $response;
832
                    }
833
834
                    if ($dispatcher->isForward()) {
835
                        return $this->forwardToRoute($dispatcher->getRoute(), $dispatcher->getPathParameters(), $dispatcher->getQueryParameters());
836
                    } else {
837
                        return $this->redirectToRoute($dispatcher->getRoute(), $dispatcher->getQueryParameters());
838
                    }
839
                }
840
841
                // 決済実行
842 6
                $response = $this->forwardToRoute('shopping_do_checkout_order');
843 6
                if ($response->isRedirection() || $response->getContent()) {
844
                    return $response;
845
                }
846
847 6
                $this->entityManager->flush();
848 6
                $this->entityManager->getConnection()->commit();
849
850 6
                log_info('購入処理完了', [$Order->getId()]);
851
            } catch (ShoppingException $e) {
852
                log_error('購入エラー', [$e->getMessage()]);
853
854
                $this->entityManager->getConnection()->rollback();
855
856
                $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...
857
                $this->addError($e->getMessage());
858
859
                return $this->redirectToRoute('shopping_error');
860
            } catch (\Exception $e) {
861
                log_error('予期しないエラー', [$e->getMessage()]);
862
863
                $this->entityManager->getConnection()->rollback();
864
865
                $this->addError('front.shopping.system.error');
866
867
                return $this->redirectToRoute('shopping_error');
868
            }
869
870 6
            return $this->forwardToRoute('shopping_after_complete');
871
        }
872
873
        return new Response();
874
    }
875
876
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
877
     * 決済完了処理
878
     *
879
     * @ForwardOnly
880
     * @Route("/shopping/do_checkout_order", name="shopping_do_checkout_order")
881
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
882 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...
883
    {
884 6
        $form = $this->parameterBag->get(OrderType::class);
885 6
        $Order = $this->parameterBag->get('Order');
886
887 6
        $paymentService = $this->createPaymentService($Order);
888 6
        $paymentMethod = $this->createPaymentMethod($Order, $form);
889
890
        // 決済実行
891 6
        $PaymentResult = $paymentService->doCheckout($paymentMethod);
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()->save();
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 createPaymentService(Order $Order)
962
    {
963 6
        $serviceClass = $Order->getPayment()->getServiceClass();
964 6
        $paymentService = new $serviceClass($this->container->get('request_stack')); // コンテナから取得したい
965
966 6
        return $paymentService;
967
    }
968
969 6
    private function createPaymentMethod(Order $Order, $form)
970
    {
971 6
        $methodClass = $Order->getPayment()->getMethodClass();
972
973
        // TODO Plugin/Xxx/Resouce/config/services.yamlでpublicにする必要がある
974 6
        $PaymentMethod = $this->container->get($methodClass);
975 6
        $PaymentMethod->setOrder($Order);
976 6
        $PaymentMethod->setFormType($form);
977
978 6
        return $PaymentMethod;
979
    }
980
}
981