Failed Conditions
Push — experimental/3.1 ( 965511...751c7a )
by chihiro
21s
created

ShoppingController::createForm()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1.0109

Importance

Changes 0
Metric Value
cc 1
eloc 12
nc 1
nop 2
dl 0
loc 20
rs 9.4285
c 0
b 0
f 0
ccs 7
cts 9
cp 0.7778
crap 1.0109
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 Eccube\Application;
28
use Eccube\Entity\Customer;
29
use Eccube\Entity\CustomerAddress;
30
use Eccube\Entity\Order;
31
use Eccube\Event\EccubeEvents;
32
use Eccube\Event\EventArgs;
33
use Eccube\Exception\CartException;
34
use Eccube\Exception\ShoppingException;
35
use Eccube\Form\Type\Front\CustomerLoginType;
36
use Eccube\Form\Type\Front\ShoppingShippingType;
37
use Eccube\Form\Type\Shopping\OrderType;
38
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
39
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
40
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
41
use Symfony\Component\HttpFoundation\Request;
42
use Symfony\Component\HttpFoundation\Response;
43
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
44
45
/**
46
 * @Route("/shopping")
47
 */
48
class ShoppingController extends AbstractShoppingController
49
{
50
    /**
51
     * 購入画面表示
52
     *
53
     * @Route("/", name="shopping")
54
     * @Template("Shopping/index.twig")
55
     *
56
     * @param Application $app
57
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
58
     * @return mixed
59
     */
60 View Code Duplication
    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...
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...
61
    {
62
        // カートチェック
63
        $response = $app->forward($app->path("shopping/checkToCart"));
64
        if ($response->isRedirection() || $response->getContent()) {
65
            return $response;
66
        }
67
68
        // 受注情報を初期化
69
        $response = $app->forward($app->path("shopping/initializeOrder"));
70
        if ($response->isRedirection() || $response->getContent()) {
71
            return $response;
72
        }
73
74
        /** @var Order $Order */
75
        $Order = $app['request_scope']->get('Order');
76
77
        // 単価集計
78
        $flowResult = $this->executePurchaseFlow($app, $Order);
79
80
        // フォームを生成する
81
        $app->forward($app->path("shopping/createForm"));
82
83
        if ($flowResult->hasWarning() || $flowResult->hasError()) {
84
            return $app->redirect($app->url('cart'));
85
        }
86
87
        // 複数配送の場合、エラーメッセージを一度だけ表示
88
        $app->forward($app->path("shopping/handleMultipleErrors"));
89
        $form = $app['request_scope']->get(OrderType::class);
90
91
        return [
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
92
            'form' => $form->createView(),
93
            'Order' => $Order
94
        ];
95
    }
96
97
    /**
98
     * 購入確認画面から, 他の画面へのリダイレクト.
99
     * 配送業者や支払方法、お問い合わせ情報をDBに保持してから遷移する.
100
     *
101
     * @param Application $app
102
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
103
     * @return mixed
104
     */
105
    public function redirectTo(Application $app, Request $request)
106
    {
107
        // カートチェック
108
        $response = $app->forward($app->path("shopping/checkToCart"));
109
        if ($response->isRedirection() || $response->getContent()) {
110
            return $response;
111
        }
112
113
        // 受注の存在チェック
114
        $response = $app->forward($app->path("shopping/existsOrder"));
115
        if ($response->isRedirection() || $response->getContent()) {
116
            return $response;
117
        }
118
119
        // フォームの生成
120
        $app->forward($app->path("shopping/createForm"));
121
        $form = $app['request_scope']->get(OrderType::class);
122
        $Order = $app['request_scope']->get('Order');
0 ignored issues
show
Unused Code introduced by
$Order is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
123
124
        $form->handleRequest($request);
125
126
        // 各種変更ページへリダイレクトする
127
        $response = $app->forward($app->path("shopping/redirectToChange"));
128
        if ($response->isRedirection() || $response->getContent()) {
129
            return $response;
130
        }
131
        $form = $app['request_scope']->get(OrderType::class);
132
        $Order = $app['request_scope']->get('Order');
133
134
        return $app->render('Shopping/index.twig', array(
135
            'form' => $form->createView(),
136
            'Order' => $Order,
137
        ));
138
    }
139
140
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
141
     * 購入処理
142
     *
143
     * @Method("POST")
144
     * @Route("/confirm", name="shopping/confirm")
145
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
146 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...
147
    {
148
        // カートチェック
149
        $response = $app->forward($app->path("shopping/checkToCart"));
150
        if ($response->isRedirection() || $response->getContent()) {
151
            return $response;
152
        }
153
154
        // 受注の存在チェック
155
        $response = $app->forward($app->path("shopping/existsOrder"));
156
        if ($response->isRedirection() || $response->getContent()) {
157
            return $response;
158
        }
159
160
        // form作成
161
        // FIXME イベントハンドラを外から渡したい
162
        $app->forward($app->path("shopping/createForm"));
163
164
        $form = $app['request_scope']->get(OrderType::class);
165
        $Order = $app['request_scope']->get('Order');
166
167
        $form->handleRequest($request);
168
169
        // 受注処理
170
        $response = $app->forward($app->path("shopping/completeOrder"));
171
        if ($response->isRedirection() || $response->getContent()) {
172
            return $response;
173
        }
174
175
        log_info('購入チェックエラー', array($Order->getId()));
176
177
        return $app->render('Shopping/index.twig', array(
178
            'form' => $form->createView(),
179
            'Order' => $Order,
180
        ));
181
    }
182
183
184
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
185
     * 購入完了画面表示
186
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
187
    public function complete(Application $app, Request $request)
188
    {
189
        // 受注IDを取得
190
        $orderId = $app['session']->get($this->sessionOrderKey);
191
192
        $event = new EventArgs(
193
            array(
194
                'orderId' => $orderId,
195
            ),
196
            $request
197
        );
198
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_COMPLETE_INITIALIZE, $event);
199
200
        if ($event->getResponse() !== null) {
201
            return $event->getResponse();
202
        }
203
204
        // 受注に関連するセッションを削除
205
        $app['session']->remove($this->sessionOrderKey);
206
        $app['session']->remove($this->sessionMultipleKey);
207
        // 非会員用セッション情報を空の配列で上書きする(プラグイン互換性保持のために削除はしない)
208
        $app['session']->set($this->sessionKey, array());
209
        $app['session']->set($this->sessionCustomerAddressKey, array());
210
211
        log_info('購入処理完了', array($orderId));
212
213
        return $app->render('Shopping/complete.twig', array(
214
            'orderId' => $orderId,
215 2
        ));
216
    }
