Failed Conditions
Push — experimental/3.1 ( 94d0cd...3ded70 )
by chihiro
23s
created

NonMemberShoppingController::index()   C

Complexity

Conditions 11
Paths 12

Size

Total Lines 133
Code Lines 87

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 76
CRAP Score 11.0284

Importance

Changes 0
Metric Value
cc 11
eloc 87
nc 12
nop 2
dl 0
loc 133
ccs 76
cts 81
cp 0.9383
crap 11.0284
rs 5.2653
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/*
3
 * This file is part of EC-CUBE
4
 *
5
 * Copyright(c) 2000-2017 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
namespace Eccube\Controller;
25
26
27
use Doctrine\ORM\EntityManager;
28
use Eccube\Annotation\Component;
29
use Eccube\Annotation\Inject;
30
use Eccube\Application;
31
use Eccube\Entity\Customer;
32
use Eccube\Entity\CustomerAddress;
33
use Eccube\Entity\Order;
34
use Eccube\Event\EccubeEvents;
35
use Eccube\Event\EventArgs;
36
use Eccube\Exception\CartException;
37
use Eccube\Form\Type\Front\NonMemberType;
38
use Eccube\Form\Type\Front\ShoppingShippingType;
39
use Eccube\Repository\Master\PrefRepository;
40
use Eccube\Service\CartService;
41
use Eccube\Service\OrderHelper;
42
use Eccube\Service\ShoppingService;
43
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
44
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
45
use Symfony\Bridge\Monolog\Logger;
46
use Symfony\Component\EventDispatcher\EventDispatcher;
47
use Symfony\Component\Form\FormFactory;
48
use Symfony\Component\HttpFoundation\Request;
49
use Symfony\Component\HttpFoundation\Response;
50
use Symfony\Component\HttpFoundation\Session\Session;
51
use Symfony\Component\Validator\Constraints as Assert;
52
use Symfony\Component\Validator\Validator\RecursiveValidator;
53
54
/**
55
 * @Component
56
 * @Route(service=NonMemberShoppingController::class)
57
 */
