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

NonMemberShoppingController::customer()   B

Complexity

Conditions 7
Paths 54

Size

Total Lines 83

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 21.5206

Importance

Changes 0
Metric Value
cc 7
nc 54
nop 1
dl 0
loc 83
ccs 13
cts 39
cp 0.3333
crap 21.5206
rs 7.4375
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
        if (!$this->orderHelper->verifyCart($this->cartService->getCart())) {
0 ignored issues
show
Bug introduced by
It seems like $this->cartService->getCart() can be null; however, verifyCart() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
86
            return $this->redirectToRoute('cart');
87
        }
88
89 20
        $builder = $this->formFactory->createBuilder(NonMemberType::class);
90
91 20
        $event = new EventArgs(
92
            [
93
                'builder' => $builder,
94 20
            ],
95 20
            $request
96 1
        );
97
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_NONMEMBER_INITIALIZE, $event);
98
99
        $form = $builder->getForm();
100 19
101 1
        $form->handleRequest($request);
102
103
        if ($form->isSubmitted() && $form->isValid()) {
104 18
            log_info('非会員お客様情報登録開始');
105
106 18
            $data = $form->getData();
107
            $Customer = new Customer();
108 18
            $Customer
109
                ->setName01($data['name01'])
110 18
                ->setName02($data['name02'])
111
                ->setKana01($data['kana01'])
112 18
                ->setKana02($data['kana02'])
113
                ->setCompanyName($data['company_name'])
114 18
                ->setEmail($data['email'])
115
                ->setPhonenumber($data['phone_number'])
116 18
                ->setPostalcode($data['postal_code'])
117
                ->setPref($data['pref'])
118 18
                ->setAddr01($data['addr01'])
119 17
                ->setAddr02($data['addr02']);
120
121 17
            // 非会員用セッションを作成
122 17
            $this->session->set(OrderHelper::SESSION_NON_MEMBER, $Customer);
123
            $this->session->set(OrderHelper::SESSION_NON_MEMBER_ADDRESSES, serialize([]));
124 17
125 17
            $event = new EventArgs(
126 17
                [
127 17
                    'form' => $form,
128 17
                ],
129 17
                $request
130 17
            );
131 17
            $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_NONMEMBER_COMPLETE, $event);
132 17
133 17
            if ($event->getResponse() !== null) {
134 17
                return $event->getResponse();
135
            }
136
137
            log_info('非会員お客様情報登録完了');
138 17
139
            return $this->redirectToRoute('shopping');
140
        }
141 17
142
        return [
143
            'form' => $form->createView(),
144
        ];
145 17
    }
146 17
147 17
    /**
148
     * お客様情報の変更(非会員)
149 17
     *
150 17
     * @Route("/shopping/customer", name="shopping_customer")
151
     */
152
    public function customer(Request $request)
153
    {
154
        if (!$request->isXmlHttpRequest()) {
155
            return $this->json(['status' => 'NG'], 400);
156
        }
157
        $this->isTokenValid();
158 17
        try {
159 17
            log_info('非会員お客様情報変更処理開始');
160
            $data = $request->request->all();
161
            // 入力チェック
162
            $errors = $this->customerValidation($data);
163
            foreach ($errors as $error) {
164 17
                if ($error->count() != 0) {
165 17
                    log_info('非会員お客様情報変更入力チェックエラー');
166
167 17
                    return $this->json(['status' => 'NG'], 400);
168
                }
169 17
            }
170 17
            $pref = $this->prefRepository->findOneBy(['name' => $data['customer_pref']]);
171
            if (!$pref) {
172 17
                log_info('非会員お客様情報変更入力チェックエラー');
173
174 17
                return $this->json(['status' => 'NG'], 400);
175
            }
176 17
            $preOrderId = $this->cartService->getPreOrderId();
177
            $Order = $this->orderHelper->getPurchaseProcessingOrder($preOrderId);
178
            if (!$Order) {
179
                log_info('受注が存在しません');
180 17
                $this->addError('front.shopping.order_error');
181
182 17
                return $this->redirectToRoute('shopping_error');
183
            }
184
            $Order
185
                ->setName01($data['customer_name01'])
186 1
                ->setName02($data['customer_name02'])
187
                ->setKana01($data['customer_kana01'])
188
                ->setKana02($data['customer_kana02'])
189
                ->setCompanyName($data['customer_company_name'])
190
                ->setPhoneNumber($data['customer_phone_number'])
191
                ->setPostalCode($data['customer_postal_code'])
192
                ->setPref($pref)
193
                ->setAddr01($data['customer_addr01'])
194
                ->setAddr02($data['customer_addr02'])
195
                ->setEmail($data['customer_email']);
196
197
            $this->entityManager->flush();
198
199
            $Customer = new Customer();
200
            $Customer
201
                ->setName01($data['customer_name01'])
202
                ->setName02($data['customer_name02'])
203
                ->setKana01($data['customer_kana01'])
204
                ->setKana02($data['customer_kana02'])
205
                ->setCompanyName($data['customer_company_name'])
206
                ->setPhoneNumber($data['customer_phone_number'])
207
                ->setPostalCode($data['customer_postal_code'])
208
                ->setPref($pref)
209
                ->setAddr01($data['customer_addr01'])
210
                ->setAddr02($data['customer_addr02'])
211
                ->setEmail($data['customer_email']);
212
213
            $this->session->set(OrderHelper::SESSION_NON_MEMBER, $Customer);
214
215
            $event = new EventArgs(
216
                [
217
                    'Order' => $Order,
218
                    'data' => $data,
219
                ],
220
                $request
221
            );
222
            $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_CUSTOMER_INITIALIZE, $event);
223
            log_info('非会員お客様情報変更処理完了', [$Order->getId()]);
224
            $message = ['status' => 'OK', 'kana01' => $data['customer_kana01'], 'kana02' => $data['customer_kana02']];
225
226
            $response = $this->json($message);
227
        } catch (\Exception $e) {
228
            log_error('予期しないエラー', [$e->getMessage()]);
229
230
            $response = $this->json(['status' => 'NG'], 500);
231
        }