217
218 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...
introduced by
Doc comment for parameter "$id" missing
Loading history...
219
     * お届け先の設定一覧からの選択
220 2
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
221
    public function shipping(Application $app, Request $request, $id)
222 2
    {
223
        // カートチェック
224
        $response = $app->forward($app->path("shopping/checkToCart"));
225
        if ($response->isRedirection() || $response->getContent()) {
226 2
            return $response;
227
        }
228 2
229
        if ('POST' === $request->getMethod()) {
230
            $address = $request->get('address');
231
232
            if (is_null($address)) {
233 2
                // 選択されていなければエラー
234
                log_info('お届け先入力チェックエラー');
235 2
                return $app->render(
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
236
                    'Shopping/shipping.twig',
237 2
                    array(
238 2
                        'Customer' => $app->user(),
239
                        'shippingId' => $id,
240
                        'error' => true,
241
                    )
242
                );
243
            }
244
245
            // 選択されたお届け先情報を取得
246
            $CustomerAddress = $app['eccube.repository.customer_address']->findOneBy(array(
247
                'Customer' => $app->user(),
248
                'id' => $address,
249
            ));
250
            if (is_null($CustomerAddress)) {
251
                throw new NotFoundHttpException('選択されたお届け先住所が存在しない');
252
            }
253
254
            /** @var Order $Order */
255
            $Order = $app['eccube.service.shopping']->getOrder($app['config']['order_processing']);
256
            if (!$Order) {
257
                log_info('購入処理中の受注情報がないため購入エラー');
258
                $app->addError('front.shopping.order.error');
259
260
                return $app->redirect($app->url('shopping_error'));
261
            }
262
263
            $Shipping = $Order->findShipping($id);
264
            if (!$Shipping) {
265
                throw new NotFoundHttpException('お届け先情報が存在しない');
266
            }
267
268
            log_info('お届先情報更新開始', array($Shipping->getId()));
269
270
            // お届け先情報を更新
271
            $Shipping->setFromCustomerAddress($CustomerAddress);
272
273
            // 配送料金の設定
274
            $app['eccube.service.shopping']->setShippingDeliveryFee($Shipping);
275
276
277
            // 合計金額の再計算
278
            $flowResult = $this->executePurchaseFlow($app, $Order);
279
            if ($flowResult->hasWarning() || $flowResult->hasError()) {
280
                return $app->redirect($app->url('shopping_error'));
281
            }
282
283
            // 配送先を更新
284
            $app['orm.em']->flush();
285
286
            $event = new EventArgs(
287
                array(
288
                    'Order' => $Order,
289
                    'shippingId' => $id,
290
                ),
291
                $request
292
            );
293
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_COMPLETE, $event);
294
295
            log_info('お届先情報更新完了', array($Shipping->getId()));
296
            return $app->redirect($app->url('shopping'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
297
        }
298
299
        return $app->render(
300
            'Shopping/shipping.twig',
301
            array(
302
                'Customer' => $app->user(),
303
                'shippingId' => $id,
304
                'error' => false,
305
            )
306
        );
307
    }
308
309
    /**
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...
310
     * お届け先の設定(非会員でも使用する)
311
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
312
    public function shippingEdit(Application $app, Request $request, $id)
313
    {
314
        // 配送先住所最大値判定
315
        $Customer = $app->user();
316 View Code Duplication
        if ($app->isGranted('IS_AUTHENTICATED_FULLY')) {
317
            $addressCurrNum = count($app->user()->getCustomerAddresses());
318
            $addressMax = $app['config']['deliv_addr_max'];
319
            if ($addressCurrNum >= $addressMax) {
320
                throw new NotFoundHttpException('配送先住所最大数エラー');
321
            }
322
        }
323
324
        // カートチェック
325
        $response = $app->forward($app->path("shopping/checkToCart"));
326
        if ($response->isRedirection() || $response->getContent()) {
327
            return $response;
328
        }
329
330
        // 受注の存在チェック
331
        $response = $app->forward($app->path("shopping/existsOrder"));
332
        if ($response->isRedirection() || $response->getContent()) {
333
            return $response;
334
        }
335
336
        /** @var Order $Order */
337
        $Order = $app['request_scope']->get('Order');
338
339
        $Shipping = $Order->findShipping($id);
340
        if (!$Shipping) {
341
            throw new NotFoundHttpException('設定されている配送先が存在しない');
342
        }
343
        if ($app->isGranted('IS_AUTHENTICATED_FULLY')) {
344
            $Shipping->clearCustomerAddress();
345
        }
346
347
        $CustomerAddress = new CustomerAddress();
348
        if ($app->isGranted('IS_AUTHENTICATED_FULLY')) {
349
            $CustomerAddress->setCustomer($Customer);
350
        } else {
351
            $CustomerAddress->setFromShipping($Shipping);
352
        }
353
354
        $builder = $app['form.factory']->createBuilder(ShoppingShippingType::class, $CustomerAddress);
355
356
        $event = new EventArgs(
357
            array(
358
                'builder' => $builder,
359
                'Order' => $Order,
360
                'Shipping' => $Shipping,
361
                'CustomerAddress' => $CustomerAddress,
362
            ),
363
            $request
364
        );
365
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_EDIT_INITIALIZE, $event);
366
367
        $form = $builder->getForm();