58
class NonMemberShoppingController extends AbstractShoppingController
59
{
60
    /**
61
     * @Inject("validator")
62
     * @var RecursiveValidator
63
     */
64
    protected $recursiveValidator;
65
66
    /**
67
     * @Inject("monolog")
68
     * @var Logger
69
     */
70
    protected $logger;
71
72
    /**
73
     * @Inject("orm.em")
74
     * @var EntityManager
75
     */
76
    protected $entityManager;
77
78
    /**
79
     * @Inject(PrefRepository::class)
80
     * @var PrefRepository
81
     */
82
    protected $prefRepository;
83
84
    /**
85
     * @Inject("session")
86
     * @var Session
87
     */
88
    protected $session;
89
90
    /**
91
     * @Inject(OrderHelper::class)
92
     * @var OrderHelper
93
     */
94
    protected $orderHelper;
95
96
    /**
97
     * @Inject("config")
98
     * @var array
99
     */
100
    protected $appConfig;
101
102
    /**
103
     * @Inject(ShoppingService::class)
104
     * @var ShoppingService
105
     */
106
    protected $shoppingService;
107
108
    /**
109
     * @Inject("eccube.event.dispatcher")
110
     * @var EventDispatcher
111
     */
112
    protected $eventDispatcher;
113
114
    /**
115
     * @Inject("form.factory")
116
     * @var FormFactory
117
     */
118
    protected $formFactory;
119
120
    /**
121
     * @Inject(CartService::class)
122
     * @var CartService
123
     */
124
    protected $cartService;
125
126
127
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
128
     * 非会員処理
129
     *
130
     * @Route("/shopping/nonmember", name="shopping_nonmember")
131
     * @Template("Shopping/nonmember.twig")
132
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
133 6
    public function index(Application $app, Request $request)
134
    {
135 6
        $cartService = $this->cartService;
136
137
        // カートチェック
138 6
        $response = $app->forward($app->path("shopping_check_to_cart"));
139 6
        if ($response->isRedirection() || $response->getContent()) {
140 1
            return $response;
141
        }
142
143
        // ログイン済みの場合は, 購入画面へリダイレクト.
144 5
        if ($app->isGranted('ROLE_USER')) {
145 1
            return $app->redirect($app->url('shopping'));
146
        }
147
148 4
        $builder = $this->formFactory->createBuilder(NonMemberType::class);
149
150 4
        $event = new EventArgs(
151
            array(
152 4
                'builder' => $builder,
153
            ),
154 4
            $request
155
        );
156 4
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_NONMEMBER_INITIALIZE, $event);
157
158 4
        $form = $builder->getForm();
159
160 4
        $form->handleRequest($request);
161
162 4
        if ($form->isSubmitted() && $form->isValid()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
163
164 3
            log_info('非会員お客様情報登録開始');
165
166 3
            $data = $form->getData();
167 3
            $Customer = new Customer();
168
            $Customer
169 3
                ->setName01($data['name01'])
170 3
                ->setName02($data['name02'])
171 3
                ->setKana01($data['kana01'])
172 3
                ->setKana02($data['kana02'])
173 3
                ->setCompanyName($data['company_name'])
174 3
                ->setEmail($data['email'])
175 3
                ->setTel01($data['tel01'])
176 3
                ->setTel02($data['tel02'])
177 3
                ->setTel03($data['tel03'])
178 3
                ->setZip01($data['zip01'])
179 3
                ->setZip02($data['zip02'])
180 3
                ->setZipCode($data['zip01'].$data['zip02'])
181 3
                ->setPref($data['pref'])
182 3
                ->setAddr01($data['addr01'])
183 3
                ->setAddr02($data['addr02']);
184
185
            // 非会員複数配送用
186 3
            $CustomerAddress = new CustomerAddress();
187
            $CustomerAddress
188 3
                ->setCustomer($Customer)
189 3
                ->setName01($data['name01'])
190 3
                ->setName02($data['name02'])
191 3
                ->setKana01($data['kana01'])
192 3
                ->setKana02($data['kana02'])
193 3
                ->setCompanyName($data['company_name'])
194 3
                ->setTel01($data['tel01'])
195 3
                ->setTel02($data['tel02'])
196 3
                ->setTel03($data['tel03'])
197 3
                ->setZip01($data['zip01'])
198 3
                ->setZip02($data['zip02'])
199 3
                ->setZipCode($data['zip01'].$data['zip02'])
200 3
                ->setPref($data['pref'])
201 3
                ->setAddr01($data['addr01'])
202 3
                ->setAddr02($data['addr02']);
203 3
            $Customer->addCustomerAddress($CustomerAddress);
204
205
            // 受注情報を取得
206
            /** @var Order $Order */
207 3
            $Order = $this->shoppingService->getOrder($this->appConfig['order_processing']);
208
209
            // 初回アクセス(受注データがない)の場合は, 受注情報を作成
210 3
            if (is_null($Order)) {
211
                // 受注情報を作成
212
                try {
213
                    // 受注情報を作成
214
//                    $Order = $app['eccube.service.shopping']->createOrder($Customer);
215 3
                    $Order = $this->orderHelper->createProcessingOrder(
216 3
                        $Customer,
217 3
                        $Customer->getCustomerAddresses()->current(),
218 3
                        $cartService->getCart()->getCartItems()
219
                    );
220 3
                    $cartService->setPreOrderId($Order->getPreOrderId());
221 3
                    $cartService->save();
222
                } catch (CartException $e) {
223
                    $app->addRequestError($e->getMessage());
224
225
                    return $app->redirect($app->url('cart'));
226
                }
227
            }
228
229 3
            $flowResult = $this->executePurchaseFlow($app, $Order);
230 3
            if ($flowResult->hasWarning() || $flowResult->hasError()) {
231
                return $app->redirect($app->url('cart'));
232
            }
233
234
            // 非会員用セッションを作成
235 3
            $nonMember = array();
236 3
            $nonMember['customer'] = $Customer;
237 3
            $nonMember['pref'] = $Customer->getPref()->getId();
238 3
            $this->session->set($this->sessionKey, $nonMember);
239
240 3
            $customerAddresses = array();
241 3
            $customerAddresses[] = $CustomerAddress;
242 3
            $this->session->set($this->sessionCustomerAddressKey, serialize($customerAddresses));
243
244 3
            $event = new EventArgs(
245
                array(
246 3
                    'form' => $form,
247 3
                    'Order' => $Order,
248
                ),
249 3
                $request
250
            );
251 3
            $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_NONMEMBER_COMPLETE, $event);
252
253 3
            if ($event->getResponse() !== null) {
254
                return $event->getResponse();
255
            }
256
257 3
            log_info('非会員お客様情報登録完了', array($Order->getId()));
258
259 3
            return $app->redirect($app->url('shopping'));
260
        }
