Failed Conditions
Pull Request — 4.0 (#3650)
by chihiro
08:02
created

NonMemberShoppingController::index()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 70

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 37
CRAP Score 7

Importance

Changes 0
Metric Value
cc 7
nc 5
nop 1
dl 0
loc 70
ccs 37
cts 37
cp 1
crap 7
rs 7.7212
c 0
b 0
f 0

How to fix   Long Method   

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\Event\EccubeEvents;
18
use Eccube\Event\EventArgs;
19
use Eccube\Form\Type\Front\NonMemberType;
20
use Eccube\Repository\Master\PrefRepository;
21
use Eccube\Service\CartService;
22
use Eccube\Service\OrderHelper;
23
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
24
use Symfony\Component\HttpFoundation\Request;
25
use Symfony\Component\Routing\Annotation\Route;
26
use Symfony\Component\Validator\Constraints as Assert;
27
use Symfony\Component\Validator\Validator\ValidatorInterface;
28
29
class NonMemberShoppingController extends AbstractShoppingController
30
{
31
    /**
32
     * @var ValidatorInterface
33
     */
34
    protected $validator;
35
36
    /**
37
     * @var PrefRepository
38
     */
39
    protected $prefRepository;
40
41
    /**
42
     * @var OrderHelper
43
     */
44
    protected $orderHelper;
45
46
    /**
47
     * @var CartService
48
     */
49
    protected $cartService;
50
51
    /**
52
     * NonMemberShoppingController constructor.
53
     *
54
     * @param ValidatorInterface $validator
55
     * @param PrefRepository $prefRepository
56
     * @param OrderHelper $orderHelper
57
     * @param CartService $cartService
58
     */
59
    public function __construct(
60
        ValidatorInterface $validator,
61
        PrefRepository $prefRepository,
62
        OrderHelper $orderHelper,
63
        CartService $cartService
64
    ) {
65
        $this->validator = $validator;
66
        $this->prefRepository = $prefRepository;
67
        $this->orderHelper = $orderHelper;
68
        $this->cartService = $cartService;
69 20
    }
70
71
    /**
72
     * 非会員処理
73
     *
74
     * @Route("/shopping/nonmember", name="shopping_nonmember")
75
     * @Template("Shopping/nonmember.twig")
76 20
     */
77 20
    public function index(Request $request)
78 20
    {
79 20
        // ログイン済みの場合は, 購入画面へリダイレクト.
80 20
        if ($this->isGranted('ROLE_USER')) {
81
            return $this->redirectToRoute('shopping');
82
        }
83
84
        // カートチェック.
85
        $Cart = $this->cartService->getCart();
86
        if (!($Cart && $this->orderHelper->verifyCart($Cart))) {
87
            return $this->redirectToRoute('cart');
88
        }
89 20
90
        $builder = $this->formFactory->createBuilder(NonMemberType::class);
91 20
92
        $event = new EventArgs(
93
            [
94 20
                'builder' => $builder,
95 20
            ],
96 1
            $request
97
        );
98
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_NONMEMBER_INITIALIZE, $event);
99
100 19
        $form = $builder->getForm();
101 1
102
        $form->handleRequest($request);
103
104 18
        if ($form->isSubmitted() && $form->isValid()) {
105
            log_info('非会員お客様情報登録開始');
106 18
107
            $data = $form->getData();
108 18
            $Customer = new Customer();
109
            $Customer
110 18
                ->setName01($data['name01'])
111
                ->setName02($data['name02'])
112 18
                ->setKana01($data['kana01'])
113
                ->setKana02($data['kana02'])
114 18
                ->setCompanyName($data['company_name'])
115
                ->setEmail($data['email'])
116 18
                ->setPhonenumber($data['phone_number'])
117
                ->setPostalcode($data['postal_code'])
118 18
                ->setPref($data['pref'])
119 17
                ->setAddr01($data['addr01'])
120
                ->setAddr02($data['addr02']);
121 17
122 17
            // 非会員用セッションを作成
123
            $this->session->set(OrderHelper::SESSION_NON_MEMBER, $Customer);
124 17
            $this->session->set(OrderHelper::SESSION_NON_MEMBER_ADDRESSES, serialize([]));
125 17
126 17
            $event = new EventArgs(
127 17
                [
128 17
                    'form' => $form,
129 17
                ],
130 17
                $request
131 17
            );
132 17
            $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_NONMEMBER_COMPLETE, $event);
133 17
134 17
            if ($event->getResponse() !== null) {
135
                return $event->getResponse();
136
            }
137
138 17
            log_info('非会員お客様情報登録完了');
139
140
            return $this->redirectToRoute('shopping');
141 17
        }
142
143
        return [
144
            'form' => $form->createView(),
145 17
        ];
146 17
    }
