Failed Conditions
Pull Request — experimental/sf (#3240)
by Kentaro
43:45
created

ShoppingController::createPaymentService()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 7
rs 10
c 0
b 0
f 0
ccs 4
cts 4
cp 1
crap 1
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\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
    /**
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...
89
     */
90 59
    public function __construct(
91
        BaseInfo $BaseInfo,
92
        OrderHelper $orderHelper,
93
        CartService $cartService,
94
        ShoppingService $shoppingService,
95
        CustomerAddressRepository $customerAddressRepository,
96
        ParameterBag $parameterBag
97
    ) {
98 59
        $this->BaseInfo = $BaseInfo;
99 59
        $this->orderHelper = $orderHelper;
100 59
        $this->cartService = $cartService;
101 59
        $this->shoppingService = $shoppingService;
102 59
        $this->customerAddressRepository = $customerAddressRepository;
103 59
        $this->parameterBag = $parameterBag;
104
    }
105
106
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
107
     * 購入画面表示
108
     *
109
     * @Route("/shopping", name="shopping")
110
     * @Template("Shopping/index.twig")
111
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
112 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...
113
    {
114
        // カートチェック
115 51
        $response = $this->forwardToRoute('shopping_check_to_cart');
116 51
        if ($response->isRedirection() || $response->getContent()) {
117 1
            return $response;
118
        }
119
120
        // 受注情報を初期化
121 50
        $response = $this->forwardToRoute('shopping_initialize_order');
122 50
        if ($response->isRedirection() || $response->getContent()) {
123
            return $response;
124
        }
125
126
        /** @var Order $Order */
127 50
        $Order = $this->parameterBag->get('Order');
128
129
        // 単価集計
130 50
        $flowResult = $this->executePurchaseFlow($Order);
131
132
        // 明細が丸められる場合に, カートから注文画面へ遷移できなくなるため, 集計の結果を保存する
133 50
        $this->entityManager->flush();
134
135
        // フォームを生成する
136 50
        $this->forwardToRoute('shopping_create_form');
137
138 50
        if ($flowResult->hasWarning() || $flowResult->hasError()) {
139 10
            return $this->redirectToRoute('cart');
140
        }
141
142 45
        $form = $this->parameterBag->get(OrderType::class);
143
144
        return [
145 45
            'form' => $form->createView(),
146 45
            'Order' => $Order,
147
        ];
148
    }
149
150
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
151
     * 購入確認画面から, 他の画面へのリダイレクト.
152
     * 配送業者や支払方法、お問い合わせ情報をDBに保持してから遷移する.
153
     *
154
     * @Route("/shopping/redirect", name="shopping_redirect_to")
155
     * @Template("Shopping/index.twig")
156
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
157 20
    public function redirectTo(Request $request)
158
    {
159
        // カートチェック
160 20
        $response = $this->forwardToRoute('shopping_check_to_cart');
161 20
        if ($response->isRedirection() || $response->getContent()) {
162
            return $response;
163
        }
164
165
        // 受注の存在チェック
166 20
        $response = $this->forwardToRoute('shopping_exists_order');
167 20
        if ($response->isRedirection() || $response->getContent()) {
168
            return $response;
169
        }
170
171
        // フォームの生成
172 20
        $this->forwardToRoute('shopping_create_form');
173 20
        $form = $this->parameterBag->get(OrderType::class);
174 20
        $form->handleRequest($request);
175
176
        // 各種変更ページへリダイレクトする
177 20
        $response = $this->forwardToRoute('shopping_redirect_to_change');
178 20
        if ($response->isRedirection() || $response->getContent()) {
179 8
            return $response;
180
        }
181 12
        $form = $this->parameterBag->get(OrderType::class);
182 12
        $Order = $this->parameterBag->get('Order');
183
184
        return [
185 12
            'form' => $form->createView(),
186 12
            'Order' => $Order,
187
        ];
188
    }
189
190
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
191
     * 購入処理
192
     *
193
     * @Route("/shopping/confirm", name="shopping_confirm")
194
     * @Method("POST")
195
     * @Template("Shopping/confirm.twig")
196
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
197 5
    public function confirm(Request $request)
198
    {
199
        // カートチェック
200 5
        $response = $this->forwardToRoute('shopping_check_to_cart');
201 5
        if ($response->isRedirection() || $response->getContent()) {
202
            return $response;
203
        }
204
205
        // 受注の存在チェック
206 5
        $response = $this->forwardToRoute('shopping_exists_order');
207 5
        if ($response->isRedirection() || $response->getContent()) {
208
            return $response;
209
        }
210
211
        // フォームの生成
212 5
        $this->forwardToRoute('shopping_create_form');
213 5
        $form = $this->parameterBag->get(OrderType::class);
214 5
        $form->handleRequest($request);
215
216 5
        $form = $this->parameterBag->get(OrderType::class);
217 5
        $Order = $this->parameterBag->get('Order');
218
219 5
        $flowResult = $this->executePurchaseFlow($Order);
220 5
        if ($flowResult->hasWarning() || $flowResult->hasError()) {
221
            return $this->redirectToRoute('shopping_error');
222
        }
223
224 5
        $paymentMethod = $this->createPaymentMethod($Order, $form);
225
226 5
        $PaymentResult = $paymentMethod->verify();
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 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
                    if ($response->isRedirection() || $response->getContent()) {
829
                        return $response;
830
                    }
831
832
                    if ($dispatcher->isForward()) {
833
                        return $this->forwardToRoute($dispatcher->getRoute(), $dispatcher->getPathParameters(), $dispatcher->getQueryParameters());
834
                    } else {
835
                        return $this->redirectToRoute($dispatcher->getRoute(), array_merge($dispatcher->getPathParameters(), $dispatcher->getQueryParameters()));
836
                    }
837
                }
838
839
                // 決済実行
840 6
                $response = $this->forwardToRoute('shopping_do_checkout_order');
841 6
                if ($response->isRedirection() || $response->getContent()) {
842
                    return $response;
843
                }
844
845 6
                $this->entityManager->flush();
846 6
                $this->entityManager->getConnection()->commit();
847
848 6
                log_info('購入処理完了', [$Order->getId()]);
849
            } catch (ShoppingException $e) {
850
                log_error('購入エラー', [$e->getMessage()]);
851
852
                $this->entityManager->getConnection()->rollback();
853
854
                $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...
855
                $this->addError($e->getMessage());
856
857
                return $this->redirectToRoute('shopping_error');
858
            } catch (\Exception $e) {
859
                log_error('予期しないエラー', [$e->getMessage()]);
860
861
                $this->entityManager->getConnection()->rollback();
862
863
                $this->addError('front.shopping.system.error');
864
865
                return $this->redirectToRoute('shopping_error');
866
            }