368
369
        $form->handleRequest($request);
370
371
        if ($form->isSubmitted() && $form->isValid()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
372
373
            log_info('お届け先追加処理開始', array('id' => $Order->getId(), 'shipping' => $id));
374
375
            // 会員の場合、お届け先情報を新規登録
376
            $Shipping->setFromCustomerAddress($CustomerAddress);
377
378
            if ($Customer instanceof Customer) {
379
                $app['orm.em']->persist($CustomerAddress);
380
                log_info('新規お届け先登録', array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
381
                    'id' => $Order->getId(),
382
                    'shipping' => $id,
383
                    'customer address' => $CustomerAddress->getId()));
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 16 spaces, but found 20.
Loading history...
384
            }
385
386
            // 配送料金の設定
387
            $app['eccube.service.shopping']->setShippingDeliveryFee($Shipping);
388
389
            // 合計金額の再計算
390
            $flowResult = $this->executePurchaseFlow($app, $Order);
391
            if ($flowResult->hasWarning() || $flowResult->hasError()) {
392
                return $app->redirect($app->url('shopping_error'));
393
            }
394
395
            // 配送先を更新
396
            $app['orm.em']->flush();
397
398
            $event = new EventArgs(
399
                array(
400
                    'form' => $form,
401
                    'Shipping' => $Shipping,
402
                    'CustomerAddress' => $CustomerAddress,
403
                ),
404
                $request
405
            );