261
262
        return [
263 1
            'form' => $form->createView(),
264
        ];
265
    }
266
267
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
268
     * 非会員用複数配送設定時の新規お届け先の設定
269
     *
270
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
271
    public function shippingMultipleEdit(Application $app, Request $request)
272
    {
273
        // カートチェック
274
        $response = $app->forward($app->path("shopping_check_to_art"));
275
        if ($response->isRedirection() || $response->getContent()) {
276
            return $response;
277
        }
278
279
        // 非会員用Customerを取得
280
        $Customer = $this->shoppingService->getNonMember($this->sessionKey);
281
        $CustomerAddress = new CustomerAddress();
282
        $CustomerAddress->setCustomer($Customer);
283
        $Customer->addCustomerAddress($CustomerAddress);
284
285
        $builder = $this->formFactory->createBuilder(ShoppingShippingType::class, $CustomerAddress);
286
287
        $event = new EventArgs(
288
            array(
289
                'builder' => $builder,
290
                'Customer' => $Customer,
291
            ),
292
            $request
293
        );
294
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_MULTIPLE_EDIT_INITIALIZE, $event);
295
296
        $form = $builder->getForm();
297
298
        $form->handleRequest($request);
299
300
        if ($form->isSubmitted() && $form->isValid()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
301
302
            log_info('非会員お届け先追加処理開始');
303
304
            // 非会員用のセッションに追加
305
            $customerAddresses = $this->session->get($this->sessionCustomerAddressKey);
306
            $customerAddresses = unserialize($customerAddresses);
307
            $customerAddresses[] = $CustomerAddress;
308
            $this->session->set($this->sessionCustomerAddressKey, serialize($customerAddresses));
309
310
            $event = new EventArgs(
311
                array(
312
                    'form' => $form,
313
                    'CustomerAddresses' => $customerAddresses,
314
                ),
315
                $request
316
            );
317
            $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_MULTIPLE_EDIT_COMPLETE, $event);
318
319
            log_info('非会員お届け先追加処理完了');
320
321
            return $app->redirect($app->url('shopping_shipping_multiple'));
322
        }
323
324
        return $app->render(
325
            'Shopping/shipping_multiple_edit.twig',
326
            array(
327
                'form' => $form->createView(),
328
            )
329
        );
330
    }
