Failed Conditions
Pull Request — experimental/sf (#3241)
by k-yamamura
43:19 queued 23:09
created

NonMemberShoppingController::index()   C

Complexity

Conditions 11
Paths 12

Size

Total Lines 100

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 49
CRAP Score 11.096

Importance

Changes 0
Metric Value
cc 11
nc 12
nop 1
dl 0
loc 100
rs 5.8533
c 0
b 0
f 0
ccs 49
cts 54
cp 0.9074
crap 11.096

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
/*
4
 * This file is part of EC-CUBE
5
 *
6
 * Copyright(c) LOCKON CO.,LTD. All Rights Reserved.
7
 *
8
 * http://www.lockon.co.jp/
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Eccube\Controller;
15
16
use Eccube\Entity\Customer;
17
use Eccube\Entity\Master\OrderStatus;
18
use Eccube\Entity\Order;
19
use Eccube\Event\EccubeEvents;
20
use Eccube\Event\EventArgs;
21
use Eccube\Exception\CartException;
22
use Eccube\Form\Type\Front\NonMemberType;
23
use Eccube\Repository\Master\PrefRepository;
24
use Eccube\Service\CartService;
25
use Eccube\Service\OrderHelper;
26
use Eccube\Service\ShoppingService;
27
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
28
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
29
use Symfony\Component\HttpFoundation\Request;
30
use Symfony\Component\HttpFoundation\Response;
31
use Symfony\Component\Validator\Constraints as Assert;
32
use Symfony\Component\Validator\Validator\ValidatorInterface;
33
34
class NonMemberShoppingController extends AbstractShoppingController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
35
{
36
    /**
37
     * @var ValidatorInterface
38
     */
39
    protected $validator;
40
41
    /**
42
     * @var PrefRepository
43
     */
44
    protected $prefRepository;
45
46
    /**
47
     * @var OrderHelper
48
     */
49
    protected $orderHelper;
50
51
    /**
52
     * @var ShoppingService
53
     */
54
    protected $shoppingService;
55
56
    /**
57
     * @var CartService
58
     */
59
    protected $cartService;
60
61
    /**
62
     * NonMemberShoppingController constructor.
63
     *
64
     * @param ValidatorInterface $validator
65
     * @param PrefRepository $prefRepository
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
66
     * @param OrderHelper $orderHelper
0 ignored issues
show
introduced by
Expected 8 spaces after parameter type; 1 found
Loading history...
67
     * @param ShoppingService $shoppingService
0 ignored issues
show
introduced by
Expected 4 spaces after parameter type; 1 found
Loading history...
68
     * @param CartService $cartService
0 ignored issues
show
introduced by
Expected 8 spaces after parameter type; 1 found
Loading history...
69
     */
70 20
    public function __construct(
71
        ValidatorInterface $validator,
72
        PrefRepository $prefRepository,
73
        OrderHelper $orderHelper,
74
        ShoppingService $shoppingService,
75
        CartService $cartService
76
    ) {
77 20
        $this->validator = $validator;
78 20
        $this->prefRepository = $prefRepository;
79 20
        $this->orderHelper = $orderHelper;
80 20
        $this->shoppingService = $shoppingService;
81 20
        $this->cartService = $cartService;
82
    }
83
84
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
85
     * 非会員処理
86
     *
87
     * @Route("/shopping/nonmember", name="shopping_nonmember")
88
     * @Template("Shopping/nonmember.twig")
89
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
90 20
    public function index(Request $request)
91
    {
92 20
        $cartService = $this->cartService;
93
94
        // カートチェック
95 20
        $response = $this->forwardToRoute('shopping_check_to_cart');
96 20
        if ($response->isRedirection() || $response->getContent()) {
97 1
            return $response;
98
        }
99
100
        // ログイン済みの場合は, 購入画面へリダイレクト.
101 19
        if ($this->isGranted('ROLE_USER')) {
102 1
            return $this->redirectToRoute('shopping');
103
        }
104
105 18
        $builder = $this->formFactory->createBuilder(NonMemberType::class);
106
107 18
        $event = new EventArgs(
108
            [
109 18
                'builder' => $builder,
110
            ],
111 18
            $request
112
        );
113 18
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_NONMEMBER_INITIALIZE, $event);
114
115 18
        $form = $builder->getForm();
116
117 18
        $form->handleRequest($request);
118
119 18
        if ($form->isSubmitted() && $form->isValid()) {
120 17
            log_info('非会員お客様情報登録開始');
121
122 17
            $data = $form->getData();
123 17
            $Customer = new Customer();
124
            $Customer
125 17
                ->setName01($data['name01'])
126 17
                ->setName02($data['name02'])
127 17
                ->setKana01($data['kana01'])
128 17
                ->setKana02($data['kana02'])
129 17
                ->setCompanyName($data['company_name'])
130 17
                ->setEmail($data['email'])
131 17
                ->setPhonenumber($data['phone_number'])
132 17
                ->setPostalcode($data['postal_code'])
133 17
                ->setPref($data['pref'])
134 17
                ->setAddr01($data['addr01'])
135 17
                ->setAddr02($data['addr02']);
136
137
            // 受注情報を取得
138
            /** @var Order $Order */
139 17
            $Order = $this->shoppingService->getOrder(OrderStatus::PROCESSING);
140
141
            // 初回アクセス(受注データがない)の場合は, 受注情報を作成
142 17
            if (is_null($Order)) {
143
                // 受注情報を作成
144
                try {
145
                    // 受注情報を作成
146 17
                    $Order = $this->orderHelper->createProcessingOrder(
147 17
                        $Customer,
148 17
                        $cartService->getCart()->getCartItems()
149
                    );
150 17
                    $cartService->setPreOrderId($Order->getPreOrderId());
151 17
                    $cartService->save();
152
                } catch (CartException $e) {
153
                    $this->addRequestError($e->getMessage());
154
155
                    return $this->redirectToRoute('cart');
156
                }
157
            }
158
159 17
            $flowResult = $this->executePurchaseFlow($Order);
160 17
            if ($flowResult->hasWarning() || $flowResult->hasError()) {
161
                return $this->redirectToRoute('cart');
162
            }
163
164
            // 非会員用セッションを作成
165 17
            $this->session->set($this->sessionKey, $Customer);
166 17
            $this->session->set($this->sessionCustomerAddressKey, serialize([]));
167
168 17
            $event = new EventArgs(
169
                [
170 17
                    'form' => $form,
171 17
                    'Order' => $Order,
172
                ],
173 17
                $request
174
            );
175 17
            $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_NONMEMBER_COMPLETE, $event);
176
177 17
            if ($event->getResponse() !== null) {
178
                return $event->getResponse();
179
            }
180
181 17
            log_info('非会員お客様情報登録完了', [$Order->getId()]);
182
183 17
            return $this->redirectToRoute('shopping');
184
        }
