Completed
Push — experimental/3.1 ( 894a79...d11c60 )
by chihiro
129:12 queued 121:53
created

ShoppingController::createForm()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1.0938

Importance

Changes 0
Metric Value
cc 1
eloc 12
nc 1
nop 2
dl 0
loc 21
ccs 6
cts 11
cp 0.5455
crap 1.0938
rs 9.3142
c 0
b 0
f 0
1
<?php
2
/*
3
 * This file is part of EC-CUBE
4
 *
5
 * Copyright(c) 2000-2015 LOCKON CO.,LTD. All Rights Reserved.
6
 *
7
 * http://www.lockon.co.jp/
8
 *
9
 * This program is free software; you can redistribute it and/or
10
 * modify it under the terms of the GNU General Public License
11
 * as published by the Free Software Foundation; either version 2
12
 * of the License, or (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22
 */
23
24
25
namespace Eccube\Controller;
26
27
use Doctrine\ORM\EntityManager;
28
use Eccube\Annotation\ForwardOnly;
29
use Eccube\Annotation\Inject;
30
use Eccube\Application;
31
use Eccube\Entity\BaseInfo;
32
use Eccube\Entity\Customer;
33
use Eccube\Entity\CustomerAddress;
34
use Eccube\Entity\Order;
35
use Eccube\Event\EccubeEvents;
36
use Eccube\Event\EventArgs;
37
use Eccube\Exception\CartException;
38
use Eccube\Exception\ShoppingException;
39
use Eccube\Form\Type\Front\CustomerLoginType;
40
use Eccube\Form\Type\Front\ShoppingShippingType;
41
use Eccube\Form\Type\Shopping\OrderType;
42
use Eccube\Repository\CustomerAddressRepository;
43
use Eccube\Service\CartService;
44
use Eccube\Service\OrderHelper;
45
use Eccube\Service\ShoppingService;
46
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
47
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
48
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
49
use Symfony\Component\EventDispatcher\EventDispatcher;
50
use Symfony\Component\Form\FormFactory;
51
use Symfony\Component\HttpFoundation\ParameterBag;
52
use Symfony\Component\HttpFoundation\Request;
53
use Symfony\Component\HttpFoundation\Response;
54
use Symfony\Component\HttpFoundation\Session\Session;
55
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
56
57
/**
58
 * @Route(service=ShoppingController::class)
59
 */