406
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_EDIT_COMPLETE, $event);
407
408
            log_info('お届け先追加処理完了', array('id' => $Order->getId(), 'shipping' => $id));
409
            return $app->redirect($app->url('shopping'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
410
        }
411
412
        return $app->render('Shopping/shipping_edit.twig', array(
413
            'form' => $form->createView(),
414
            'shippingId' => $id,
415
        ));
416
    }
417
418
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
419
     * ログイン
420
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
421
    public function login(Application $app, Request $request)
422
    {
423
        if (!$app['eccube.service.cart']->isLocked()) {
424
            return $app->redirect($app->url('cart'));
425
        }
426
427
        if ($app->isGranted('IS_AUTHENTICATED_FULLY')) {
428
            return $app->redirect($app->url('shopping'));
429
        }
430
431
        /* @var $form \Symfony\Component\Form\FormInterface */
432
        $builder = $app['form.factory']->createNamedBuilder('', CustomerLoginType::class);
433
434 View Code Duplication
        if ($app->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
435
            $Customer = $app->user();
436
            if ($Customer) {
437
                $builder->get('login_email')->setData($Customer->getEmail());
438
            }
439
        }
440
441
        $event = new EventArgs(
442
            array(
443
                'builder' => $builder,
444
            ),
445
            $request
446
        );
447
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_LOGIN_INITIALIZE, $event);
448
449
        $form = $builder->getForm();
450
451
        return $app->render('Shopping/login.twig', array(
452
            'error' => $app['security.last_error']($request),
453
            'form' => $form->createView(),
454
        ));
455
    }
456
457
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
458
     * 購入エラー画面表示
459
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
460
    public function shoppingError(Application $app, Request $request)
461
    {
462
463
        $event = new EventArgs(
464
            array(),
465
            $request
466
        );
467
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_ERROR_COMPLETE, $event);
468
469
        if ($event->getResponse() !== null) {
470
            return $event->getResponse();
471
        }
472
473
        return $app->render('Shopping/shopping_error.twig');
474
    }
475
476
    /**
477
     * カート画面のチェック
478
     *
479
     * @Route("/checkToCart", name="shopping/checkToCart")
480
     * @param Application $app
481
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
482
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
483
     */
484
    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...
485
    {
486
        $cartService = $app['eccube.service.cart'];
487
488
        // カートチェック
489
        if (!$cartService->isLocked()) {
490
            log_info('カートが存在しません');
491
            // カートが存在しない、カートがロックされていない時はエラー
492
            return $app->redirect($app->url('cart'));
493
        }
494
495
        // カートチェック
496
        if (count($cartService->getCart()->getCartItems()) <= 0) {
497
            log_info('カートに商品が入っていないためショッピングカート画面にリダイレクト');
498
            // カートが存在しない時はエラー
499
            return $app->redirect($app->url('cart'));
500
        }
501
502
        return new Response();
503
    }