185
186
        return [
187 1
            'form' => $form->createView(),
188
        ];
189
    }
190
191
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$id" missing
Loading history...
192
     * お届け先の設定(非会員)がクリックされた場合の処理
193
     *
194
     * @Route("/shopping/shipping_edit_change/{id}", name="shopping_shipping_edit_change", requirements={"id" = "\d+"})
195
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
196
    public function shippingEditChange(Request $request, $id)
197
    {
198
        $Order = $this->shoppingService->getOrder(OrderStatus::PROCESSING);
199
        if (!$Order) {
200
            $this->addError('front.shopping.order.error');
201
202
            return $this->redirectToRoute('shopping_error');
203
        }
204
205
        if ('POST' !== $request->getMethod()) {
206
            return $this->redirectToRoute('shopping');
207
        }
208
209
        $builder = $this->shoppingService->getShippingFormBuilder($Order);
0 ignored issues
show
Deprecated Code introduced by
The method Eccube\Service\ShoppingS...etShippingFormBuilder() has been deprecated with message: 利用している箇所なし

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
210
211
        $event = new EventArgs(
212
            [
213
                'builder' => $builder,
214
                'Order' => $Order,
215
            ],
216
            $request
217
        );
218
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_EDIT_CHANGE_INITIALIZE, $event);
219
220
        $form = $builder->getForm();