60
class ShoppingController extends AbstractShoppingController
61
{
62
    /**
63
     * @Inject(BaseInfo::class)
64
     * @var BaseInfo
65
     */
66
    protected $BaseInfo;
67
68
    /**
69
     * @Inject(OrderHelper::class)
70
     * @var OrderHelper
71
     */
72
    protected $orderHelper;
73
74
    /**
75
     * @Inject(CartService::class)
76
     * @var CartService
77
     */
78
    protected $cartService;
79
80
    /**
81
     * @Inject("form.factory")
82
     * @var FormFactory
83
     */
84
    protected $formFactory;
85
86
    /**
87
     * @Inject("orm.em")
88
     * @var EntityManager
89
     */
90
    protected $entityManager;
91
92
    /**
93
     * @Inject("config")
94
     * @var array
95
     */
96
    protected $appConfig;
97
98
    /**
99
     * @Inject(ShoppingService::class)
100
     * @var ShoppingService
101
     */
102
    protected $shoppingService;
103
104
    /**
105
     * @Inject(CustomerAddressRepository::class)
106
     * @var CustomerAddressRepository
107
     */
108
    protected $customerAddressRepository;
109
110
    /**
111
     * @Inject("eccube.event.dispatcher")
112
     * @var EventDispatcher
113
     */
114
    protected $eventDispatcher;
115
116
    /**
117
     * @Inject("session")
118
     * @var Session
119
     */
120
    protected $session;
121
122
    /**
123
     * @Inject("request_scope")
124
     * @var ParameterBag
125
     */
126
    protected $parameterBag;
127
128
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
129
     * 購入画面表示
130
     *
131
     * @Route("/shopping", name="shopping")
132
     * @Template("Shopping/index.twig")
133
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
134 13
    public function index(Application $app, 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...
135
    {
136
        // カートチェック
137 13
        $response = $app->forward($app->path("shopping_check_to_cart"));
138 13
        if ($response->isRedirection() || $response->getContent()) {
139 3
            return $response;
140
        }
141
142
        // 受注情報を初期化
143 10
        $response = $app->forward($app->path("shopping_initialize_order"));
144 10
        if ($response->isRedirection() || $response->getContent()) {
145
            return $response;
146
        }
147
148
        /** @var Order $Order */
149 10
        $Order = $this->parameterBag->get('Order');
150
151
        // 単価集計
152 10
        $flowResult = $this->executePurchaseFlow($app, $Order);
153
154
        // フォームを生成する
155 10
        $app->forward($app->path("shopping_create_form"));
156
157 10
        if ($flowResult->hasWarning() || $flowResult->hasError()) {
158
            return $app->redirect($app->url('cart'));
159
        }
160
161
        // 複数配送の場合、エラーメッセージを一度だけ表示
162 10
        $app->forward($app->path("shopping_handle_multiple_errors"));
163 10
        $form = $this->parameterBag->get(OrderType::class);
164
165
        return [
166 10
            'form' => $form->createView(),
167 10
            'Order' => $Order,
168
        ];
169
    }
170
171
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
172
     * 購入確認画面から, 他の画面へのリダイレクト.
173
     * 配送業者や支払方法、お問い合わせ情報をDBに保持してから遷移する.
174
     *
175
     * @Route("/shopping/redirect", name="shopping_redirect_to")
176
     * @Template("Shopping/index.twig")
177
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
178 5 View Code Duplication
    public function redirectTo(Application $app, Request $request)
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...
179
    {
180
        // カートチェック
181 5
        $response = $app->forward($app->path("shopping_check_to_cart"));
182 5
        if ($response->isRedirection() || $response->getContent()) {
183
            return $response;
184
        }
185
186
        // 受注の存在チェック
187 5
        $response = $app->forward($app->path("shopping_exists_order"));
188 5
        if ($response->isRedirection() || $response->getContent()) {
189
            return $response;
190
        }
191
192
        // フォームの生成
193 5
        $app->forward($app->path("shopping_create_form"));
194 5
        $form = $this->parameterBag->get(OrderType::class);
195 5
        $form->handleRequest($request);
196
197
        // 各種変更ページへリダイレクトする
198 5
        $response = $app->forward($app->path("shopping_redirect_to_change"));
199 5
        if ($response->isRedirection() || $response->getContent()) {
200 2
            return $response;
201
        }
202 3
        $form = $this->parameterBag->get(OrderType::class);
203 3
        $Order = $this->parameterBag->get('Order');
204
205
        return [
206 3
            'form' => $form->createView(),
207 3
            'Order' => $Order,
208
        ];
209
    }
210
211
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
212
     * 購入処理
213
     *
214
     * @Route("/shopping/confirm", name="shopping_confirm")
215
     * @Method("POST")
216
     * @Template("Shopping/confirm.twig")
217
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
218 2 View Code Duplication
    public function confirm(Application $app, Request $request)
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...
219
    {
220
        // カートチェック
221 2
        $response = $app->forward($app->path("shopping_check_to_cart"));
222 2
        if ($response->isRedirection() || $response->getContent()) {
223
            return $response;
224
        }
225
226
        // 受注の存在チェック
227 2
        $response = $app->forward($app->path("shopping_exists_order"));
228 2
        if ($response->isRedirection() || $response->getContent()) {
229
            return $response;
230
        }
231
232
        // フォームの生成
233
        $app->forward($app->path("shopping_create_form"));
234 2
        $form = $this->parameterBag->get(OrderType::class);
235
        $form->handleRequest($request);
236 2
237 2
        $form = $this->parameterBag->get(OrderType::class);
238
        $Order = $this->parameterBag->get('Order');
239 2
240
        $flowResult = $this->executePurchaseFlow($app, $Order);
241
        if ($flowResult->hasWarning() || $flowResult->hasError()) {
242 2
            return $app->redirect($app->url('shopping_error'));
243 2
        }
244 2
245
        return [
246
            'form' => $form->createView(),
247
            'Order' => $Order,
248
        ];
249
    }
250
251
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
252
     * 購入処理
253
     *
254
     * @Route("/shopping/order", name="shopping_order")
255
     * @Method("POST")
256
     * @Template("Shopping/index.twig")
257
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
258 View Code Duplication
    public function order(Application $app, Request $request)
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...
259
    {
260
        // カートチェック
261
        $response = $app->forward($app->path("shopping_check_to_cart"));
262 1
        if ($response->isRedirection() || $response->getContent()) {
263
            return $response;
264
        }
265 1
266
        // 受注の存在チェック
267 1
        $response = $app->forward($app->path("shopping_exists_order"));
268
        if ($response->isRedirection() || $response->getContent()) {
269 1
            return $response;
270
        }
271 1
272
        // form作成
273 1
        // FIXME イベントハンドラを外から渡したい
274
        $app->forward($app->path("shopping_create_form"));
275 1
276
        $form = $this->parameterBag->get(OrderType::class);
277
        $Order = $this->parameterBag->get('Order');
278
279
        $form->handleRequest($request);
280 1
281 1
        // 受注処理
282
        $response = $app->forward($app->path("shopping_complete_order"));
283
        if ($response->isRedirection() || $response->getContent()) {
284 1
            return $response;
285 1
        }
286
287 1
        log_info('購入チェックエラー', array($Order->getId()));
288
289
        return [
290 1
            'form' => $form->createView(),
291
            'Order' => $Order,
292
        ];
293
    }
294
295
296
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
297
     * 購入完了画面表示
298
     *
299
     * @Route("/shopping/complete", name="shopping_complete")
300 2
     * @Template("Shopping/complete.twig")
301
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
302
    public function complete(Application $app, Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $app 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...
303 2
    {
304 2
        // 受注IDを取得
305
        $orderId = $this->session->get($this->sessionOrderKey);
306
307
        $event = new EventArgs(
308 2
            array(
309 2
                'orderId' => $orderId,
310
            ),
311 2
            $request
312
        );
313 2
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_COMPLETE_INITIALIZE, $event);
314
315
        if ($event->getResponse() !== null) {
316 2
            return $event->getResponse();
317 2
        }
318
319
        // 受注に関連するセッションを削除
320
        $this->session->remove($this->sessionOrderKey);
321
        $this->session->remove($this->sessionMultipleKey);
322
323
        // 非会員用セッション情報を空の配列で上書きする(プラグイン互換性保持のために削除はしない)
324
        $this->session->set($this->sessionKey, array());
325
        $this->session->set($this->sessionCustomerAddressKey, array());
326
327
        log_info('購入処理完了', array($orderId));
328
329
        $hasNextCart = !empty($this->cartService->getCarts());
330
331
        return [
332
            'orderId' => $orderId,
333
            'hasNextCart' => $hasNextCart,
334
        ];
335
    }
336
337
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$id" missing
Loading history...
338
     * お届け先の設定一覧からの選択
339
     *
340
     * @Route("/shopping/shipping/{id}", name="shopping_shipping", requirements={"id" = "\d+"})
341
     * @Template("Shopping/shipping.twig")
342
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
343
    public function shipping(Application $app, Request $request, $id)
344
    {
345
        // カートチェック
346
        $response = $app->forward($app->path("shopping_check_to_cart"));
347
        if ($response->isRedirection() || $response->getContent()) {
348
            return $response;
349
        }
350
351
        if ('POST' === $request->getMethod()) {
352
            $address = $request->get('address');
353
354
            if (is_null($address)) {
355
                // 選択されていなければエラー
356
                log_info('お届け先入力チェックエラー');
357
358
                return [
359
                    'Customer' => $app->user(),
360
                    'shippingId' => $id,
361
                    'error' => true,
362
                ];
363
            }
364
365
            // 選択されたお届け先情報を取得
366
            $CustomerAddress = $this->customerAddressRepository->findOneBy(
367
                array(
368
                    'Customer' => $app->user(),
369
                    'id' => $address,
370
                )
371
            );
372
            if (is_null($CustomerAddress)) {
373
                throw new NotFoundHttpException('選択されたお届け先住所が存在しない');
374
            }
375
376
            /** @var Order $Order */
377
            $Order = $this->shoppingService->getOrder($this->appConfig['order_processing']);
378
            if (!$Order) {
379
                log_info('購入処理中の受注情報がないため購入エラー');
380 1
                $app->addError('front.shopping.order.error');
381 1
382
                return $app->redirect($app->url('shopping_error'));
383
            }
384
385
            $Shipping = $Order->findShipping($id);
386
            if (!$Shipping) {
387
                throw new NotFoundHttpException('お届け先情報が存在しない');
388
            }
389
390
            log_info('お届先情報更新開始', array($Shipping->getId()));
391
392
            // お届け先情報を更新
393
            $Shipping->setFromCustomerAddress($CustomerAddress);
394
395
            // 配送料金の設定
396
            $this->shoppingService->setShippingDeliveryFee($Shipping);
397
398
399
            // 合計金額の再計算
400
            $flowResult = $this->executePurchaseFlow($app, $Order);
401
            if ($flowResult->hasWarning() || $flowResult->hasError()) {
402
                return $app->redirect($app->url('shopping_error'));
403
            }
404
405
            // 配送先を更新
406
            $this->entityManager->flush();
407
408
            $event = new EventArgs(
409
                array(
410
                    'Order' => $Order,
411
                    'shippingId' => $id,
412
                ),
413
                $request
414
            );
415
            $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_COMPLETE, $event);
416
417
            log_info('お届先情報更新完了', array($Shipping->getId()));
418
419
            return $app->redirect($app->url('shopping'));
420
        }
421
422
        return [
423
            'Customer' => $app->user(),
424
            'shippingId' => $id,
425
            'error' => false,
426
        ];
427
    }
428
429
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$id" missing
Loading history...
430
     * お届け先の設定(非会員でも使用する)
431
     *
432
     * @Route("/shopping/shipping_edit/{id}", name="shopping_shipping_edit", requirements={"id" = "\d+"})
433
     * @Template("Shopping/shipping_edit.twig")
434
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
435
    public function shippingEdit(Application $app, Request $request, $id)
436
    {
437
        // 配送先住所最大値判定
438
        $Customer = $app->user();
439 View Code Duplication
        if ($app->isGranted('IS_AUTHENTICATED_FULLY')) {
440
            $addressCurrNum = count($app->user()->getCustomerAddresses());
441
            $addressMax = $this->appConfig['deliv_addr_max'];
442
            if ($addressCurrNum >= $addressMax) {
443
                throw new NotFoundHttpException('配送先住所最大数エラー');
444
            }
445
        }
446
447
        // カートチェック
448
        $response = $app->forward($app->path("shopping_check_to_cart"));
449
        if ($response->isRedirection() || $response->getContent()) {
450
            return $response;
451
        }
452
453
        // 受注の存在チェック
454
        $response = $app->forward($app->path("shopping_exists_order"));
455
        if ($response->isRedirection() || $response->getContent()) {
456
            return $response;
457
        }
458
459
        /** @var Order $Order */
460
        $Order = $this->parameterBag->get('Order');
461
462
        $Shipping = $Order->findShipping($id);
463
        if (!$Shipping) {
464
            throw new NotFoundHttpException('設定されている配送先が存在しない');
465
        }
466
        if ($app->isGranted('IS_AUTHENTICATED_FULLY')) {
467
            $Shipping->clearCustomerAddress();
468
        }
469
470
        $CustomerAddress = new CustomerAddress();
471
        if ($app->isGranted('IS_AUTHENTICATED_FULLY')) {
472
            $CustomerAddress->setCustomer($Customer);
473
        } else {
474
            $CustomerAddress->setFromShipping($Shipping);
475
        }
476
477
        $builder = $this->formFactory->createBuilder(ShoppingShippingType::class, $CustomerAddress);
478
479
        $event = new EventArgs(
480
            array(
481
                'builder' => $builder,
482
                'Order' => $Order,
483
                'Shipping' => $Shipping,
484
                'CustomerAddress' => $CustomerAddress,
485
            ),
486
            $request
487
        );
488
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_EDIT_INITIALIZE, $event);
489
490
        $form = $builder->getForm();
491
492
        $form->handleRequest($request);
493
494
        if ($form->isSubmitted() && $form->isValid()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
495
496
            log_info('お届け先追加処理開始', array('id' => $Order->getId(), 'shipping' => $id));
497
498
            // 会員の場合、お届け先情報を新規登録
499
            $Shipping->setFromCustomerAddress($CustomerAddress);
500
501
            if ($Customer instanceof Customer) {
502
                $this->entityManager->persist($CustomerAddress);
503
                log_info(
504
                    '新規お届け先登録',
505
                    array(
506
                        'id' => $Order->getId(),
507
                        'shipping' => $id,
508
                        'customer address' => $CustomerAddress->getId(),
509 2
                    )
510
                );
511 2
            }
512 2
513
            // 配送料金の設定
514
            $this->shoppingService->setShippingDeliveryFee($Shipping);
515
516
            // 合計金額の再計算
517
            $flowResult = $this->executePurchaseFlow($app, $Order);
518
            if ($flowResult->hasWarning() || $flowResult->hasError()) {
519
                return $app->redirect($app->url('shopping_error'));
520
            }
521
522
            // 配送先を更新
523
            $this->entityManager->flush();
524
525
            $event = new EventArgs(
526
                array(
527
                    'form' => $form,
528
                    'Shipping' => $Shipping,
529
                    'CustomerAddress' => $CustomerAddress,
530
                ),
531
                $request
532
            );
533
            $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_EDIT_COMPLETE, $event);
534
535
            log_info('お届け先追加処理完了', array('id' => $Order->getId(), 'shipping' => $id));
536
537
            return $app->redirect($app->url('shopping'));
538
        }