232
233
        return $response;
234
    }
235
236
    /**
237
     * 非会員でのお客様情報変更時の入力チェック
238
     *
239
     * @param array $data リクエストパラメータ
240
     *
241
     * @return \Symfony\Component\Validator\ConstraintViolationListInterface[]
242
     */
243
    protected function customerValidation(array &$data)
244
    {
245
        // 入力チェック
246
        $errors = [];
247
248
        $errors[] = $this->validator->validate(
249
            $data['customer_name01'],
250
            [
251
                new Assert\NotBlank(),
252
                new Assert\Length(['max' => $this->eccubeConfig['eccube_name_len']]),
253
                new Assert\Regex(
254
                    ['pattern' => '/^[^\s ]+$/u', 'message' => 'form.type.name.firstname.nothasspace']
255
                ),
256
            ]
257
        );
258
259
        $errors[] = $this->validator->validate(
260
            $data['customer_name02'],
261
            [
262
                new Assert\NotBlank(),
263
                new Assert\Length(['max' => $this->eccubeConfig['eccube_name_len']]),
264
                new Assert\Regex(
265
                    ['pattern' => '/^[^\s ]+$/u', 'message' => 'form.type.name.firstname.nothasspace']
266
                ),
267
            ]
268
        );
269
270
        $data['customer_kana01'] = mb_convert_kana($data['customer_kana01'], 'CV', 'utf-8');
271
        $errors[] = $this->validator->validate(
272
            $data['customer_kana01'],
273
            [
274
                new Assert\NotBlank(),
275
                new Assert\Length(['max' => $this->eccubeConfig['eccube_kana_len']]),
276
                new Assert\Regex(['pattern' => '/^[ァ-ヶヲ-゚ー]+$/u']),
277
            ]
278
        );
279
        $data['customer_kana02'] = mb_convert_kana($data['customer_kana02'], 'CV', 'utf-8');
280
        $errors[] = $this->validator->validate(
281
            $data['customer_kana02'],
282
            [
283
                new Assert\NotBlank(),
284
                new Assert\Length(['max' => $this->eccubeConfig['eccube_kana_len']]),
285
                new Assert\Regex(['pattern' => '/^[ァ-ヶヲ-゚ー]+$/u']),
286
            ]);
287
288
        $errors[] = $this->validator->validate(
289
            $data['customer_company_name'],
290
            [
291
                new Assert\Length(['max' => $this->eccubeConfig['eccube_stext_len']]),
292
            ]
293
        );
294
295
        $errors[] = $this->validator->validate(
296
            $data['customer_phone_number'],
297
            [
298
                new Assert\NotBlank(),
299
                new Assert\Type(['type' => 'numeric', 'message' => 'form.type.numeric.invalid']),
300
                new Assert\Length(
301
                    ['max' => $this->eccubeConfig['eccube_tel_len_max']]
302
                ),
303
            ]
304
        );
305
306
        $errors[] = $this->validator->validate(
307
            $data['customer_postal_code'],
308
            [
309
                new Assert\NotBlank(),
310
                new Assert\Type(['type' => 'numeric', 'message' => 'form.type.numeric.invalid']),
311
                new Assert\Length(
312
                    ['max' => $this->eccubeConfig['eccube_postal_code']]
313
                ),
314
            ]
315
        );
316
317
        $errors[] = $this->validator->validate(
318
            $data['customer_addr01'],
319
            [
320
                new Assert\NotBlank(),
321
                new Assert\Length(['max' => $this->eccubeConfig['eccube_address1_len']]),
322
            ]
323
        );
324
325
        $errors[] = $this->validator->validate(
326
            $data['customer_addr02'],
327
            [
328
                new Assert\NotBlank(),
329
                new Assert\Length(['max' => $this->eccubeConfig['eccube_address2_len']]),
330
            ]
331
        );
332
333
        $errors[] = $this->validator->validate(
334
            $data['customer_email'],
335
            [
336
                new Assert\NotBlank(),
337
                new Assert\Email(['strict' => true]),
338
            ]
339
        );
340
341
        return $errors;
342
    }
343
}
344