331
332
    /**
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...
333
     * お届け先の設定(非会員)がクリックされた場合の処理
334
     *
335
     * @Route("/shopping/shipping_edit_change/{id}", name="shopping_shipping_edit_change", requirements={"id" = "\d+"})
336
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
337
    public function shippingEditChange(Application $app, Request $request, $id)
338
    {
339
        $Order = $app['eccube.service.shopping']->getOrder($app['config']['order_processing']);
340
        if (!$Order) {
341
            $app->addError('front.shopping.order.error');
342
            return $app->redirect($app->url('shopping_error'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
343
        }
344
345
        if ('POST' !== $request->getMethod()) {
346
            return $app->redirect($app->url('shopping'));
347
        }
348
349
        $builder = $app['eccube.service.shopping']->getShippingFormBuilder($Order);
350
351
        $event = new EventArgs(
352
            array(
353
                'builder' => $builder,
354
                'Order' => $Order,
355
            ),
356
            $request
357
        );
358
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_EDIT_CHANGE_INITIALIZE, $event);
359
360
        $form = $builder->getForm();
361
362
        $form->handleRequest($request);
363
364
        if ($form->isSubmitted() && $form->isValid()) {
365
            $data = $form->getData();
366
            $message = $data['message'];
367
            $Order->setMessage($message);
368
            // 受注情報を更新
369
            $app['orm.em']->flush();
370
371
            // お届け先設定一覧へリダイレクト
372
            return $app->redirect($app->url('shopping_shipping_edit', array('id' => $id)));
373
        }
374
375
        return $app->render('Shopping/index.twig', array(
376
            'form' => $form->createView(),
377
            'Order' => $Order,
378
        ));
379
    }
380
381
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
382
     * お客様情報の変更(非会員)
383
     *
384
     * @Route("/shopping/customer", name="shopping_customer")
385
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
386
    public function customer(Application $app, Request $request)
387
    {
388
        if ($request->isXmlHttpRequest()) {
389
            try {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
390
391
                log_info('非会員お客様情報変更処理開始');
392
393
                $data = $request->request->all();
394
395
                // 入力チェック
396
                $errors = $this->customerValidation($app, $data);
397
398
                foreach ($errors as $error) {
399 View Code Duplication
                    if ($error->count() != 0) {
400
                        log_info('非会員お客様情報変更入力チェックエラー');
401
                        $response = new Response(json_encode('NG'), 400);
402
                        $response->headers->set('Content-Type', 'application/json');
403
404
                        return $response;
405
                    }
406
                }
407
408
                $pref = $this->prefRepository->findOneBy(array('name' => $data['customer_pref']));
409 View Code Duplication
                if (!$pref) {
410
                    log_info('非会員お客様情報変更入力チェックエラー');
411
                    $response = new Response(json_encode('NG'), 400);
412
                    $response->headers->set('Content-Type', 'application/json');
413
414
                    return $response;
415
                }
416
417
                $Order = $this->shoppingService->getOrder($this->appConfig['order_processing']);
418
                if (!$Order) {
419
                    log_info('カートが存在しません');
420
                    $app->addError('front.shopping.order.error');
421
422
                    return $app->redirect($app->url('shopping_error'));
423
                }
424
425
                $Order
426
                    ->setName01($data['customer_name01'])
427
                    ->setName02($data['customer_name02'])
428
                    ->setCompanyName($data['customer_company_name'])
429
                    ->setTel01($data['customer_tel01'])
430
                    ->setTel02($data['customer_tel02'])
431
                    ->setTel03($data['customer_tel03'])
432
                    ->setZip01($data['customer_zip01'])
433
                    ->setZip02($data['customer_zip02'])
434
                    ->setZipCode($data['customer_zip01'].$data['customer_zip02'])
435
                    ->setPref($pref)
436
                    ->setAddr01($data['customer_addr01'])
437
                    ->setAddr02($data['customer_addr02'])
438
                    ->setEmail($data['customer_email']);
439
440
                // 配送先を更新
441
                $this->entityManager->flush();
442
443
                // 受注関連情報を最新状態に更新
444
                $this->entityManager->refresh($Order);
445
446
                $event = new EventArgs(
447
                    array(
448
                        'Order' => $Order,
449
                        'data' => $data,
450
                    ),
451
                    $request
452
                );
453
                $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_CUSTOMER_INITIALIZE, $event);
454
455
                log_info('非会員お客様情報変更処理完了', array($Order->getId()));
456
                $response = new Response(json_encode('OK'));
457
                $response->headers->set('Content-Type', 'application/json');
458
            } catch (\Exception $e) {
459
                log_error('予期しないエラー', array($e->getMessage()));
460
                $this->logger->error($e);
461
462
                $response = new Response(json_encode('NG'), 500);
463
                $response->headers->set('Content-Type', 'application/json');
464
            }
465
466
            return $response;
467
        }
468
    }
469
470
    /**
471
     * 非会員でのお客様情報変更時の入力チェック
472
     *
473
     * @param Application $app
474
     * @param array $data リクエストパラメータ
475
     * @return array
476
     */
477
    protected function customerValidation(Application $app, array $data)
