ShoppingController   F
last analyzed

Complexity

Total Complexity 140

Size/Duplication

Total Lines 1528
Duplicated Lines 11.58 %

Coupling/Cohesion

Components 1
Dependencies 17

Importance

Changes 0
Metric Value
dl 177
loc 1528
rs 0.6314
c 0
b 0
f 0
wmc 140
lcom 1
cbo 17

19 Methods

Rating   Name   Duplication   Size   Complexity  
C index() 5 98 11
D confirm() 8 129 10
B complete() 0 30 2
D delivery() 0 101 9
B payment() 0 67 5
B shippingChange() 43 43 5
C shipping() 0 84 7
B shippingEditChange() 43 43 5
C shippingEdit() 7 101 11
C customer() 12 80 7
B login() 6 35 5
D nonmember() 5 128 9
B shippingMultipleChange() 43 43 5
F shippingMultiple() 5 263 38
A getCustomerAddressId() 0 8 2
A getCustomerAddress() 0 16 2
A shippingMultipleEdit() 0 58 4
A shoppingError() 0 15 2
A customerValidation() 0 68 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like ShoppingController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ShoppingController, and based on these observations, apply Extract Interface, too.

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\Common\Constant;
29
use Eccube\Entity\Customer;
30
use Eccube\Entity\CustomerAddress;
31
use Eccube\Entity\ShipmentItem;
32
use Eccube\Entity\Shipping;
33
use Eccube\Event\EccubeEvents;
34
use Eccube\Event\EventArgs;
35
use Eccube\Exception\CartException;
36
use Eccube\Exception\ShoppingException;
37
use Symfony\Component\HttpFoundation\Request;
38
use Symfony\Component\HttpFoundation\Response;
39
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
40
use Symfony\Component\Validator\Constraints as Assert;
41
42
class ShoppingController extends AbstractController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
43
{
44
45
    /**
46
     * @var string 非会員用セッションキー
47
     */
48
    private $sessionKey = 'eccube.front.shopping.nonmember';
49
50
    /**
51
     * @var string 非会員用セッションキー
52
     */
53
    private $sessionCustomerAddressKey = 'eccube.front.shopping.nonmember.customeraddress';
54
55
    /**
56
     * @var string 複数配送警告メッセージ
57
     */
58
    private $sessionMultipleKey = 'eccube.front.shopping.multiple';
59
60
    /**
61
     * @var string 受注IDキー
62
     */
63
    private $sessionOrderKey = 'eccube.front.shopping.order.id';
64
65
    /**
66
     * 購入画面表示
67
     *
68
     * @param Application $app
69
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
70
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
71
     */
72
    public function index(Application $app, Request $request)
73
    {
74
        $cartService = $app['eccube.service.cart'];
75
76
        // カートチェック
77
        if (!$cartService->isLocked()) {
78
            log_info('カートが存在しません');
79
            // カートが存在しない、カートがロックされていない時はエラー
80
            return $app->redirect($app->url('cart'));
81
        }
82
83
        // カートチェック
84 View Code Duplication
        if (count($cartService->getCart()->getCartItems()) <= 0) {
85
            log_info('カートに商品が入っていないためショッピングカート画面にリダイレクト');
86
            // カートが存在しない時はエラー
87
            return $app->redirect($app->url('cart'));
88
        }
89
90
        // 登録済みの受注情報を取得
91
        $Order = $app['eccube.service.shopping']->getOrder($app['config']['order_processing']);
92
93
        // 初回アクセス(受注情報がない)の場合は, 受注情報を作成
94
        if (is_null($Order)) {
95
            // 未ログインの場合, ログイン画面へリダイレクト.
96
            if (!$app->isGranted('IS_AUTHENTICATED_FULLY')) {
97
                // 非会員でも一度会員登録されていればショッピング画面へ遷移
98
                $Customer = $app['eccube.service.shopping']->getNonMember($this->sessionKey);
99
100
                if (is_null($Customer)) {
101
                    log_info('未ログインのためログイン画面にリダイレクト');
102
                    return $app->redirect($app->url('shopping_login'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
103
                }
104
            } else {
105
                $Customer = $app->user();
106
            }
107
108
            try {
109
                // 受注情報を作成
110
                $Order = $app['eccube.service.shopping']->createOrder($Customer);
111
            } catch (CartException $e) {
112
                log_error('初回受注情報作成エラー', array($e->getMessage()));
113
                $app->addRequestError($e->getMessage());
114
                return $app->redirect($app->url('cart'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
115
            }
116
117
            // セッション情報を削除
118
            $app['session']->remove($this->sessionOrderKey);
119
            $app['session']->remove($this->sessionMultipleKey);
120
        }
121
122
        // 受注関連情報を最新状態に更新
123
        $app['orm.em']->refresh($Order);
124
125
        // form作成
126
        $builder = $app['eccube.service.shopping']->getShippingFormBuilder($Order);
127
128
        $event = new EventArgs(
129
            array(
130
                'builder' => $builder,
131
                'Order' => $Order,
132
            ),
133
            $request
134
        );
135
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_INDEX_INITIALIZE, $event);
136
137
        $form = $builder->getForm();
138
139
        if ($Order->getTotalPrice() < 0) {
140
            // 合計金額がマイナスの場合、エラー
141
            log_info('受注金額マイナスエラー', array($Order->getId()));
142
            $message = $app->trans('shopping.total.price', array('totalPrice' => number_format($Order->getTotalPrice())));
143
            $app->addError($message);
144
145
            return $app->redirect($app->url('shopping_error'));
146
        }
147
148
        // 複数配送の場合、エラーメッセージを一度だけ表示
149
        if (!$app['session']->has($this->sessionMultipleKey)) {
150
            if (count($Order->getShippings()) > 1) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
151
152
                $BaseInfo = $app['eccube.repository.base_info']->get();
153
154
                if (!$BaseInfo->getOptionMultipleShipping()) {
155
                    // 複数配送に設定されていないのに複数配送先ができればエラー
156
                    $app->addRequestError('cart.product.type.kind');
157
                    return $app->redirect($app->url('cart'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
158
                }
159
160
                $app->addError('shopping.multiple.delivery');
161
            }
162
            $app['session']->set($this->sessionMultipleKey, 'multiple');
163
        }
164
165
        return $app->render('Shopping/index.twig', array(
166
            'form' => $form->createView(),
167
            '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
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
174
    public function confirm(Application $app, Request $request)
175
    {
176
        $cartService = $app['eccube.service.cart'];
177
178
        // カートチェック
179
        if (!$cartService->isLocked()) {
180
            // カートが存在しない、カートがロックされていない時はエラー
181
            log_info('カートが存在しません');
182
            return $app->redirect($app->url('cart'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
183
        }
184
185
        $Order = $app['eccube.service.shopping']->getOrder($app['config']['order_processing']);
186
        if (!$Order) {
187
            log_info('購入処理中の受注情報がないため購入エラー');
188
            $app->addError('front.shopping.order.error');
189
            return $app->redirect($app->url('shopping_error'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
190
        }
191
192
        if ('POST' !== $request->getMethod()) {
193
            return $app->redirect($app->url('cart'));
194
        }
195
196
        // form作成
197
        $builder = $app['eccube.service.shopping']->getShippingFormBuilder($Order);
198
199
        $event = new EventArgs(
200
            array(
201
                'builder' => $builder,
202
                'Order' => $Order,
203
            ),
204
            $request
205
        );
206
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_CONFIRM_INITIALIZE, $event);
207
208
        $form = $builder->getForm();
209
210
        $form->handleRequest($request);
211
212
        if ($form->isSubmitted() && $form->isValid()) {
213
            $data = $form->getData();
214
215
            log_info('購入処理開始', array($Order->getId()));
216
217
            // トランザクション制御
218
            $em = $app['orm.em'];
219
            $em->getConnection()->beginTransaction();
220
            try {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
221
222
                // お問い合わせ、配送時間などのフォーム項目をセット
223
                $app['eccube.service.shopping']->setFormData($Order, $data);
224
                // 購入処理
225
                $app['eccube.service.shopping']->processPurchase($Order);
226
227
                $em->flush();
228
                $em->getConnection()->commit();
229
230
                log_info('購入処理完了', array($Order->getId()));
231
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
232
            } catch (ShoppingException $e) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
233
234
                log_error('購入エラー', array($e->getMessage()));
235
236
                $em->getConnection()->rollback();
237
238
                $app->log($e);
239
                $app->addError($e->getMessage());
240
241
                return $app->redirect($app->url('shopping_error'));
242
            } catch (\Exception $e) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
243
244
                log_error('予期しないエラー', array($e->getMessage()));
245
246
                $em->getConnection()->rollback();
247
248
                $app->log($e);
249
250
                $app->addError('front.shopping.system.error');
251
                return $app->redirect($app->url('shopping_error'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
252
            }
253
254
            // カート削除
255
            $app['eccube.service.cart']->clear()->save();
256
257
            $event = new EventArgs(
258
                array(
259
                    'form' => $form,
260
                    'Order' => $Order,
261
                ),
262
                $request
263
            );
264
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_CONFIRM_PROCESSING, $event);
265
266 View Code Duplication
            if ($event->getResponse() !== null) {
267
                log_info('イベントレスポンス返却', array($Order->getId()));
268
                return $event->getResponse();
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
269
            }
270
271
            // 受注IDをセッションにセット
272
            $app['session']->set($this->sessionOrderKey, $Order->getId());
273
274
            // メール送信
275
            $MailHistory = $app['eccube.service.shopping']->sendOrderMail($Order);
276
277
            $event = new EventArgs(
278
                array(
279
                    'form' => $form,
280
                    'Order' => $Order,
281
                    'MailHistory' => $MailHistory,
282
                ),
283
                $request
284
            );
285
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_CONFIRM_COMPLETE, $event);
286
287 View Code Duplication
            if ($event->getResponse() !== null) {
288
                log_info('イベントレスポンス返却', array($Order->getId()));
289
                return $event->getResponse();
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
290
            }
291
292
            // 完了画面表示
293
            return $app->redirect($app->url('shopping_complete'));
294
        }
295
296
        log_info('購入チェックエラー', array($Order->getId()));
297
298
        return $app->render('Shopping/index.twig', array(
299
            'form' => $form->createView(),
300
            'Order' => $Order,
301
        ));
302
    }
303
304
305
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
306
     * 購入完了画面表示
307
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
308
    public function complete(Application $app, Request $request)
309
    {
310
        // 受注IDを取得
311
        $orderId = $app['session']->get($this->sessionOrderKey);
312
313
        $event = new EventArgs(
314
            array(
315
                'orderId' => $orderId,
316
            ),
317
            $request
318
        );
319
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_COMPLETE_INITIALIZE, $event);
320
321
        if ($event->getResponse() !== null) {
322
            return $event->getResponse();
323
        }
324
325
        // 受注に関連するセッションを削除
326
        $app['session']->remove($this->sessionOrderKey);
327
        $app['session']->remove($this->sessionMultipleKey);
328
        // 非会員用セッション情報を空の配列で上書きする(プラグイン互換性保持のために削除はしない)
329
        $app['session']->set($this->sessionKey, array());
330
        $app['session']->set($this->sessionCustomerAddressKey, array());
331
332
        log_info('購入処理完了', array($orderId));
333
334
        return $app->render('Shopping/complete.twig', array(
335
            'orderId' => $orderId,
336
        ));
337
    }
338
339
340
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
341
     * 配送業者選択処理
342
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
343
    public function delivery(Application $app, Request $request)
344
    {
345
        // カートチェック
346
        if (!$app['eccube.service.cart']->isLocked()) {
347
            // カートが存在しない、カートがロックされていない時はエラー
348
            log_info('カートが存在しません');
349
            return $app->redirect($app->url('cart'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
350
        }
351
352
        $Order = $app['eccube.service.shopping']->getOrder($app['config']['order_processing']);
353
        if (!$Order) {
354
            log_info('購入処理中の受注情報がないため購入エラー');
355
            $app->addError('front.shopping.order.error');
356
            return $app->redirect($app->url('shopping_error'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
357
        }
358
359
        if ('POST' !== $request->getMethod()) {
360
            return $app->redirect($app->url('shopping'));
361
        }
362
363
        $builder = $app['eccube.service.shopping']->getShippingFormBuilder($Order);
364
365
        $event = new EventArgs(
366
            array(
367
                'builder' => $builder,
368
                'Order' => $Order,
369
            ),
370
            $request
371
        );
372
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_DELIVERY_INITIALIZE, $event);
373
374
        $form = $builder->getForm();
375
376
        $form->handleRequest($request);
377
378
        if ($form->isSubmitted() && $form->isValid()) {
379
            log_info('配送業者変更処理開始', array($Order->getId()));
380
381
            $data = $form->getData();
382
383
            $shippings = $data['shippings'];
384
385
            $productDeliveryFeeTotal = 0;
386
            $BaseInfo = $app['eccube.repository.base_info']->get();
387
388
            foreach ($shippings as $Shipping) {
389
                $Delivery = $Shipping->getDelivery();
390
391
                if ($Delivery) {
392
                    $deliveryFee = $app['eccube.repository.delivery_fee']->findOneBy(array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
393
                        'Delivery' => $Delivery,
394
                        'Pref' => $Shipping->getPref()
395
                    ));
396
397
                    // 商品ごとの配送料合計
398
                    if ($BaseInfo->getOptionProductDeliveryFee() === Constant::ENABLED) {
399
                        $productDeliveryFeeTotal += $app['eccube.service.shopping']->getProductDeliveryFee($Shipping);
400
                    }
401
402
                    $Shipping->setDeliveryFee($deliveryFee);
403
                    $Shipping->setShippingDeliveryFee($deliveryFee->getFee() + $productDeliveryFeeTotal);
404
                    $Shipping->setShippingDeliveryName($Delivery->getName());
405
                }
406
            }
407
408
            // 支払い情報をセット
409
            $payment = $data['payment'];
410
            $message = $data['message'];
411
412
            $Order->setPayment($payment);
413
            $Order->setPaymentMethod($payment->getMethod());
414
            $Order->setMessage($message);
415
            $Order->setCharge($payment->getCharge());
416
417
            $Order->setDeliveryFeeTotal($app['eccube.service.shopping']->getShippingDeliveryFeeTotal($shippings));
418
419
            // 合計金額の再計算
420
            $Order = $app['eccube.service.shopping']->getAmount($Order);
421
422
            // 受注関連情報を最新状態に更新
423
            $app['orm.em']->flush();
424
425
            $event = new EventArgs(
426
                array(
427
                    'form' => $form,
428
                    'Order' => $Order,
429
                ),
430
                $request
431
            );
432
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_DELIVERY_COMPLETE, $event);
433
434
            log_info('配送業者変更処理完了', array($Order->getId()));
435
            return $app->redirect($app->url('shopping'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
436
        }
437
438
        log_info('配送業者変更入力チェックエラー', array($Order->getId()));
439
        return $app->render('Shopping/index.twig', array(
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
440
            'form' => $form->createView(),
441
            'Order' => $Order,
442
        ));
443
    }
444
445
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
446
     * 支払い方法選択処理
447
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
448
    public function payment(Application $app, Request $request)
449
    {
450
        $Order = $app['eccube.service.shopping']->getOrder($app['config']['order_processing']);
451
        if (!$Order) {
452
            log_info('購入処理中の受注情報がないため購入エラー');
453
            $app->addError('front.shopping.order.error');
454
            return $app->redirect($app->url('shopping_error'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
455
        }
456
457
        if ('POST' !== $request->getMethod()) {
458
            return $app->redirect($app->url('shopping'));
459
        }
460
461
        $builder = $app['eccube.service.shopping']->getShippingFormBuilder($Order);
462
463
        $event = new EventArgs(
464
            array(
465
                'builder' => $builder,
466
                'Order' => $Order,
467
            ),
468
            $request
469
        );
470
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_PAYMENT_INITIALIZE, $event);
471
472
        $form = $builder->getForm();
473
474
        $form->handleRequest($request);
475
476
        if ($form->isSubmitted() && $form->isValid()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
477
478
            log_info('支払い方法変更処理開始', array("id" => $Order->getId()));
479
480
            $data = $form->getData();
481
            $payment = $data['payment'];
482
            $message = $data['message'];
483
484
            $Order->setPayment($payment);
485
            $Order->setPaymentMethod($payment->getMethod());
486
            $Order->setMessage($message);
487
            $Order->setCharge($payment->getCharge());
488
489
            // 合計金額の再計算
490
            $Order = $app['eccube.service.shopping']->getAmount($Order);
491
492
            // 受注関連情報を最新状態に更新
493
            $app['orm.em']->flush();
494
495
            $event = new EventArgs(
496
                array(
497
                    'form' => $form,
498
                    'Order' => $Order,
499
                ),
500
                $request
501
            );
502
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_PAYMENT_COMPLETE, $event);
503
504
            log_info('支払い方法変更処理完了', array("id" => $Order->getId(), "payment" => $payment->getId()));
505
506
            return $app->redirect($app->url('shopping'));
507
        }
508
509
        log_info('支払い方法変更入力チェックエラー', array("id" => $Order->getId()));
510
        return $app->render('Shopping/index.twig', array(
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
511
            'form' => $form->createView(),
512
            'Order' => $Order,
513
        ));
514
    }
515
516
    /**
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...
517
     * お届け先変更がクリックされた場合の処理
518
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
519 View Code Duplication
    public function shippingChange(Application $app, Request $request, $id)
520
    {
521
        $Order = $app['eccube.service.shopping']->getOrder($app['config']['order_processing']);
522
        if (!$Order) {
523
            $app->addError('front.shopping.order.error');
524
            return $app->redirect($app->url('shopping_error'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
525
        }
526
527
        if ('POST' !== $request->getMethod()) {
528
            return $app->redirect($app->url('shopping'));
529
        }
530
531
        $builder = $app['eccube.service.shopping']->getShippingFormBuilder($Order);
532
533
        $event = new EventArgs(
534
            array(
535
                'builder' => $builder,
536
                'Order' => $Order,
537
            ),
538
            $request
539
        );
540
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_CHANGE_INITIALIZE, $event);
541
542
        $form = $builder->getForm();
543
544
        $form->handleRequest($request);
545
546
        if ($form->isSubmitted() && $form->isValid()) {
547
            $data = $form->getData();
548
            $message = $data['message'];
549
            $Order->setMessage($message);
550
            // 受注情報を更新
551
            $app['orm.em']->flush();
552
553
            // お届け先設定一覧へリダイレクト
554
            return $app->redirect($app->url('shopping_shipping', array('id' => $id)));
555
        }
556
557
        return $app->render('Shopping/index.twig', array(
558
            'form' => $form->createView(),
559
            'Order' => $Order,
560
        ));
561
    }
562
563
    /**
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...
564
     * お届け先の設定一覧からの選択
565
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
566
    public function shipping(Application $app, Request $request, $id)
567
    {
568
        // カートチェック
569
        if (!$app['eccube.service.cart']->isLocked()) {
570
            // カートが存在しない、カートがロックされていない時はエラー
571
            log_info('カートが存在しません');
572
            return $app->redirect($app->url('cart'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
573
        }
574
575
        if ('POST' === $request->getMethod()) {
576
            $address = $request->get('address');
577
578
            if (is_null($address)) {
579
                // 選択されていなければエラー
580
                log_info('お届け先入力チェックエラー');
581
                return $app->render(
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
582
                    'Shopping/shipping.twig',
583
                    array(
584
                        'Customer' => $app->user(),
585
                        'shippingId' => $id,
586
                        'error' => true,
587
                    )
588
                );
589
            }
590
591
            // 選択されたお届け先情報を取得
592
            $CustomerAddress = $app['eccube.repository.customer_address']->findOneBy(array(
593
                'Customer' => $app->user(),
594
                'id' => $address,
595
            ));
596
            if (is_null($CustomerAddress)) {
597
                throw new NotFoundHttpException('選択されたお届け先住所が存在しない');
598
            }
599
600
            $Order = $app['eccube.service.shopping']->getOrder($app['config']['order_processing']);
601
            if (!$Order) {
602
                log_info('購入処理中の受注情報がないため購入エラー');
603
                $app->addError('front.shopping.order.error');
604
605
                return $app->redirect($app->url('shopping_error'));
606
            }
607
608
            $Shipping = $Order->findShipping($id);
609
            if (!$Shipping) {
610
                throw new NotFoundHttpException('お届け先情報が存在しない');
611
            }
612
613
            log_info('お届先情報更新開始', array($Shipping->getId()));
614
615
            // お届け先情報を更新
616
            $Shipping
617
                ->setFromCustomerAddress($CustomerAddress);
618
619
            // 配送料金の設定
620
            $app['eccube.service.shopping']->setShippingDeliveryFee($Shipping);
621
622
            // 合計金額の再計算
623
            $Order = $app['eccube.service.shopping']->getAmount($Order);
624
625
            // 配送先を更新
626
            $app['orm.em']->flush();
627
628
            $event = new EventArgs(
629
                array(
630
                    'Order' => $Order,
631
                    'shippingId' => $id,
632
                ),
633
                $request
634
            );
635
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_COMPLETE, $event);
636
637
            log_info('お届先情報更新完了', array($Shipping->getId()));
638
            return $app->redirect($app->url('shopping'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
639
        }
640
641
        return $app->render(
642
            'Shopping/shipping.twig',
643
            array(
644
                'Customer' => $app->user(),
645
                'shippingId' => $id,
646
                'error' => false,
647
            )
648
        );
649
    }
650
651
    /**
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...
652
     * お届け先の設定(非会員)がクリックされた場合の処理
653
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
654 View Code Duplication
    public function shippingEditChange(Application $app, Request $request, $id)
655
    {
656
        $Order = $app['eccube.service.shopping']->getOrder($app['config']['order_processing']);
657
        if (!$Order) {
658
            $app->addError('front.shopping.order.error');
659
            return $app->redirect($app->url('shopping_error'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
660
        }
661
662
        if ('POST' !== $request->getMethod()) {
663
            return $app->redirect($app->url('shopping'));
664
        }
665
666
        $builder = $app['eccube.service.shopping']->getShippingFormBuilder($Order);
667
668
        $event = new EventArgs(
669
            array(
670
                'builder' => $builder,
671
                'Order' => $Order,
672
            ),
673
            $request
674
        );
675
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_EDIT_CHANGE_INITIALIZE, $event);
676
677
        $form = $builder->getForm();
678
679
        $form->handleRequest($request);
680
681
        if ($form->isSubmitted() && $form->isValid()) {
682
            $data = $form->getData();
683
            $message = $data['message'];
684
            $Order->setMessage($message);
685
            // 受注情報を更新
686
            $app['orm.em']->flush();
687
688
            // お届け先設定一覧へリダイレクト
689
            return $app->redirect($app->url('shopping_shipping_edit', array('id' => $id)));
690
        }
691
692
        return $app->render('Shopping/index.twig', array(
693
            'form' => $form->createView(),
694
            'Order' => $Order,
695
        ));
696
    }
697
698
    /**
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...
699
     * お届け先の設定(非会員でも使用する)
700
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
701
    public function shippingEdit(Application $app, Request $request, $id)
702
    {
703
        // 配送先住所最大値判定
704
        $Customer = $app->user();
705 View Code Duplication
        if ($app->isGranted('IS_AUTHENTICATED_FULLY')) {
706
            $addressCurrNum = count($app->user()->getCustomerAddresses());
707
            $addressMax = $app['config']['deliv_addr_max'];
708
            if ($addressCurrNum >= $addressMax) {
709
                throw new NotFoundHttpException('配送先住所最大数エラー');
710
            }
711
        }
712
713
        // カートチェック
714
        if (!$app['eccube.service.cart']->isLocked()) {
715
            // カートが存在しない、カートがロックされていない時はエラー
716
            log_info('カートが存在しません');
717
            return $app->redirect($app->url('cart'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
718
        }
719
720
        $Order = $app['eccube.service.shopping']->getOrder($app['config']['order_processing']);
721
        if (!$Order) {
722
            log_info('購入処理中の受注情報がないため購入エラー');
723
            $app->addError('front.shopping.order.error');
724
            return $app->redirect($app->url('shopping_error'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
725
        }
726
727
        $Shipping = $Order->findShipping($id);
728
        if (!$Shipping) {
729
            throw new NotFoundHttpException('設定されている配送先が存在しない');
730
        }
731
        if ($app->isGranted('IS_AUTHENTICATED_FULLY')) {
732
            $Shipping->clearCustomerAddress();
733
        }
734
735
        $CustomerAddress = new CustomerAddress();
736
        if ($app->isGranted('IS_AUTHENTICATED_FULLY')) {
737
            $CustomerAddress->setCustomer($Customer);
738
        } else {
739
            $CustomerAddress->setFromShipping($Shipping);
740
        }
741
742
        $builder = $app['form.factory']->createBuilder('shopping_shipping', $CustomerAddress);
743
744
        $event = new EventArgs(
745
            array(
746
                'builder' => $builder,
747
                'Order' => $Order,
748
                'Shipping' => $Shipping,
749
                'CustomerAddress' => $CustomerAddress,
750
            ),
751
            $request
752
        );
753
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_EDIT_INITIALIZE, $event);
754
755
        $form = $builder->getForm();
756
757
        $form->handleRequest($request);
758
759
        if ($form->isSubmitted() && $form->isValid()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
760
761
            log_info('お届け先追加処理開始', array('id' => $Order->getId(), 'shipping' => $id));
762
763
            // 会員の場合、お届け先情報を新規登録
764
            $Shipping->setFromCustomerAddress($CustomerAddress);
765
766
            if ($Customer instanceof Customer) {
0 ignored issues
show
Bug introduced by
The class Eccube\Entity\Customer does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
767
                $app['orm.em']->persist($CustomerAddress);
768
                log_info('新規お届け先登録', array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
769
                    'id' => $Order->getId(),
770
                    'shipping' => $id,
771
                    '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...
772
            }
773
774
            // 配送料金の設定
775
            $app['eccube.service.shopping']->setShippingDeliveryFee($Shipping);
776
777
            // 合計金額の再計算
778
            $app['eccube.service.shopping']->getAmount($Order);
779
780
            // 配送先を更新 
781
            $app['orm.em']->flush();
782
783
            $event = new EventArgs(
784
                array(
785
                    'form' => $form,
786
                    'Shipping' => $Shipping,
787
                    'CustomerAddress' => $CustomerAddress,
788
                ),
789
                $request
790
            );
791
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_EDIT_COMPLETE, $event);
792
793
            log_info('お届け先追加処理完了', array('id' => $Order->getId(), 'shipping' => $id));
794
            return $app->redirect($app->url('shopping'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
795
        }
796
797
        return $app->render('Shopping/shipping_edit.twig', array(
798
            'form' => $form->createView(),
799
            'shippingId' => $id,
800
        ));
801
    }
802
803
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
804
     * お客様情報の変更(非会員)
805
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
806
    public function customer(Application $app, Request $request)
807
    {
808
        if ($request->isXmlHttpRequest()) {
809
            try {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
810
811
                log_info('非会員お客様情報変更処理開始');
812
813
                $data = $request->request->all();
814
815
                // 入力チェック
816
                $errors = $this->customerValidation($app, $data);
817
818
                foreach ($errors as $error) {
819 View Code Duplication
                    if ($error->count() != 0) {
820
                        log_info('非会員お客様情報変更入力チェックエラー');
821
                        $response = new Response(json_encode('NG'), 400);
822
                        $response->headers->set('Content-Type', 'application/json');
823
                        return $response;
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
824
                    }
825
                }
826
827
                $pref = $app['eccube.repository.master.pref']->findOneBy(array('name' => $data['customer_pref']));
828 View Code Duplication
                if (!$pref) {
829
                    log_info('非会員お客様情報変更入力チェックエラー');
830
                    $response = new Response(json_encode('NG'), 400);
831
                    $response->headers->set('Content-Type', 'application/json');
832
                    return $response;
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
833
                }
834
835
                $Order = $app['eccube.service.shopping']->getOrder($app['config']['order_processing']);
836
                if (!$Order) {
837
                    log_info('カートが存在しません');
838
                    $app->addError('front.shopping.order.error');
839
                    return $app->redirect($app->url('shopping_error'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
840
                }
841
842
                $Order
843
                    ->setName01($data['customer_name01'])
844
                    ->setName02($data['customer_name02'])
845
                    ->setCompanyName($data['customer_company_name'])
846
                    ->setTel01($data['customer_tel01'])
847
                    ->setTel02($data['customer_tel02'])
848
                    ->setTel03($data['customer_tel03'])
849
                    ->setZip01($data['customer_zip01'])
850
                    ->setZip02($data['customer_zip02'])
851
                    ->setZipCode($data['customer_zip01'].$data['customer_zip02'])
852
                    ->setPref($pref)
853
                    ->setAddr01($data['customer_addr01'])
854
                    ->setAddr02($data['customer_addr02'])
855
                    ->setEmail($data['customer_email']);
856
857
                // 配送先を更新
858
                $app['orm.em']->flush();
859
860
                // 受注関連情報を最新状態に更新
861
                $app['orm.em']->refresh($Order);
862
863
                $event = new EventArgs(
864
                    array(
865
                        'Order' => $Order,
866
                        'data' => $data,
867
                    ),
868
                    $request
869
                );
870
                $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_CUSTOMER_INITIALIZE, $event);
871
872
                log_info('非会員お客様情報変更処理完了', array($Order->getId()));
873
                $response = new Response(json_encode('OK'));
874
                $response->headers->set('Content-Type', 'application/json');
875
            } catch (\Exception $e) {
876
                log_error('予期しないエラー', array($e->getMessage()));
877
                $app['monolog']->error($e);
878
879
                $response = new Response(json_encode('NG'), 500);
880
                $response->headers->set('Content-Type', 'application/json');
881
            }
882
883
            return $response;
884
        }
885
    }
886
887
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
888
     * ログイン
889
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
890
    public function login(Application $app, Request $request)
891
    {
892
        if (!$app['eccube.service.cart']->isLocked()) {
893
            return $app->redirect($app->url('cart'));
894
        }
895
896
        if ($app->isGranted('IS_AUTHENTICATED_FULLY')) {
897
            return $app->redirect($app->url('shopping'));
898
        }
899
900
        /* @var $form \Symfony\Component\Form\FormInterface */
901
        $builder = $app['form.factory']->createNamedBuilder('', 'customer_login');
902
903 View Code Duplication
        if ($app->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
904
            $Customer = $app->user();
905
            if ($Customer) {
906
                $builder->get('login_email')->setData($Customer->getEmail());
907
            }
908
        }
909
910
        $event = new EventArgs(
911
            array(
912
                'builder' => $builder,
913
            ),
914
            $request
915
        );
916
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_LOGIN_INITIALIZE, $event);
917
918
        $form = $builder->getForm();
919
920
        return $app->render('Shopping/login.twig', array(
921
            'error' => $app['security.last_error']($request),
922
            'form' => $form->createView(),
923
        ));
924
    }
925
926
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
927
     * 非会員処理
928
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
929
    public function nonmember(Application $app, Request $request)
930
    {
931
        $cartService = $app['eccube.service.cart'];
932
933
        // カートチェック
934
        if (!$cartService->isLocked()) {
935
            // カートが存在しない、カートがロックされていない時はエラー
936
            log_info('カートが存在しません');
937
            return $app->redirect($app->url('cart'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
938
        }
939
940
        // ログイン済みの場合は, 購入画面へリダイレクト.
941
        if ($app->isGranted('ROLE_USER')) {
942
            return $app->redirect($app->url('shopping'));
943
        }
944
945
        // カートチェック
946 View Code Duplication
        if (count($cartService->getCart()->getCartItems()) <= 0) {
947
            // カートが存在しない時はエラー
948
            log_info('カートに商品が入っていないためショッピングカート画面にリダイレクト');
949
            return $app->redirect($app->url('cart'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
950
        }
951
952
        $builder = $app['form.factory']->createBuilder('nonmember');
953
954
        $event = new EventArgs(
955
            array(
956
                'builder' => $builder,
957
            ),
958
            $request
959
        );
960
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_NONMEMBER_INITIALIZE, $event);
961
962
        $form = $builder->getForm();
963
964
        $form->handleRequest($request);
965
966
        if ($form->isSubmitted() && $form->isValid()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
967
968
            log_info('非会員お客様情報登録開始');
969
970
            $data = $form->getData();
971
            $Customer = new Customer();
972
            $Customer
973
                ->setName01($data['name01'])
974
                ->setName02($data['name02'])
975
                ->setKana01($data['kana01'])
976
                ->setKana02($data['kana02'])
977
                ->setCompanyName($data['company_name'])
978
                ->setEmail($data['email'])
979
                ->setTel01($data['tel01'])
980
                ->setTel02($data['tel02'])
981
                ->setTel03($data['tel03'])
982
                ->setZip01($data['zip01'])
983
                ->setZip02($data['zip02'])
984
                ->setZipCode($data['zip01'].$data['zip02'])
985
                ->setPref($data['pref'])
986
                ->setAddr01($data['addr01'])
987
                ->setAddr02($data['addr02']);
988
989
            // 非会員複数配送用
990
            $CustomerAddress = new CustomerAddress();
991
            $CustomerAddress
992
                ->setCustomer($Customer)
993
                ->setName01($data['name01'])
994
                ->setName02($data['name02'])
995
                ->setKana01($data['kana01'])
996
                ->setKana02($data['kana02'])
997
                ->setCompanyName($data['company_name'])
998
                ->setTel01($data['tel01'])
999
                ->setTel02($data['tel02'])
1000
                ->setTel03($data['tel03'])
1001
                ->setZip01($data['zip01'])
1002
                ->setZip02($data['zip02'])
1003
                ->setZipCode($data['zip01'].$data['zip02'])
1004
                ->setPref($data['pref'])
1005
                ->setAddr01($data['addr01'])
1006
                ->setAddr02($data['addr02'])
1007
                ->setDelFlg(Constant::DISABLED);
1008
            $Customer->addCustomerAddress($CustomerAddress);
1009
1010
            // 受注情報を取得
1011
            $Order = $app['eccube.service.shopping']->getOrder($app['config']['order_processing']);
1012
1013
            // 初回アクセス(受注データがない)の場合は, 受注情報を作成
1014
            if (is_null($Order)) {
1015
                // 受注情報を作成
1016
                try {
1017
                    // 受注情報を作成
1018
                    $Order = $app['eccube.service.shopping']->createOrder($Customer);
1019
                } catch (CartException $e) {
1020
                    $app->addRequestError($e->getMessage());
1021
                    return $app->redirect($app->url('cart'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
1022
                }
1023
            }
1024
1025
            // 非会員用セッションを作成
1026
            $nonMember = array();
1027
            $nonMember['customer'] = $Customer;
1028
            $nonMember['pref'] = $Customer->getPref()->getId();
1029
            $app['session']->set($this->sessionKey, $nonMember);
1030
1031
            $customerAddresses = array();
1032
            $customerAddresses[] = $CustomerAddress;
1033
            $app['session']->set($this->sessionCustomerAddressKey, serialize($customerAddresses));
1034
1035
            $event = new EventArgs(
1036
                array(
1037
                    'form' => $form,
1038
                    'Order' => $Order,
1039
                ),
1040
                $request
1041
            );
1042
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_NONMEMBER_COMPLETE, $event);
1043
1044
            if ($event->getResponse() !== null) {
1045
                return $event->getResponse();
1046
            }
1047
1048
            log_info('非会員お客様情報登録完了', array($Order->getId()));
1049
1050
            return $app->redirect($app->url('shopping'));
1051
        }
1052
1053
        return $app->render('Shopping/nonmember.twig', array(
1054
            'form' => $form->createView(),
1055
        ));
1056
    }
1057
1058
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
1059
     * 複数配送処理がクリックされた場合の処理
1060
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
1061 View Code Duplication
    public function shippingMultipleChange(Application $app, Request $request)
1062
    {
1063
        $Order = $app['eccube.service.shopping']->getOrder($app['config']['order_processing']);
1064
        if (!$Order) {
1065
            $app->addError('front.shopping.order.error');
1066
            return $app->redirect($app->url('shopping_error'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
1067
        }
1068
1069
        if ('POST' !== $request->getMethod()) {
1070
            return $app->redirect($app->url('shopping'));
1071
        }
1072
1073
        $builder = $app['eccube.service.shopping']->getShippingFormBuilder($Order);
1074
1075
        $event = new EventArgs(
1076
            array(
1077
                'builder' => $builder,
1078
                'Order' => $Order,
1079
            ),
1080
            $request
1081
        );
1082
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_MULTIPLE_CHANGE_INITIALIZE, $event);
1083
1084
        $form = $builder->getForm();
1085
1086
        $form->handleRequest($request);
1087
1088
        if ($form->isSubmitted() && $form->isValid()) {
1089
            $data = $form->getData();
1090
            $message = $data['message'];
1091
            $Order->setMessage($message);
1092
            // 受注情報を更新
1093
            $app['orm.em']->flush();
1094
1095
            // 複数配送設定へリダイレクト
1096
            return $app->redirect($app->url('shopping_shipping_multiple'));
1097
        }
1098
1099
        return $app->render('Shopping/index.twig', array(
1100
            'form' => $form->createView(),
1101
            'Order' => $Order,
1102
        ));
1103
    }
1104
1105
1106
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
1107
     * 複数配送処理
1108
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
1109
    public function shippingMultiple(Application $app, Request $request)
1110
    {
1111
        $cartService = $app['eccube.service.cart'];
1112
1113
        // カートチェック
1114
        if (!$cartService->isLocked()) {
1115
            // カートが存在しない、カートがロックされていない時はエラー
1116
            log_info('カートが存在しません');
1117
            return $app->redirect($app->url('cart'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
1118
        }
1119
1120
        // カートチェック
1121 View Code Duplication
        if (count($cartService->getCart()->getCartItems()) <= 0) {
1122
            // カートが存在しない時はエラー
1123
            log_info('カートに商品が入っていないためショッピングカート画面にリダイレクト');
1124
            return $app->redirect($app->url('cart'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
1125
        }
1126
1127
        /** @var \Eccube\Entity\Order $Order */
1128
        $Order = $app['eccube.service.shopping']->getOrder($app['config']['order_processing']);
1129
        if (!$Order) {
1130
            log_info('購入処理中の受注情報がないため購入エラー');
1131
            $app->addError('front.shopping.order.error');
1132
            return $app->redirect($app->url('shopping_error'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
1133
        }
1134
1135
        // 処理しやすいようにすべてのShippingItemをまとめる
1136
        $ShipmentItems = array();
1137
        foreach ($Order->getShippings() as $Shipping) {
1138
            foreach ($Shipping->getShipmentItems() as $ShipmentItem) {
1139
                $ShipmentItems[] = $ShipmentItem;
1140
            }
1141
        }
1142
1143
        // Orderに含まれる商品ごとの数量を求める
1144
        $ItemQuantitiesByClassId = array();
1145
        foreach ($ShipmentItems as $item) {
1146
            $itemId = $item->getProductClass()->getId();
1147
            $quantity = $item->getQuantity();
1148
            if (array_key_exists($itemId, $ItemQuantitiesByClassId)) {
1149
                $ItemQuantitiesByClassId[$itemId] += $quantity;
1150
            } else {
1151
                $ItemQuantitiesByClassId[$itemId] = $quantity;
1152
            }
1153
        }
1154
1155
        // FormBuilder用に商品ごとにShippingItemをまとめる
1156
        $ShipmentItemsForFormBuilder = array();
1157
        $tmpAddedClassIds = array();
1158
        foreach ($ShipmentItems as $item) {
1159
            $itemId = $item->getProductClass()->getId();
1160
            if (!in_array($itemId, $tmpAddedClassIds)) {
1161
                $ShipmentItemsForFormBuilder[] = $item;
1162
                $tmpAddedClassIds[] = $itemId;
1163
            }
1164
        }
1165
1166
        // Form生成
1167
        $builder = $app->form();
1168
        $builder
1169
            ->add('shipping_multiple', 'collection', array(
1170
                'type' => 'shipping_multiple',
1171
                'data' => $ShipmentItemsForFormBuilder,
1172
                'allow_add' => true,
1173
                'allow_delete' => true,
1174
            ));
1175
        // Event
1176
        $event = new EventArgs(
1177
            array(
1178
                'builder' => $builder,
1179
                'Order' => $Order,
1180
            ),
1181
            $request
1182
        );
1183
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_MULTIPLE_INITIALIZE, $event);
1184
1185
        $form = $builder->getForm();
1186
        $form->handleRequest($request);
1187
1188
        $errors = array();
1189
        if ($form->isSubmitted() && $form->isValid()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
1190
1191
            log_info('複数配送設定処理開始', array($Order->getId()));
1192
1193
            $data = $form['shipping_multiple'];
1194
1195
            // フォームの入力から、送り先ごとに商品の数量を集計する
1196
            $arrShipmentItemTemp = array();
1197
            foreach ($data as $mulitples) {
1198
                $ShipmentItem = $mulitples->getData();
1199
                foreach ($mulitples as $items) {
1200
                    foreach ($items as $item) {
1201
                        $cusAddId = $this->getCustomerAddressId($item['customer_address']->getData());
1202
                        $itemId = $ShipmentItem->getProductClass()->getId();
1203
                        $quantity = $item['quantity']->getData();
1204
1205
                        if (isset($arrShipmentItemTemp[$cusAddId]) && array_key_exists($itemId, $arrShipmentItemTemp[$cusAddId])) {
1206
                            $arrShipmentItemTemp[$cusAddId][$itemId] = $arrShipmentItemTemp[$cusAddId][$itemId] + $quantity;
1207
                        } else {
1208
                            $arrShipmentItemTemp[$cusAddId][$itemId] = $quantity;
1209
                        }
1210
                    }
1211
                }
1212
            }
1213
1214
            // フォームの入力から、商品ごとの数量を集計する
1215
            $itemQuantities = array();
1216
            foreach ($arrShipmentItemTemp as $FormItemByAddress) {
1217
                foreach ($FormItemByAddress as $itemId => $quantity) {
1218
                    if (array_key_exists($itemId, $itemQuantities)) {
1219
                        $itemQuantities[$itemId] = $itemQuantities[$itemId] + $quantity;
1220
                    } else {
1221
                        $itemQuantities[$itemId] = $quantity;
1222
                    }
1223
                }
1224
            }
1225
1226
            // 「Orderに含まれる商品ごとの数量」と「フォームに入力された商品ごとの数量」が一致しているかの確認
1227
            // 数量が異なっているならエラーを表示する
1228
            foreach ($ItemQuantitiesByClassId as $key => $value) {
1229
                if (array_key_exists($key, $itemQuantities)) {
1230
                    if ($itemQuantities[$key] != $value) {
1231
                        $errors[] = array('message' => $app->trans('shopping.multiple.quantity.diff'));
1232
1233
                        // 対象がなければエラー
1234
                        log_info('複数配送設定入力チェックエラー', array($Order->getId()));
1235
                        return $app->render('Shopping/shipping_multiple.twig', array(
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
1236
                            'form' => $form->createView(),
1237
                            'shipmentItems' => $ShipmentItemsForFormBuilder,
1238
                            'compItemQuantities' => $ItemQuantitiesByClassId,
1239
                            'errors' => $errors,
1240
                        ));
1241
                    }
1242
                }
1243
            }
1244
1245
            // -- ここから先がお届け先を再生成する処理 --
1246
1247
            // お届け先情報をすべて削除
1248
            foreach ($Order->getShippings() as $Shipping) {
1249
                $Order->removeShipping($Shipping);
1250
                $app['orm.em']->remove($Shipping);
1251
            }
1252
1253
            // お届け先のリストを作成する
1254
            $ShippingList = array();
1255
            foreach ($data as $mulitples) {
1256
                $ShipmentItem = $mulitples->getData();
1257
                $ProductClass = $ShipmentItem->getProductClass();
1258
                $Delivery = $ShipmentItem->getShipping()->getDelivery();
1259
                $productTypeId = $ProductClass->getProductType()->getId();
1260
1261
                foreach ($mulitples as $items) {
1262
                    foreach ($items as $item) {
1263
                        $CustomerAddress = $this->getCustomerAddress($app, $item['customer_address']->getData());
1264
                        $cusAddId = $this->getCustomerAddressId($item['customer_address']->getData());
1265
1266
                        $Shipping = new Shipping();
1267
                        $Shipping
1268
                            ->setFromCustomerAddress($CustomerAddress)
1269
                            ->setDelivery($Delivery)
1270
                            ->setDelFlg(Constant::DISABLED)
1271
                            ->setOrder($Order);
1272
1273
                        $ShippingList[$cusAddId][$productTypeId] = $Shipping;
1274
                    }
1275
                }
1276
            }
1277
            // お届け先のリストを保存
1278
            foreach ($ShippingList as $ShippingListByAddress) {
1279
                foreach ($ShippingListByAddress as $Shipping) {
1280
                    $app['orm.em']->persist($Shipping);
1281
                }
1282
            }
1283
1284
            // お届け先に、配送商品の情報(ShipmentItem)を関連付ける
1285
            foreach ($data as $mulitples) {
1286
                $ShipmentItem = $mulitples->getData();
1287
                $ProductClass = $ShipmentItem->getProductClass();
1288
                $Product = $ShipmentItem->getProduct();
1289
                $productTypeId = $ProductClass->getProductType()->getId();
1290
                $productClassId = $ProductClass->getId();
1291
1292
                foreach ($mulitples as $items) {
1293
                    foreach ($items as $item) {
1294
                        $cusAddId = $this->getCustomerAddressId($item['customer_address']->getData());
1295
1296
                        // お届け先から商品の数量を取得
1297
                        $quantity = 0;
0 ignored issues
show
Unused Code introduced by
$quantity 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...
1298
                        if (isset($arrShipmentItemTemp[$cusAddId]) && array_key_exists($productClassId, $arrShipmentItemTemp[$cusAddId])) {
1299
                            $quantity = $arrShipmentItemTemp[$cusAddId][$productClassId];
1300
                            unset($arrShipmentItemTemp[$cusAddId][$productClassId]);
1301
                        } else {
1302
                            // この配送先には送る商品がないのでスキップ(通常ありえない)
1303
                            continue;
1304
                        }
1305
1306
                        // 関連付けるお届け先のインスタンスを取得
1307
                        $Shipping = $ShippingList[$cusAddId][$productTypeId];
1308
1309
                        // インスタンスを生成して保存
1310
                        $ShipmentItem = new ShipmentItem();
1311
                        $ShipmentItem->setShipping($Shipping)
1312
                            ->setOrder($Order)
1313
                            ->setProductClass($ProductClass)
1314
                            ->setProduct($Product)
1315
                            ->setProductName($Product->getName())
1316
                            ->setProductCode($ProductClass->getCode())
1317
                            ->setPrice($ProductClass->getPrice02())
1318
                            ->setQuantity($quantity);
1319
1320
                        $ClassCategory1 = $ProductClass->getClassCategory1();
1321
                        if (!is_null($ClassCategory1)) {
1322
                            $ShipmentItem->setClasscategoryName1($ClassCategory1->getName());
1323
                            $ShipmentItem->setClassName1($ClassCategory1->getClassName()->getName());
1324
                        }
1325
                        $ClassCategory2 = $ProductClass->getClassCategory2();
1326
                        if (!is_null($ClassCategory2)) {
1327
                            $ShipmentItem->setClasscategoryName2($ClassCategory2->getName());
1328
                            $ShipmentItem->setClassName2($ClassCategory2->getClassName()->getName());
1329
                        }
1330
                        $Shipping->addShipmentItem($ShipmentItem);
1331
                        $app['orm.em']->persist($ShipmentItem);
1332
                    }
1333
                }
1334
            }
1335
1336
            // 送料を計算(お届け先ごと)
1337
            foreach ($ShippingList as $data) {
1338
                // data is product type => shipping
1339
                foreach ($data as $Shipping) {
1340
                    // 配送料金の設定
1341
                    $app['eccube.service.shopping']->setShippingDeliveryFee($Shipping);
1342
                    $Order->addShipping($Shipping);
1343
                }
1344
            }
1345
1346
            // 合計金額の再計算
1347
            $Order = $app['eccube.service.shopping']->getAmount($Order);
1348
1349
            // 配送先を更新
1350
            $app['orm.em']->flush();
1351
1352
            $event = new EventArgs(
1353
                array(
1354
                    'form' => $form,
1355
                    'Order' => $Order,
1356
                ),
1357
                $request
1358
            );
1359
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_MULTIPLE_COMPLETE, $event);
1360
1361
            log_info('複数配送設定処理完了', array($Order->getId()));
1362
            return $app->redirect($app->url('shopping'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
1363
        }
1364
1365
        return $app->render('Shopping/shipping_multiple.twig', array(
1366
            'form' => $form->createView(),
1367
            'shipmentItems' => $ShipmentItemsForFormBuilder,
1368
            'compItemQuantities' => $ItemQuantitiesByClassId,
1369
            'errors' => $errors,
1370
        ));
1371
    }
1372
1373
    /**
1374
     * フォームの情報からお届け先のインデックスを返す
1375
     *
1376
     * @param Application $app
0 ignored issues
show
Bug introduced by
There is no parameter named $app. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
1377
     * @param mixed $CustomerAddressData
1378
     * @return int
1379
     */
1380
    private function getCustomerAddressId($CustomerAddressData)
1381
    {
1382
        if ($CustomerAddressData instanceof CustomerAddress) {
0 ignored issues
show
Bug introduced by
The class Eccube\Entity\CustomerAddress does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
1383
            return $CustomerAddressData->getId();
1384
        } else {
1385
            return $CustomerAddressData;
1386
        }
1387
    }
1388
1389
    /**
1390
     * フォームの情報からお届け先のインスタンスを返す
1391
     *
1392
     * @param Application $app
1393
     * @param mixed $CustomerAddressData
1394
     * @return CustomerAddress
1395
     */
1396
    private function getCustomerAddress(Application $app, $CustomerAddressData)
1397
    {
1398
        if ($CustomerAddressData instanceof CustomerAddress) {
0 ignored issues
show
Bug introduced by
The class Eccube\Entity\CustomerAddress does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
1399
            return $CustomerAddressData;
1400
        } else {
1401
            $cusAddId = $CustomerAddressData;
1402
            $customerAddresses = $app['session']->get($this->sessionCustomerAddressKey);
1403
            $customerAddresses = unserialize($customerAddresses);
1404
1405
            $CustomerAddress = $customerAddresses[$cusAddId];
1406
            $pref = $app['eccube.repository.master.pref']->find($CustomerAddress->getPref()->getId());
1407
            $CustomerAddress->setPref($pref);
1408
1409
            return $CustomerAddress;
1410
        }
1411
    }
1412
1413
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
1414
     * 非会員用複数配送設定時の新規お届け先の設定
1415
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
1416
    public function shippingMultipleEdit(Application $app, Request $request)
0 ignored issues
show
introduced by
Declare public methods first, then protected ones and finally private ones
Loading history...
1417
    {
1418
        // カートチェック
1419
        if (!$app['eccube.service.cart']->isLocked()) {
1420
            log_info('カートが存在しません');
1421
            // カートが存在しない、カートがロックされていない時はエラー
1422
            return $app->redirect($app->url('cart'));
1423
        }
1424
1425
        // 非会員用Customerを取得
1426
        $Customer = $app['eccube.service.shopping']->getNonMember($this->sessionKey);
1427
        $CustomerAddress = new CustomerAddress();
1428
        $CustomerAddress->setCustomer($Customer);
1429
        $Customer->addCustomerAddress($CustomerAddress);
1430
1431
        $builder = $app['form.factory']->createBuilder('shopping_shipping', $CustomerAddress);
1432
1433
        $event = new EventArgs(
1434
            array(
1435
                'builder' => $builder,
1436
                'Customer' => $Customer,
1437
            ),
1438
            $request
1439
        );
1440
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_MULTIPLE_EDIT_INITIALIZE, $event);
1441
1442
        $form = $builder->getForm();
1443
1444
        $form->handleRequest($request);
1445
1446
        if ($form->isSubmitted() && $form->isValid()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
1447
1448
            log_info('非会員お届け先追加処理開始');
1449
1450
            // 非会員用のセッションに追加
1451
            $customerAddresses = $app['session']->get($this->sessionCustomerAddressKey);
1452
            $customerAddresses = unserialize($customerAddresses);
1453
            $customerAddresses[] = $CustomerAddress;
1454
            $app['session']->set($this->sessionCustomerAddressKey, serialize($customerAddresses));
1455
1456
            $event = new EventArgs(
1457
                array(
1458
                    'form' => $form,
1459
                    'CustomerAddresses' => $customerAddresses,
1460
                ),
1461
                $request
1462
            );
1463
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_MULTIPLE_EDIT_COMPLETE, $event);
1464
1465
            log_info('非会員お届け先追加処理完了');
1466
1467
            return $app->redirect($app->url('shopping_shipping_multiple'));
1468
        }
1469
1470
        return $app->render('Shopping/shipping_multiple_edit.twig', array(
1471
            'form' => $form->createView(),
1472
        ));
1473
    }
1474
1475
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
1476
     * 購入エラー画面表示
1477
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
1478
    public function shoppingError(Application $app, Request $request)
1479
    {
1480
1481
        $event = new EventArgs(
1482
            array(),
1483
            $request
1484
        );
1485
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_ERROR_COMPLETE, $event);
1486
1487
        if ($event->getResponse() !== null) {
1488
            return $event->getResponse();
1489
        }
1490
1491
        return $app->render('Shopping/shopping_error.twig');
1492
    }
1493
1494
    /**
1495
     * 非会員でのお客様情報変更時の入力チェック
1496
     *
1497
     * @param Application $app
1498
     * @param array $data リクエストパラメータ
1499
     * @return array
1500
     */
1501
    private function customerValidation(Application $app, array $data)
1502
    {
1503
        // 入力チェック
1504
        $errors = array();
1505
1506
        $errors[] = $app['validator']->validateValue($data['customer_name01'], array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
1507
            new Assert\NotBlank(),
1508
            new Assert\Length(array('max' => $app['config']['name_len'],)),
0 ignored issues
show
introduced by
Add a single space after each comma delimiter
Loading history...
1509
            new Assert\Regex(array('pattern' => '/^[^\s ]+$/u', 'message' => 'form.type.name.firstname.nothasspace'))
1510
        ));
1511
1512
        $errors[] = $app['validator']->validateValue($data['customer_name02'], array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
1513
            new Assert\NotBlank(),
1514
            new Assert\Length(array('max' => $app['config']['name_len'],)),
0 ignored issues
show
introduced by
Add a single space after each comma delimiter
Loading history...
1515
            new Assert\Regex(array('pattern' => '/^[^\s ]+$/u', 'message' => 'form.type.name.firstname.nothasspace'))
1516
        ));
1517
1518
        $errors[] = $app['validator']->validateValue($data['customer_company_name'], array(
1519
            new Assert\Length(array('max' => $app['config']['stext_len'])),
1520
        ));
1521
1522
        $errors[] = $app['validator']->validateValue($data['customer_tel01'], array(
1523
            new Assert\NotBlank(),
1524
            new Assert\Type(array('type' => 'numeric', 'message' => 'form.type.numeric.invalid')),
1525
            new Assert\Length(array('max' => $app['config']['tel_len'], 'min' => $app['config']['tel_len_min'])),
1526
        ));
1527
1528
        $errors[] = $app['validator']->validateValue($data['customer_tel02'], array(
1529
            new Assert\NotBlank(),
1530
            new Assert\Type(array('type' => 'numeric', 'message' => 'form.type.numeric.invalid')),
1531
            new Assert\Length(array('max' => $app['config']['tel_len'], 'min' => $app['config']['tel_len_min'])),
1532
        ));
1533
1534
        $errors[] = $app['validator']->validateValue($data['customer_tel03'], array(
1535
            new Assert\NotBlank(),
1536
            new Assert\Type(array('type' => 'numeric', 'message' => 'form.type.numeric.invalid')),
1537
            new Assert\Length(array('max' => $app['config']['tel_len'], 'min' => $app['config']['tel_len_min'])),
1538
        ));
1539
1540
        $errors[] = $app['validator']->validateValue($data['customer_zip01'], array(
1541
            new Assert\NotBlank(),
1542
            new Assert\Type(array('type' => 'numeric', 'message' => 'form.type.numeric.invalid')),
1543
            new Assert\Length(array('min' => $app['config']['zip01_len'], 'max' => $app['config']['zip01_len'])),
1544
        ));
1545
1546
        $errors[] = $app['validator']->validateValue($data['customer_zip02'], array(
1547
            new Assert\NotBlank(),
1548
            new Assert\Type(array('type' => 'numeric', 'message' => 'form.type.numeric.invalid')),
1549
            new Assert\Length(array('min' => $app['config']['zip02_len'], 'max' => $app['config']['zip02_len'])),
1550
        ));
1551
1552
        $errors[] = $app['validator']->validateValue($data['customer_addr01'], array(
1553
            new Assert\NotBlank(),
1554
            new Assert\Length(array('max' => $app['config']['address1_len'])),
1555
        ));
1556
1557
        $errors[] = $app['validator']->validateValue($data['customer_addr02'], array(
1558
            new Assert\NotBlank(),
1559
            new Assert\Length(array('max' => $app['config']['address2_len'])),
1560
        ));
1561
1562
        $errors[] = $app['validator']->validateValue($data['customer_email'], array(
1563
            new Assert\NotBlank(),
1564
            new Assert\Email(array('strict' => true)),
1565
        ));
1566
1567
        return $errors;
1568
    }
1569
}
1570