504
505
    /**
506
     * 受注情報を初期化する.
507
     *
508
     * @Route("/initializeOrder", name="shopping/initializeOrder")
509
     * @param Application $app
510
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
511
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
512
     */
513
    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...
514
    {
515
        $cartService = $app['eccube.service.cart'];
516
        // 購入処理中の受注情報を取得
517
        $Order = $app['eccube.service.shopping']->getOrder($app['config']['order_processing']);
518
519
        // 初回アクセス(受注情報がない)の場合は, 受注情報を作成
520
        if (is_null($Order)) {
521 4
            // 未ログインの場合, ログイン画面へリダイレクト.
522
            if (!$app->isGranted('IS_AUTHENTICATED_FULLY')) {
523 4
                // 非会員でも一度会員登録されていればショッピング画面へ遷移
524 3
                $Customer = $app['eccube.service.shopping']->getNonMember($this->sessionKey);
525
526
                if (is_null($Customer)) {
527 1
                    log_info('未ログインのためログイン画面にリダイレクト');
528
                    return $app->redirect($app->url('shopping_login'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
529
                }
530
            } else {
531
                $Customer = $app->user();
532 1
            }
533
534 1
            try {
535
                // 受注情報を作成
536
                //$Order = $app['eccube.service.shopping']->createOrder($Customer);
537
                $Order = $app['eccube.helper.order']->createProcessingOrder(
538
                    $Customer, $Customer->getCustomerAddresses()->current(), $cartService->getCart()->getCartItems());
539
                $cartService->setPreOrderId($Order->getPreOrderId());
540
                $cartService->save();
541 1
            } catch (CartException $e) {
542
                log_error('初回受注情報作成エラー', array($e->getMessage()));
543 1
                $app->addRequestError($e->getMessage());
544
                return $app->redirect($app->url('cart'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
545
            }
546
547 1
            // セッション情報を削除
548
            $app['session']->remove($this->sessionOrderKey);
549 1
            $app['session']->remove($this->sessionMultipleKey);
550
        }
551 1
552 1
        // 受注関連情報を最新状態に更新
553 1
        $app['orm.em']->refresh($Order);
554
555
        $app['request_scope']->set('Order', $Order);
556
        return new Response();
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
557
    }
558
559
    /**
560 16
     * フォームを作成し, イベントハンドラを設定する
561
     *
562 16
     * @Route("/createForm", name="shopping/createForm")
563
     * @param Application $app
564
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
565 16
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
566 16
     */
567 1
    public function createForm(Application $app, Request $request)
568
    {
569
        $Order = $app['request_scope']->get('Order');
570
        // フォームの生成
571 15
        $builder = $app['form.factory']->createBuilder(OrderType::class, $Order);
572 1
573
        $event = new EventArgs(
574
            array(
575
                'builder' => $builder,
576 14
                'Order' => $Order,
577
            ),
578
            $request
579
        );
580
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_INDEX_INITIALIZE, $event);
581
582 14
        $form = $builder->getForm();
583
584 14
        $app['request_scope']->set(OrderType::class, $form);
585
        return new Response();
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
586 14
    }
587
588
    /**
589
     * mode に応じて各変更ページへリダイレクトする.
590 14
     *
591
     * @Route("/redirectToChange", name="shopping/redirectToChange")
592 14
     * @param Application $app
593
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
594 14
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
595
     */
596 14
    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...
597
    {
598 13
        $form = $app['request_scope']->get(OrderType::class);
599
        $Order = $app['request_scope']->get('Order');
0 ignored issues
show
Unused Code introduced by
$Order is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
600 13
601 13
        // requestのバインド後、Calculatorに再集計させる
602
        //$app['eccube.service.calculate']($Order, $Order->getCustomer())->calculate();
603 13
604 13
        // 支払い方法の変更や配送業者の変更があった場合はDBに保持する.
605 13
        if ($form->isSubmitted() && $form->isValid()) {
606 13
            // POSTされたデータをDBに保持.
607 13
            $app['orm.em']->flush();
608 13
609 13
            $mode = $form['mode']->getData();
610 13
            switch ($mode) {
611 13
                case 'shipping_change':
612 13
                    // お届け先設定一覧へリダイレクト
613 13
                    $param = $form['param']->getData();
614 13
                    return $app->redirect($app->url('shopping_shipping', array('id' => $param)));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
615 13
                case 'shipping_edit_change':
616 13
                    // お届け先設定一覧へリダイレクト
617 13
                    $param = $form['param']->getData();
618
                    return $app->redirect($app->url('shopping_shipping_edit', array('id' => $param)));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
619
                case 'shipping_multiple_change':
620 13
                    // 複数配送設定へリダイレクト
621
                    return $app->redirect($app->url('shopping_shipping_multiple'));
622 13
                case 'payment':
623 13
                case 'delivery':
624 13
                default:
625 13
                    return $app->redirect($app->url('shopping'));
626 13
            }
627 13
        }
628 13
629 13
        return new Response();
630 13
    }
631 13
632 13
    /**
633 13
     * 複数配送時のエラーを表示する
634 13
     *
635 13
     * @Route("/handleMultipleErrors", name="shopping/handleMultipleErrors")
636 13
     * @param Application $app
637 13
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
638 13
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
639
     */
640
    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...
641 13
    {
642
        $Order = $app['request_scope']->get('Order');
643
644 13
        // 複数配送の場合、エラーメッセージを一度だけ表示
645
        if (!$app['session']->has($this->sessionMultipleKey)) {
646
            if (count($Order->getShippings()) > 1) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
647
648 13
                $BaseInfo = $app['eccube.repository.base_info']->get();
649
650
                if (!$BaseInfo->getOptionMultipleShipping()) {
651
                    // 複数配送に設定されていないのに複数配送先ができればエラー
652
                    $app->addRequestError('cart.product.type.kind');
653
                    return $app->redirect($app->url('cart'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
654
                }
655
656 13
                $app->addError('shopping.multiple.delivery');
657 13
            }
658 13
            $app['session']->set($this->sessionMultipleKey, 'multiple');
659 13
        }
660
661 13
        return new Response();
662 13
    }
663 13
664
    /**
665 13
     * 受注の存在チェック
666
     *
667 13
     * @Route("/existsOrder", name="shopping/existsOrder")
668 13
     * @param Application $app
669
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
670
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
671
     */
672 13
    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...
673
    {
674 13
        $Order = $app['eccube.service.shopping']->getOrder($app['config']['order_processing']);
675
        if (!$Order) {
676
            log_info('購入処理中の受注情報がないため購入エラー');
677
            $app->addError('front.shopping.order.error');
678 13
            return $app->redirect($app->url('shopping_error'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
679
        }
680 13
        $app['request_scope']->set('Order', $Order);
681
        return new Response();
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
682
    }
683 1
684 1
    /**
685
     * 受注完了処理
686
     *
687
     * @Route("/completeOrder", name="shopping/completeOrder")
688
     * @param Application $app
689
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
690
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
691
     */
692
    public function completeOrder(Application $app, Request $request)
693
    {
694
        $form = $app['request_scope']->get(OrderType::class);
695
696
        if ($form->isSubmitted() && $form->isValid()) {
697
698
            /** @var Order $Order */
699
            $Order = $form->getData();
700
            log_info('購入処理開始', array($Order->getId()));
701
702
            // トランザクション制御
703
            $em = $app['orm.em'];
704
            $em->getConnection()->beginTransaction();
705
            try {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
706
707
                // お問い合わせ、配送時間などのフォーム項目をセット
708
                // FormTypeで更新されるため不要
709
                //$app['eccube.service.shopping']->setFormData($Order, $data);
710
711
                $flowResult = $this->executePurchaseFlow($app, $Order);
712
                if ($flowResult->hasWarning() || $flowResult->hasError()) {
713
                    // TODO エラーメッセージ
714
                    throw new ShoppingException();
715
                }
716
717
                // 購入処理
718
                $app['eccube.service.shopping']->processPurchase($Order); // XXX フロント画面に依存してるので管理画面では使えない
719
720
                // Order も引数で渡すのがベスト??
721
                $paymentService = $app['eccube.service.payment']($Order->getPayment()->getServiceClass());
722
723
                $paymentMethod = $app['payment.method.request']($Order->getPayment()->getMethodClass(), $form, $request);
724
                // 必要に応じて別のコントローラへ forward or redirect(移譲)
725
                // forward の処理はプラグイン内で書けるようにしておく
726
                // dispatch をしたら, パスを返して forwardする
727
                // http://silex.sensiolabs.org/doc/cookbook/sub_requests.html
728
                // 確認画面も挟める
729
                // Request をセッションに入れるべし
730
                $dispatcher = $paymentService->dispatch($paymentMethod); // 決済処理中.
731
                // 一旦、決済処理中になった後は、購入処理中に戻せない。キャンセル or 購入完了の仕様とする
732
                // ステータス履歴も保持しておく? 在庫引き当ての仕様もセットで。
733
                if ($dispatcher instanceof Response
734
                    && ($dispatcher->isRedirection() || $dispatcher->getContent())) { // $paymentMethod->apply() が Response を返した場合は画面遷移
735
                    return $dispatcher;                // 画面遷移したいパターンが複数ある場合はどうする? 引数で制御?
736
                }
737
                $PaymentResult = $paymentService->doCheckout($paymentMethod); // 決済実行
738
                if (!$PaymentResult->isSuccess()) {
739
                    $em->getConnection()->rollback();
740
                    return $app->redirect($app->url('shopping_error'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
741
                }
742
743
                $em->flush();
744
                $em->getConnection()->commit();
745
746
                log_info('購入処理完了', array($Order->getId()));
747
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
748
            } catch (ShoppingException $e) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
749
750
                log_error('購入エラー', array($e->getMessage()));
751
752
                $em->getConnection()->rollback();
753
754
                $app->log($e);
755
                $app->addError($e->getMessage());
756
757
                return $app->redirect($app->url('shopping_error'));
758
            } catch (\Exception $e) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
759
760
                log_error('予期しないエラー', array($e->getMessage()));
761
762
                $em->getConnection()->rollback();
763
764
                $app->log($e);
765
766
                $app->addError('front.shopping.system.error');
767
                return $app->redirect($app->url('shopping_error'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
768
            }
769
770
            return $app->forward($app->path('shopping/afterComplete'));
771
        }
772
773
        return new Response();
774
    }
775
776
    /**
777
     * 受注完了の後処理
778
     *
779
     * @Route("/afterComplete", name="shopping/afterComplete")
780
     * @param Application $app
781
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
782
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
783
     */
784
    public function afterComplete(Application $app, Request $request)
785
    {
786
        $form = $app['request_scope']->get(OrderType::class);
787
        $Order = $app['request_scope']->get('Order');
788
789
        // カート削除
790
        $app['eccube.service.cart']->clear()->save();
791
792
        $event = new EventArgs(
793
            array(
794
                'form' => $form,
795
                'Order' => $Order,
796
            ),
797
            $request
798
        );
799
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_CONFIRM_PROCESSING, $event);
800
801 View Code Duplication
        if ($event->getResponse() !== null) {
802
            log_info('イベントレスポンス返却', array($Order->getId()));
803
            return $event->getResponse();
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
804
        }
805
806
        // 受注IDをセッションにセット
807
        $app['session']->set($this->sessionOrderKey, $Order->getId());
808
809
        // メール送信
810
        $MailHistory = $app['eccube.service.shopping']->sendOrderMail($Order);
811
812
        $event = new EventArgs(
813
            array(
814
                'form' => $form,
815
                'Order' => $Order,
816
                'MailHistory' => $MailHistory,
817
            ),
818
            $request
819
        );
820
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_CONFIRM_COMPLETE, $event);
821
822 View Code Duplication
        if ($event->getResponse() !== null) {
823
            log_info('イベントレスポンス返却', array($Order->getId()));
824
            return $event->getResponse();
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
825
        }
826
827
        // 完了画面表示
828
        return $app->redirect($app->url('shopping_complete'));
829
    }
830
}
831