0 ignored issues
show
Unused Code introduced by
The parameter $app is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
478
    {
479
        // 入力チェック
480
        $errors = array();
481
482
        $errors[] = $this->recursiveValidator->validate(
483
            $data['customer_name01'],
484
            array(
485
                new Assert\NotBlank(),
486
                new Assert\Length(array('max' => $this->appConfig['name_len'],)),
0 ignored issues
show
introduced by
Add a single space after each comma delimiter
Loading history...
487
                new Assert\Regex(
488
                    array('pattern' => '/^[^\s ]+$/u', 'message' => 'form.type.name.firstname.nothasspace')
489
                ),
490
            )
491
        );
492
493
        $errors[] = $this->recursiveValidator->validate(
494
            $data['customer_name02'],
495
            array(
496
                new Assert\NotBlank(),
497
                new Assert\Length(array('max' => $this->appConfig['name_len'],)),
0 ignored issues
show
introduced by
Add a single space after each comma delimiter
Loading history...
498
                new Assert\Regex(
499
                    array('pattern' => '/^[^\s ]+$/u', 'message' => 'form.type.name.firstname.nothasspace')
500
                ),
501
            )
502
        );
503
504
        $errors[] = $this->recursiveValidator->validate(
505
            $data['customer_company_name'],
506
            array(
507
                new Assert\Length(array('max' => $this->appConfig['stext_len'])),
508
            )
509
        );
510
511
        $errors[] = $this->recursiveValidator->validate(
512
            $data['customer_tel01'],
513
            array(
514
                new Assert\NotBlank(),
515
                new Assert\Type(array('type' => 'numeric', 'message' => 'form.type.numeric.invalid')),
516
                new Assert\Length(
517
                    array('max' => $this->appConfig['tel_len'], 'min' => $this->appConfig['tel_len_min'])
518
                ),
519
            )
520
        );
521
522
        $errors[] = $this->recursiveValidator->validate(
523
            $data['customer_tel02'],
524
            array(
525
                new Assert\NotBlank(),
526
                new Assert\Type(array('type' => 'numeric', 'message' => 'form.type.numeric.invalid')),
527
                new Assert\Length(
528
                    array('max' => $this->appConfig['tel_len'], 'min' => $this->appConfig['tel_len_min'])
529
                ),
530
            )
531
        );
532
533
        $errors[] = $this->recursiveValidator->validate(
534
            $data['customer_tel03'],
535
            array(
536
                new Assert\NotBlank(),
537
                new Assert\Type(array('type' => 'numeric', 'message' => 'form.type.numeric.invalid')),
538
                new Assert\Length(
539
                    array('max' => $this->appConfig['tel_len'], 'min' => $this->appConfig['tel_len_min'])
540
                ),
541
            )
542
        );
543
544
        $errors[] = $this->recursiveValidator->validate(
545
            $data['customer_zip01'],
546
            array(
547
                new Assert\NotBlank(),
548
                new Assert\Type(array('type' => 'numeric', 'message' => 'form.type.numeric.invalid')),
549
                new Assert\Length(
550
                    array('min' => $this->appConfig['zip01_len'], 'max' => $this->appConfig['zip01_len'])
551
                ),
552
            )
553
        );
554
555
        $errors[] = $this->recursiveValidator->validate(
556
            $data['customer_zip02'],
557
            array(
558
                new Assert\NotBlank(),
559
                new Assert\Type(array('type' => 'numeric', 'message' => 'form.type.numeric.invalid')),
560
                new Assert\Length(
561
                    array('min' => $this->appConfig['zip02_len'], 'max' => $this->appConfig['zip02_len'])
562
                ),
563
            )
564
        );
565
566
        $errors[] = $this->recursiveValidator->validate(
567
            $data['customer_addr01'],
568
            array(
569
                new Assert\NotBlank(),
570
                new Assert\Length(array('max' => $this->appConfig['address1_len'])),
571
            )
572
        );
573
574
        $errors[] = $this->recursiveValidator->validate(
575
            $data['customer_addr02'],
576
            array(
577
                new Assert\NotBlank(),
578
                new Assert\Length(array('max' => $this->appConfig['address2_len'])),
579
            )
580
        );
581
582
        $errors[] = $this->recursiveValidator->validate(
583
            $data['customer_email'],
584
            array(
585
                new Assert\NotBlank(),
586
                new Assert\Email(array('strict' => true)),
587
            )
588
        );
589
590
        return $errors;
591
    }
592
}