539
540
        return [
541
            'form' => $form->createView(),
542
            'shippingId' => $id,
543
        ];
544
    }
545
546
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
547
     * ログイン
548
     *
549
     * @Route("/shopping/login", name="shopping_login")
550
     * @Template("Shopping/login.twig")
551 1
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
552
    public function login(Application $app, Request $request)
553 1
    {
554 1
        if (!$this->cartService->isLocked()) {
555 1
            return $app->redirect($app->url('cart'));
556
        }
557 1
558
        if ($app->isGranted('IS_AUTHENTICATED_FULLY')) {
559 1
            return $app->redirect($app->url('shopping'));
560
        }
561
562
        /* @var $form \Symfony\Component\Form\FormInterface */
563 1
        $builder = $this->formFactory->createNamedBuilder('', CustomerLoginType::class);
564
565 View Code Duplication
        if ($app->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
566
            $Customer = $app->user();
567
            if ($Customer) {
568
                $builder->get('login_email')->setData($Customer->getEmail());
569
            }
570
        }
571
572 17
        $event = new EventArgs(
573
            array(
574
                'builder' => $builder,
575 17
            ),
576 3
            $request
577
        );
578
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_LOGIN_INITIALIZE, $event);
579 3
580
        $form = $builder->getForm();
581
582
        return [
583 14
            'error' => $app['security.last_error']($request),
584 1
            'form' => $form->createView(),
585
        ];