147 17
148
    /**
149 17
     * お客様情報の変更(非会員)
150 17
     *
151
     * @Route("/shopping/customer", name="shopping_customer")
152
     */
153
    public function customer(Request $request)
154
    {
155
        if (!$request->isXmlHttpRequest()) {
156
            return $this->json(['status' => 'NG'], 400);
157
        }
158 17
        $this->isTokenValid();
159 17
        try {
160
            log_info('非会員お客様情報変更処理開始');
161
            $data = $request->request->all();
162
            // 入力チェック
163
            $errors = $this->customerValidation($data);
164 17
            foreach ($errors as $error) {
165 17
                if ($error->count() != 0) {
166
                    log_info('非会員お客様情報変更入力チェックエラー');
167 17
168
                    return $this->json(['status' => 'NG'], 400);
169 17
                }
170 17
            }
171
            $pref = $this->prefRepository->findOneBy(['name' => $data['customer_pref']]);
172 17
            if (!$pref) {
173
                log_info('非会員お客様情報変更入力チェックエラー');
174 17
175
                return $this->json(['status' => 'NG'], 400);
176 17
            }
177
            $preOrderId = $this->cartService->getPreOrderId();
178
            $Order = $this->orderHelper->getPurchaseProcessingOrder($preOrderId);
179
            if (!$Order) {
180 17
                log_info('受注が存在しません');
181
                $this->addError('front.shopping.order_error');
182 17
183
                return $this->redirectToRoute('shopping_error');
184
            }
185
            $Order
186 1
                ->setName01($data['customer_name01'])
187
                ->setName02($data['customer_name02'])
188
                ->setKana01($data['customer_kana01'])
189
                ->setKana02($data['customer_kana02'])
190
                ->setCompanyName($data['customer_company_name'])
191
                ->setPhoneNumber($data['customer_phone_number'])
192
                ->setPostalCode($data['customer_postal_code'])
193
                ->setPref($pref)
194
                ->setAddr01($data['customer_addr01'])
195
                ->setAddr02($data['customer_addr02'])
196
                ->setEmail($data['customer_email']);
197
198
            $this->entityManager->flush();
199
200
            $Customer = new Customer();
201
            $Customer
202
                ->setName01($data['customer_name01'])
203
                ->setName02($data['customer_name02'])
204
                ->setKana01($data['customer_kana01'])
205
                ->setKana02($data['customer_kana02'])
206
                ->setCompanyName($data['customer_company_name'])
207
                ->setPhoneNumber($data['customer_phone_number'])
208
                ->setPostalCode($data['customer_postal_code'])
209
                ->setPref($pref)
210
                ->setAddr01($data['customer_addr01'])
211
                ->setAddr02($data['customer_addr02'])
212
                ->setEmail($data['customer_email']);
213
214
            $this->session->set(OrderHelper::SESSION_NON_MEMBER, $Customer);
215
216
            $event = new EventArgs(
217
                [
218
                    'Order' => $Order,
219
                    'data' => $data,
220
                ],
221
                $request
222
            );
223
            $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_CUSTOMER_INITIALIZE, $event);
224
            log_info('非会員お客様情報変更処理完了', [$Order->getId()]);
225
            $message = ['status' => 'OK', 'kana01' => $data['customer_kana01'], 'kana02' => $data['customer_kana02']];
226
227
            $response = $this->json($message);
228
        } catch (\Exception $e) {
229
            log_error('予期しないエラー', [$e->getMessage()]);
230
231
            $response = $this->json(['status' => 'NG'], 500);
232
        }