221
222
        $form->handleRequest($request);
223
224
        if ($form->isSubmitted() && $form->isValid()) {
225
            $data = $form->getData();
226
            $message = $data['message'];
227
            $Order->setMessage($message);
228
            // 受注情報を更新
229
            $this->entityManager->flush();
230
231
            // お届け先設定一覧へリダイレクト
232
            return $this->redirectToRoute('shopping_shipping_edit', ['id' => $id]);
233
        }
234
235
        return $this->redirectToRoute('Shopping/index.twig', [
236
            'form' => $form->createView(),
237
            'Order' => $Order,
238
        ]);
239
    }
240
241
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
242
     * お客様情報の変更(非会員)
243
     *
244
     * @Route("/shopping/customer", name="shopping_customer")
245
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
246
    public function customer(Request $request)
247
    {
248 View Code Duplication
        if (!$request->isXmlHttpRequest()) {
249
            $response = new Response(json_encode(['status' => 'NG']), 400);
250
            $response->headers->set('Content-Type', 'application/json');
251
252
            return $response;
253
        }
254
        try {
255
            log_info('非会員お客様情報変更処理開始');
256
            $data = $request->request->all();
257
            // 入力チェック
258
            $errors = $this->customerValidation($data);
259
            foreach ($errors as $error) {
260 View Code Duplication
                if ($error->count() != 0) {
261
                    log_info('非会員お客様情報変更入力チェックエラー');
262
                    $response = new Response(json_encode('NG'), 400);
263
                    $response->headers->set('Content-Type', 'application/json');
264
265
                    return $response;
266
                }
267
            }
268
            $pref = $this->prefRepository->findOneBy(['name' => $data['customer_pref']]);
269 View Code Duplication
            if (!$pref) {
270
                log_info('非会員お客様情報変更入力チェックエラー');
271
                $response = new Response(json_encode('NG'), 400);
272
                $response->headers->set('Content-Type', 'application/json');
273
274
                return $response;
275
            }
276
            /** @var Order $Order */
277
            $Order = $this->shoppingService->getOrder(OrderStatus::PROCESSING);
278
            if (!$Order) {
279
                log_info('カートが存在しません');
280
                $this->addError('front.shopping.order.error');
281
282
                return $this->redirectToRoute('shopping_error');
283
            }
284
            $Order
285
                ->setName01($data['customer_name01'])
286
                ->setName02($data['customer_name02'])
287
                ->setKana01($data['customer_kana01'])
288
                ->setKana02($data['customer_kana02'])
289
                ->setCompanyName($data['customer_company_name'])
290
                ->setPhoneNumber($data['customer_phone_number'])
291
                ->setPostalCode($data['customer_postal_code'])
292
                ->setPref($pref)
293
                ->setAddr01($data['customer_addr01'])
294
                ->setAddr02($data['customer_addr02'])
295
                ->setEmail($data['customer_email']);
296
            // 配送先を更新
297
            $this->entityManager->flush();
298
            // 受注関連情報を最新状態に更新
299
            $this->entityManager->refresh($Order);
300
            $event = new EventArgs(
301
                [
302
                    'Order' => $Order,
303
                    'data' => $data,
304
                ],
305
                $request
306
            );
307
            $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_CUSTOMER_INITIALIZE, $event);
308
            log_info('非会員お客様情報変更処理完了', [$Order->getId()]);
309
            $message = ['status' => 'OK', 'kana01' => $data['customer_kana01'], 'kana02' => $data['customer_kana02']];
310
            $response = new Response(json_encode($message));
311
            $response->headers->set('Content-Type', 'application/json');
312
        } catch (\Exception $e) {
313
            log_error('予期しないエラー', [$e->getMessage()]);
314
            $response = new Response(json_encode(['status' => 'NG']), 500);
315
            $response->headers->set('Content-Type', 'application/json');
316
        }