586
    }
587 1
588
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
589
     * 購入エラー画面表示
590 13
     *
591
     * @Route("/shopping/error", name="shopping_error")
592
     * @Template("Shopping/shopping_error.twig")
593
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
594
    public function shoppingError(Application $app, Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $app 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...
595
    {
596
        $event = new EventArgs(
597
            array(),
598
            $request
599 10
        );
600
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_ERROR_COMPLETE, $event);
601
602 10
        if ($event->getResponse() !== null) {
603
            return $event->getResponse();
604
        }
605 10
606
        return [];
607 10
    }
608
609 2
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
610
     * カート画面のチェック
611 2
     *
612
     * @ForwardOnly
613
     * @Route("/shopping/check_to_cart", name="shopping_check_to_cart")
614 2
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
615
    public function checkToCart(Application $app, 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...
616
    {
617 8
        // カートチェック
618
        if (!$this->cartService->isLocked()) {
619
            log_info('カートが存在しません');
620
621
            // カートが存在しない、カートがロックされていない時はエラー
622
            return $app->redirect($app->url('cart'));
623 10
        }
624 10
625 10
        // カートチェック
626 10
        if (count($this->cartService->getCart()->getCartItems()) <= 0) {
627
            log_info('カートに商品が入っていないためショッピングカート画面にリダイレクト');
628 10
629 10
            // カートが存在しない時はエラー
630
            return $app->redirect($app->url('cart'));
631
        }
632
633
        return new Response();
634
    }
635
636
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
637
     * 受注情報を初期化する.
638 10
     *
639 10
     * @ForwardOnly
640
     * @Route("/shopping/initialize_order", name="shopping_initialize_order")
641
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
642
    public function initializeOrder(Application $app, 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...
643 10
    {
644
        // 購入処理中の受注情報を取得
645 10
        $Order = $this->shoppingService->getOrder($this->appConfig['order_processing']);
646
647 10
        // 初回アクセス(受注情報がない)の場合は, 受注情報を作成
648
        if (is_null($Order)) {
649
            // 未ログインの場合, ログイン画面へリダイレクト.
650
            if (!$app->isGranted('IS_AUTHENTICATED_FULLY')) {
651
                // 非会員でも一度会員登録されていればショッピング画面へ遷移
652
                $Customer = $this->shoppingService->getNonMember($this->sessionKey);
653
654
                if (is_null($Customer)) {
655
                    log_info('未ログインのためログイン画面にリダイレクト');
656 10
657
                    return $app->redirect($app->url('shopping_login'));
658 10
                }
659
            } else {
660 10
                $Customer = $app->user();
661
            }
662 10
663
            try {
664 10
                // 受注情報を作成
665 10
                //$Order = $app['eccube.service.shopping']->createOrder($Customer);
666
                $Order = $this->orderHelper->createProcessingOrder(
667 10
                    $Customer,
668
                    $Customer->getCustomerAddresses()->current(),
669 10
                    $this->cartService->getCart()->getCartItems()
670
                );
671 10
                $this->cartService->setPreOrderId($Order->getPreOrderId());
672
                $this->cartService->save();
673 10
            } catch (CartException $e) {
674
                log_error('初回受注情報作成エラー', array($e->getMessage()));
675 10
                $app->addRequestError($e->getMessage());
676
677
                return $app->redirect($app->url('cart'));
678
            }
679
680
            // セッション情報を削除
681
            $this->session->remove($this->sessionOrderKey);
682
            $this->session->remove($this->sessionMultipleKey);
683
        }
684 5
685
        // 受注関連情報を最新状態に更新
686 5
        $this->entityManager->refresh($Order);
687
688
        $this->parameterBag->set('Order', $Order);
689
690
        return new Response();
691
    }
692 5
693
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
694 2
     * フォームを作成し, イベントハンドラを設定する
695
     *
696 2
     * @ForwardOnly
697
     * @Route("/shopping/create_form", name="shopping_create_form")
698 2
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
699
    public function createForm(Application $app, Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $app 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...
700
    {
701
        $Order = $this->parameterBag->get('Order');
702
        // フォームの生成
703 2
        $builder = $this->formFactory->createBuilder(OrderType::class, $Order);
704
705
        $event = new EventArgs(
706
            array(
707
                'builder' => $builder,
708 2
                'Order' => $Order,
709
            ),
710
            $request
711 2
        );
712 2
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_INDEX_INITIALIZE, $event);
713
714 2
        $form = $builder->getForm();
715
716
        $this->parameterBag->set(OrderType::class, $form);
717
718 3
        return new Response();
719
    }
720
721
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
722
     * mode に応じて各変更ページへリダイレクトする.
723
     *
724
     * @ForwardOnly
725
     * @Route("/shopping/redirect_to_change", name="shopping_redirect_to_change")
726
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
727 10
    public function redirectToChange(Application $app, 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...
728
    {
729 10
        $form = $this->parameterBag->get(OrderType::class);
730
731
        // requestのバインド後、Calculatorに再集計させる
732 10
        //$app['eccube.service.calculate']($Order, $Order->getCustomer())->calculate();
733 10
734
        // 支払い方法の変更や配送業者の変更があった場合はDBに保持する.
735
        if ($form->isSubmitted() && $form->isValid()) {
736
            // POSTされたデータをDBに保持.
737
            $this->entityManager->flush();
738
739
            $mode = $form['mode']->getData();
740
            switch ($mode) {
741
                case 'shipping_change':
742
                    // お届け先設定一覧へリダイレクト
743 10
                    $param = $form['param']->getData();
744
745
                    return $app->redirect($app->url('shopping_shipping', array('id' => $param)));
746 10
                case 'shipping_edit_change':
747
                    // お届け先設定一覧へリダイレクト
748
                    $param = $form['param']->getData();
749
750
                    return $app->redirect($app->url('shopping_shipping_edit', array('id' => $param)));
751
                case 'shipping_multiple_change':
752
                    // 複数配送設定へリダイレクト
753
                    return $app->redirect($app->url('shopping_shipping_multiple'));
754
                case 'payment':
755 7
                case 'delivery':
756
                default:
757 7
                    return $app->redirect($app->url('shopping'));
758 7
            }
759
        }
760
761
        return new Response();
762
    }
763
764 7
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
765
     * 複数配送時のエラーを表示する
766 7
     *
767
     * @ForwardOnly
768
     * @Route("/shopping/handle_multiple_errors", name="shopping_handle_multiple_errors")
769
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
770
    public function handleMultipleErrors(Application $app, 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...
771
    {
772
        $Order = $this->parameterBag->get('Order');
773
774
        // 複数配送の場合、エラーメッセージを一度だけ表示
775 2
        if (!$this->session->has($this->sessionMultipleKey)) {
776
            if (count($Order->getShippings()) > 1) {
777 2
                if (!$this->BaseInfo->isOptionMultipleShipping()) {
778
                    // 複数配送に設定されていないのに複数配送先ができればエラー
779 2
                    $app->addRequestError('cart.product.type.kind');
780
781
                    return $app->redirect($app->url('cart'));
782 2
                }
783 2
784
                $app->addError('shopping.multiple.delivery');
785
            }
786 2
            $this->session->set($this->sessionMultipleKey, 'multiple');
787 2
        }
788
789
        return new Response();
790
    }
791
792
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
793
     * 受注の存在チェック
794 2
     *
795 2
     * @ForwardOnly
796
     * @Route("/shopping/exists_order", name="shopping_exists_order")
797
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
798
    public function existsOrder(Application $app, 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...
799
    {
800
        $Order = $this->shoppingService->getOrder($this->appConfig['order_processing']);
801 2
        if (!$Order) {
802
            log_info('購入処理中の受注情報がないため購入エラー');
803
            $app->addError('front.shopping.order.error');
804 2
805
            return $app->redirect($app->url('shopping_error'));
806 2
        }
807 2
        $this->parameterBag->set('Order', $Order);
808 2
809 2
        return new Response();
810
    }
811
812
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
813
     * 受注完了処理
814
     *
815
     * @ForwardOnly
816
     * @Route("/shopping/complete_order", name="shopping_complete_order")
817 2
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
818
    public function completeOrder(Application $app, Request $request)
819
    {
820 2
        $form = $this->parameterBag->get(OrderType::class);
821 2
822
        if ($form->isSubmitted() && $form->isValid()) {
823
824
            /** @var Order $Order */
825 2
            $Order = $form->getData();
826 2
            log_info('購入処理開始', array($Order->getId()));
827
828
            // トランザクション制御
829
            $em = $this->entityManager;
830
            $em->getConnection()->beginTransaction();
831
            try {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
832 2
833 2
                // お問い合わせ、配送時間などのフォーム項目をセット
834
                // FormTypeで更新されるため不要
835 2
                //$app['eccube.service.shopping']->setFormData($Order, $data);
836
837
                $flowResult = $this->executePurchaseFlow($app, $Order);
838
                if ($flowResult->hasWarning() || $flowResult->hasError()) {
839
                    // TODO エラーメッセージ
840
                    throw new ShoppingException();
841
                }
842
                try {
843
                    $this->purchaseFlow->purchase($Order, $app['eccube.purchase.context']($Order, $Order->getCustomer())); // TODO 変更前の Order を渡す必要がある?
844
                } 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...
845
                    $app->addError($e->getMessage(), 'front');
846
                }
847
848
                // 購入処理
849
                $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...
850
851
                // Order も引数で渡すのがベスト??
852
                $paymentService = $app['eccube.service.payment']($Order->getPayment()->getServiceClass());
853
854
                $paymentMethod = $app['payment.method.request'](
855
                    $Order->getPayment()->getMethodClass(),
856
                    $form,
857
                    $request
858
                );
859
                // 必要に応じて別のコントローラへ forward or redirect(移譲)
860 2
                // forward の処理はプラグイン内で書けるようにしておく
861
                // dispatch をしたら, パスを返して forwardする
862
                // http://silex.sensiolabs.org/doc/cookbook/sub_requests.html
863
                // 確認画面も挟める
864
                // Request をセッションに入れるべし
865
                $dispatcher = $paymentService->dispatch($paymentMethod); // 決済処理中.
866
                // 一旦、決済処理中になった後は、購入処理中に戻せない。キャンセル or 購入完了の仕様とする
867
                // ステータス履歴も保持しておく? 在庫引き当ての仕様もセットで。
868
                if ($dispatcher instanceof Response
869
                    && ($dispatcher->isRedirection() || $dispatcher->getContent())
870
                ) { // $paymentMethod->apply() が Response を返した場合は画面遷移
871
                    return $dispatcher;                // 画面遷移したいパターンが複数ある場合はどうする? 引数で制御?
872 2
                }
873
                $PaymentResult = $paymentService->doCheckout($paymentMethod); // 決済実行
874 2
                if (!$PaymentResult->isSuccess()) {
875 2
                    $em->getConnection()->rollback();
876
877
                    return $app->redirect($app->url('shopping_error'));
878 2
                }
879
880 2
                $em->flush();
881
                $em->getConnection()->commit();
882 2
883 2
                log_info('購入処理完了', array($Order->getId()));
884
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
885 2
            } catch (ShoppingException $e) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
886
887 2
                log_error('購入エラー', array($e->getMessage()));
888
889 2
                $em->getConnection()->rollback();
890
891
                $app->log($e);
892
                $app->addError($e->getMessage());
893
894
                return $app->redirect($app->url('shopping_error'));
895
            } catch (\Exception $e) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
896 2
897
                log_error('予期しないエラー', array($e->getMessage()));
898
899 2
                $em->getConnection()->rollback();
900
901 2
                $app->log($e);
902
903 2
                $app->addError('front.shopping.system.error');
904 2
905 2
                return $app->redirect($app->url('shopping_error'));
906
            }
907 2
908
            return $app->forward($app->path('shopping_after_complete'));
909 2
        }
910
911 2
        return new Response();
912
    }
913
914
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
915
     * 受注完了の後処理
916
     *
917
     * @ForwardOnly
918 2
     * @Route("/shopping/after_complete", name="shopping_after_complete")
919
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
920
    public function afterComplete(Application $app, Request $request)
921
    {
922
        $form = $this->parameterBag->get(OrderType::class);
923
        $Order = $this->parameterBag->get('Order');
924
925
        // カート削除
926
        $this->cartService->clear()->save();
927
928
        $event = new EventArgs(
929
            array(
930
                'form' => $form,
931
                'Order' => $Order,
932
            ),
933
            $request
934
        );
935
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_CONFIRM_PROCESSING, $event);
936
937 View Code Duplication
        if ($event->getResponse() !== null) {
938
            log_info('イベントレスポンス返却', array($Order->getId()));
939
940
            return $event->getResponse();
941
        }
942
943
        // 受注IDをセッションにセット
944
        $this->session->set($this->sessionOrderKey, $Order->getId());
945
946
        // メール送信
947
        $MailHistory = $this->shoppingService->sendOrderMail($Order);
948
949
        $event = new EventArgs(
950
            array(
951
                'form' => $form,
952
                'Order' => $Order,
953
                'MailHistory' => $MailHistory,
954
            ),
955
            $request
956
        );
957
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_CONFIRM_COMPLETE, $event);
958
959 View Code Duplication
        if ($event->getResponse() !== null) {
960
            log_info('イベントレスポンス返却', array($Order->getId()));
961
962
            return $event->getResponse();
963
        }
964
965
        // 完了画面表示
966
        return $app->redirect($app->url('shopping_complete'));
967
    }
968
}
969