867
868 6
            return $this->forwardToRoute('shopping_after_complete');
869
        }
870
871
        return new Response();
872
    }
873
874
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
875
     * 決済完了処理
876
     *
877
     * @ForwardOnly
878
     * @Route("/shopping/do_checkout_order", name="shopping_do_checkout_order")
879
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
880 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...
881
    {
882 6
        $form = $this->parameterBag->get(OrderType::class);
883 6
        $Order = $this->parameterBag->get('Order');
884
885 6
        $paymentMethod = $this->createPaymentMethod($Order, $form);
886
887
        // 決済実行
888 6
        $PaymentResult = $paymentMethod->checkout();
889 6
        $response = $PaymentResult->getResponse();
890 6
        if ($response && ($response->isRedirection() || $response->getContent())) {
891
            return $response;
892
        }
893
894 6
        if (!$PaymentResult->isSuccess()) {
895
            $this->entityManager->getConnection()->rollback();
896
897
            $this->addError($PaymentResult->getErrors());
898
        }
899
900 6
        return new Response();
901
    }
902
903
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
904
     * 受注完了の後処理
905
     *
906
     * @ForwardOnly
907
     * @Route("/shopping/after_complete", name="shopping_after_complete")
908
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
909 6
    public function afterComplete(Request $request)
910
    {
911 6
        $form = $this->parameterBag->get(OrderType::class);
912 6
        $Order = $this->parameterBag->get('Order');
913
914
        // カート削除
915 6
        $this->cartService->clear()->save();
916
917 6
        $event = new EventArgs(
918
            [
919 6
                'form' => $form,
920 6
                'Order' => $Order,
921
            ],
922 6
            $request
923
        );
924 6
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_CONFIRM_PROCESSING, $event);
925
926 6 View Code Duplication
        if ($event->getResponse() !== null) {
927
            log_info('イベントレスポンス返却', [$Order->getId()]);
928
929
            return $event->getResponse();
930
        }
931
932
        // 受注IDをセッションにセット
933 6
        $this->session->set($this->sessionOrderKey, $Order->getId());
934
935
        // メール送信
936 6
        $MailHistory = $this->shoppingService->sendOrderMail($Order);
937
938 6
        $event = new EventArgs(
939
            [
940 6
                'form' => $form,
941 6
                'Order' => $Order,
942 6
                'MailHistory' => $MailHistory,
943
            ],
944 6
            $request
945
        );
946 6
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_CONFIRM_COMPLETE, $event);
947
948 6 View Code Duplication
        if ($event->getResponse() !== null) {
949
            log_info('イベントレスポンス返却', [$Order->getId()]);
950
951
            return $event->getResponse();
952
        }
953
954
        // 完了画面表示
955 6
        return $this->redirectToRoute('shopping_complete');
956
    }
957
958 6
    private function createPaymentMethod(Order $Order, FormInterface $form)
959
    {
960 6
        $PaymentMethod = $this->container->get($Order->getPayment()->getMethodClass());
961 6
        $PaymentMethod->setOrder($Order);
962 6
        $PaymentMethod->setFormType($form);
963
964 6
        return $PaymentMethod;
965
    }
966
}
967