233
234
        return $response;
235
    }
236
237
    /**
238
     * 非会員でのお客様情報変更時の入力チェック
239
     *
240
     * @param array $data リクエストパラメータ
241
     *
242
     * @return \Symfony\Component\Validator\ConstraintViolationListInterface[]
243
     */
244
    protected function customerValidation(array &$data)
245
    {
246
        // 入力チェック
247
        $errors = [];
248
249
        $errors[] = $this->validator->validate(
250
            $data['customer_name01'],
251
            [
252
                new Assert\NotBlank(),
253
                new Assert\Length(['max' => $this->eccubeConfig['eccube_name_len']]),
254
                new Assert\Regex(
255
                    ['pattern' => '/^[^\s ]+$/u', 'message' => 'form.type.name.firstname.nothasspace']
256
                ),
257
            ]
258
        );
259
260
        $errors[] = $this->validator->validate(
261
            $data['customer_name02'],
262
            [
263
                new Assert\NotBlank(),
264
                new Assert\Length(['max' => $this->eccubeConfig['eccube_name_len']]),
265
                new Assert\Regex(
266
                    ['pattern' => '/^[^\s ]+$/u', 'message' => 'form.type.name.firstname.nothasspace']
267
                ),
268
            ]
269
        );
270
271
        $data['customer_kana01'] = mb_convert_kana($data['customer_kana01'], 'CV', 'utf-8');
272
        $errors[] = $this->validator->validate(
273
            $data['customer_kana01'],
274
            [
275
                new Assert\NotBlank(),
276
                new Assert\Length(['max' => $this->eccubeConfig['eccube_kana_len']]),
277
                new Assert\Regex(['pattern' => '/^[ァ-ヶヲ-゚ー]+$/u']),
278
            ]
279
        );
280
        $data['customer_kana02'] = mb_convert_kana($data['customer_kana02'], 'CV', 'utf-8');
281
        $errors[] = $this->validator->validate(
282
            $data['customer_kana02'],
283
            [
284
                new Assert\NotBlank(),
285
                new Assert\Length(['max' => $this->eccubeConfig['eccube_kana_len']]),
286
                new Assert\Regex(['pattern' => '/^[ァ-ヶヲ-゚ー]+$/u']),
287
            ]);
288
289
        $errors[] = $this->validator->validate(
290
            $data['customer_company_name'],
291
            [
292
                new Assert\Length(['max' => $this->eccubeConfig['eccube_stext_len']]),
293
            ]
294
        );
295
296
        $errors[] = $this->validator->validate(
297
            $data['customer_phone_number'],
298
            [
299
                new Assert\NotBlank(),
300
                new Assert\Type(['type' => 'numeric', 'message' => 'form.type.numeric.invalid']),
301
                new Assert\Length(
302
                    ['max' => $this->eccubeConfig['eccube_tel_len_max']]
303
                ),
304
            ]
305
        );
306
307
        $errors[] = $this->validator->validate(
308
            $data['customer_postal_code'],
309
            [
310
                new Assert\NotBlank(),
311
                new Assert\Type(['type' => 'numeric', 'message' => 'form.type.numeric.invalid']),
312
                new Assert\Length(
313
                    ['max' => $this->eccubeConfig['eccube_postal_code']]
314
                ),
315
            ]
316
        );
317
318
        $errors[] = $this->validator->validate(
319
            $data['customer_addr01'],
320
            [
321
                new Assert\NotBlank(),
322
                new Assert\Length(['max' => $this->eccubeConfig['eccube_address1_len']]),
323
            ]
324
        );
325
326
        $errors[] = $this->validator->validate(
327
            $data['customer_addr02'],
328
            [
329
                new Assert\NotBlank(),
330
                new Assert\Length(['max' => $this->eccubeConfig['eccube_address2_len']]),
331
            ]
332
        );
333
334
        $errors[] = $this->validator->validate(
335
            $data['customer_email'],
336
            [
337
                new Assert\NotBlank(),
338
                new Assert\Email(['strict' => true]),
339
            ]
340
        );
341
342
        return $errors;
343
    }
344
}
345