317
318
        return $response;
319
    }
320
321
    /**
322
     * 非会員でのお客様情報変更時の入力チェック
323
     *
324
     * @param array $data リクエストパラメータ
325
     *
326
     * @return array
327
     */
328
    protected function customerValidation(array &$data)
329
    {
330
        // 入力チェック
331
        $errors = [];
332
333
        $errors[] = $this->validator->validate(
334
            $data['customer_name01'],
335
            [
336
                new Assert\NotBlank(),
337
                new Assert\Length(['max' => $this->eccubeConfig['eccube_name_len']]),
338
                new Assert\Regex(
339
                    ['pattern' => '/^[^\s ]+$/u', 'message' => 'form.type.name.firstname.nothasspace']
340
                ),
341
            ]
342
        );
343
344
        $errors[] = $this->validator->validate(
345
            $data['customer_name02'],
346
            [
347
                new Assert\NotBlank(),
348
                new Assert\Length(['max' => $this->eccubeConfig['eccube_name_len']]),
349
                new Assert\Regex(
350
                    ['pattern' => '/^[^\s ]+$/u', 'message' => 'form.type.name.firstname.nothasspace']
351
                ),
352
            ]
353
        );
354
355
        $data['customer_kana01'] = mb_convert_kana($data['customer_kana01'], 'CV', 'utf-8');
356
        $errors[] = $this->validator->validate(
357
            $data['customer_kana01'],
358
            [
359
                new Assert\NotBlank(),
360
                new Assert\Length(['max' => $this->eccubeConfig['eccube_kana_len']]),
361
                new Assert\Regex(['pattern' => '/^[ァ-ヶヲ-゚ー]+$/u']),
362
            ]
363
        );
364
        $data['customer_kana02'] = mb_convert_kana($data['customer_kana02'], 'CV', 'utf-8');
365
        $errors[] = $this->validator->validate(
366
            $data['customer_kana02'],
367
            [
368
                new Assert\NotBlank(),
369
                new Assert\Length(['max' => $this->eccubeConfig['eccube_kana_len']]),
370
                new Assert\Regex(['pattern' => '/^[ァ-ヶヲ-゚ー]+$/u']),
371
        ]);
372
373
        $errors[] = $this->validator->validate(
374
            $data['customer_company_name'],
375
            [
376
                new Assert\Length(['max' => $this->eccubeConfig['eccube_stext_len']]),
377
            ]
378
        );
379
380
        $errors[] = $this->validator->validate(
381
            $data['customer_phone_number'],
382
            [
383
                new Assert\NotBlank(),
384
                new Assert\Type(['type' => 'numeric', 'message' => 'form.type.numeric.invalid']),
385
                new Assert\Length(
386
                    ['max' => $this->eccubeConfig['eccube_tel_len_max']]
387
                ),
388
            ]
389
        );
390
391
        $errors[] = $this->validator->validate(
392
            $data['customer_postal_code'],
393
            [
394
                new Assert\NotBlank(),
395
                new Assert\Type(['type' => 'numeric', 'message' => 'form.type.numeric.invalid']),
396
                new Assert\Length(
397
                    ['max' => $this->eccubeConfig['eccube_postal_code']]
398
                ),
399
            ]
400
        );
401
402
        $errors[] = $this->validator->validate(
403
            $data['customer_addr01'],
404
            [
405
                new Assert\NotBlank(),
406
                new Assert\Length(['max' => $this->eccubeConfig['eccube_address1_len']]),
407
            ]
408
        );
409
410
        $errors[] = $this->validator->validate(
411
            $data['customer_addr02'],
412
            [
413
                new Assert\NotBlank(),
414
                new Assert\Length(['max' => $this->eccubeConfig['eccube_address2_len']]),
415
            ]
416
        );
417
418
        $errors[] = $this->validator->validate(
419
            $data['customer_email'],
420
            [
421
                new Assert\NotBlank(),
422
                new Assert\Email(['strict' => true]),
423
            ]
424
        );
425
426
        return $errors;
427
    }
428
}
429