Failed Conditions
Branch experimental/sf (68db07)
by Kentaro
42:17 queued 33:39
created

NonMemberShoppingController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 5
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
ccs 6
cts 6
cp 1
crap 1
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
                ->setTel01($data['tel01'])
132 17
                ->setTel02($data['tel02'])
133 17
                ->setTel03($data['tel03'])
134 17
                ->setZip01($data['zip01'])
135 17
                ->setZip02($data['zip02'])
136 17
                ->setZipCode($data['zip01'].$data['zip02'])
137 17
                ->setPref($data['pref'])
138 17
                ->setAddr01($data['addr01'])
139 17
                ->setAddr02($data['addr02']);
140
141
            // 受注情報を取得
142
            /** @var Order $Order */
143 17
            $Order = $this->shoppingService->getOrder(OrderStatus::PROCESSING);
144
145
            // 初回アクセス(受注データがない)の場合は, 受注情報を作成
146 17
            if (is_null($Order)) {
147
                // 受注情報を作成
148
                try {
149
                    // 受注情報を作成
150 17
                    $Order = $this->orderHelper->createProcessingOrder(
151 17
                        $Customer,
152 17
                        $cartService->getCart()->getCartItems()
153
                    );
154 17
                    $cartService->setPreOrderId($Order->getPreOrderId());
155 17
                    $cartService->save();
156
                } catch (CartException $e) {
157
                    $this->addRequestError($e->getMessage());
158
159
                    return $this->redirectToRoute('cart');
160
                }
161
            }
162
163 17
            $flowResult = $this->executePurchaseFlow($Order);
164 17
            if ($flowResult->hasWarning() || $flowResult->hasError()) {
165
                return $this->redirectToRoute('cart');
166
            }
167
168
            // 非会員用セッションを作成
169 17
            $this->session->set($this->sessionKey, $Customer);
170 17
            $this->session->set($this->sessionCustomerAddressKey, serialize([]));
171
172 17
            $event = new EventArgs(
173
                [
174 17
                    'form' => $form,
175 17
                    'Order' => $Order,
176
                ],
177 17
                $request
178
            );
179 17
            $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_NONMEMBER_COMPLETE, $event);
180
181 17
            if ($event->getResponse() !== null) {
182
                return $event->getResponse();
183
            }
184
185 17
            log_info('非会員お客様情報登録完了', [$Order->getId()]);
186
187 17
            return $this->redirectToRoute('shopping');
188
        }
189
190
        return [
191 1
            'form' => $form->createView(),
192
        ];
193
    }
194
195
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$id" missing
Loading history...
196
     * お届け先の設定(非会員)がクリックされた場合の処理
197
     *
198
     * @Route("/shopping/shipping_edit_change/{id}", name="shopping_shipping_edit_change", requirements={"id" = "\d+"})
199
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
200
    public function shippingEditChange(Request $request, $id)
201
    {
202
        $Order = $this->shoppingService->getOrder(OrderStatus::PROCESSING);
203
        if (!$Order) {
204
            $this->addError('front.shopping.order.error');
205
206
            return $this->redirectToRoute('shopping_error');
207
        }
208
209
        if ('POST' !== $request->getMethod()) {
210
            return $this->redirectToRoute('shopping');
211
        }
212
213
        $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...
214
215
        $event = new EventArgs(
216
            [
217
                'builder' => $builder,
218
                'Order' => $Order,
219
            ],
220
            $request
221
        );
222
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_EDIT_CHANGE_INITIALIZE, $event);
223
224
        $form = $builder->getForm();
225
226
        $form->handleRequest($request);
227
228
        if ($form->isSubmitted() && $form->isValid()) {
229
            $data = $form->getData();
230
            $message = $data['message'];
231
            $Order->setMessage($message);
232
            // 受注情報を更新
233
            $this->entityManager->flush();
234
235
            // お届け先設定一覧へリダイレクト
236
            return $this->redirectToRoute('shopping_shipping_edit', ['id' => $id]);
237
        }
238
239
        return $this->redirectToRoute('Shopping/index.twig', [
240
            'form' => $form->createView(),
241
            'Order' => $Order,
242
        ]);
243
    }
244
245
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
246
     * お客様情報の変更(非会員)
247
     *
248
     * @Route("/shopping/customer", name="shopping_customer")
249
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
250
    public function customer(Request $request)
251
    {
252 View Code Duplication
        if (!$request->isXmlHttpRequest()) {
253
            $response = new Response(json_encode(['status' => 'NG']), 400);
254
            $response->headers->set('Content-Type', 'application/json');
255
256
            return $response;
257
        }
258
        try {
259
            log_info('非会員お客様情報変更処理開始');
260
            $data = $request->request->all();
261
            // 入力チェック
262
            $errors = $this->customerValidation($data);
263
            foreach ($errors as $error) {
264 View Code Duplication
                if ($error->count() != 0) {
265
                    log_info('非会員お客様情報変更入力チェックエラー');
266
                    $response = new Response(json_encode('NG'), 400);
267
                    $response->headers->set('Content-Type', 'application/json');
268
269
                    return $response;
270
                }
271
            }
272
            $pref = $this->prefRepository->findOneBy(['name' => $data['customer_pref']]);
273 View Code Duplication
            if (!$pref) {
274
                log_info('非会員お客様情報変更入力チェックエラー');
275
                $response = new Response(json_encode('NG'), 400);
276
                $response->headers->set('Content-Type', 'application/json');
277
278
                return $response;
279
            }
280
            $Order = $this->shoppingService->getOrder(OrderStatus::PROCESSING);
281
            if (!$Order) {
282
                log_info('カートが存在しません');
283
                $this->addError('front.shopping.order.error');
284
285
                return $this->redirectToRoute('shopping_error');
286
            }
287
            $Order
288
                ->setName01($data['customer_name01'])
289
                ->setName02($data['customer_name02'])
290
                ->setKana01($data['customer_kana01'])
291
                ->setKana02($data['customer_kana02'])
292
                ->setCompanyName($data['customer_company_name'])
293
                ->setTel01($data['customer_tel01'])
294
                ->setTel02($data['customer_tel02'])
295
                ->setTel03($data['customer_tel03'])
296
                ->setZip01($data['customer_zip01'])
297
                ->setZip02($data['customer_zip02'])
298
                ->setZipCode($data['customer_zip01'].$data['customer_zip02'])
299
                ->setPref($pref)
300
                ->setAddr01($data['customer_addr01'])
301
                ->setAddr02($data['customer_addr02'])
302
                ->setEmail($data['customer_email']);
303
            // 配送先を更新
304
            $this->entityManager->flush();
305
            // 受注関連情報を最新状態に更新
306
            $this->entityManager->refresh($Order);
307
            $event = new EventArgs(
308
                [
309
                    'Order' => $Order,
310
                    'data' => $data,
311
                ],
312
                $request
313
            );
314
            $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_CUSTOMER_INITIALIZE, $event);
315
            log_info('非会員お客様情報変更処理完了', [$Order->getId()]);
316
            $message = ['status' => 'OK', 'kana01' => $data['customer_kana01'], 'kana02' => $data['customer_kana02']];
317
            $response = new Response(json_encode($message));
318
            $response->headers->set('Content-Type', 'application/json');
319
        } catch (\Exception $e) {
320
            log_error('予期しないエラー', [$e->getMessage()]);
321
            $response = new Response(json_encode(['status' => 'NG']), 500);
322
            $response->headers->set('Content-Type', 'application/json');
323
        }
324
325
        return $response;
326
    }
327
328
    /**
329
     * 非会員でのお客様情報変更時の入力チェック
330
     *
331
     * @param array $data リクエストパラメータ
332
     *
333
     * @return array
334
     */
335
    protected function customerValidation(array &$data)
336
    {
337
        // 入力チェック
338
        $errors = [];
339
340
        $errors[] = $this->validator->validate(
341
            $data['customer_name01'],
342
            [
343
                new Assert\NotBlank(),
344
                new Assert\Length(['max' => $this->eccubeConfig['eccube_name_len']]),
345
                new Assert\Regex(
346
                    ['pattern' => '/^[^\s ]+$/u', 'message' => 'form.type.name.firstname.nothasspace']
347
                ),
348
            ]
349
        );
350
351
        $errors[] = $this->validator->validate(
352
            $data['customer_name02'],
353
            [
354
                new Assert\NotBlank(),
355
                new Assert\Length(['max' => $this->eccubeConfig['eccube_name_len']]),
356
                new Assert\Regex(
357
                    ['pattern' => '/^[^\s ]+$/u', 'message' => 'form.type.name.firstname.nothasspace']
358
                ),
359
            ]
360
        );
361
362
        $data['customer_kana01'] = mb_convert_kana($data['customer_kana01'], 'CV', 'utf-8');
363
        $errors[] = $this->validator->validate(
364
            $data['customer_kana01'],
365
            [
366
                new Assert\NotBlank(),
367
                new Assert\Length(['max' => $this->eccubeConfig['eccube_kana_len']]),
368
                new Assert\Regex(['pattern' => '/^[ァ-ヶヲ-゚ー]+$/u']),
369
            ]
370
        );
371
        $data['customer_kana02'] = mb_convert_kana($data['customer_kana02'], 'CV', 'utf-8');
372
        $errors[] = $this->validator->validate(
373
            $data['customer_kana02'],
374
            [
375
                new Assert\NotBlank(),
376
                new Assert\Length(['max' => $this->eccubeConfig['eccube_kana_len']]),
377
                new Assert\Regex(['pattern' => '/^[ァ-ヶヲ-゚ー]+$/u']),
378
        ]);
379
380
        $errors[] = $this->validator->validate(
381
            $data['customer_company_name'],
382
            [
383
                new Assert\Length(['max' => $this->eccubeConfig['eccube_stext_len']]),
384
            ]
385
        );
386
387
        $errors[] = $this->validator->validate(
388
            $data['customer_tel01'],
389
            [
390
                new Assert\NotBlank(),
391
                new Assert\Type(['type' => 'numeric', 'message' => 'form.type.numeric.invalid']),
392
                new Assert\Length(
393
                    ['max' => $this->eccubeConfig['eccube_tel_len'], 'min' => $this->eccubeConfig['eccube_tel_len_min']]
394
                ),
395
            ]
396
        );
397
398
        $errors[] = $this->validator->validate(
399
            $data['customer_tel02'],
400
            [
401
                new Assert\NotBlank(),
402
                new Assert\Type(['type' => 'numeric', 'message' => 'form.type.numeric.invalid']),
403
                new Assert\Length(
404
                    ['max' => $this->eccubeConfig['eccube_tel_len'], 'min' => $this->eccubeConfig['eccube_tel_len_min']]
405
                ),
406
            ]
407
        );
408
409
        $errors[] = $this->validator->validate(
410
            $data['customer_tel03'],
411
            [
412
                new Assert\NotBlank(),
413
                new Assert\Type(['type' => 'numeric', 'message' => 'form.type.numeric.invalid']),
414
                new Assert\Length(
415
                    ['max' => $this->eccubeConfig['eccube_tel_len'], 'min' => $this->eccubeConfig['eccube_tel_len_min']]
416
                ),
417
            ]
418
        );
419
420
        $errors[] = $this->validator->validate(
421
            $data['customer_zip01'],
422
            [
423
                new Assert\NotBlank(),
424
                new Assert\Type(['type' => 'numeric', 'message' => 'form.type.numeric.invalid']),
425
                new Assert\Length(
426
                    ['min' => $this->eccubeConfig['eccube_zip01_len'], 'max' => $this->eccubeConfig['eccube_zip01_len']]
427
                ),
428
            ]
429
        );
430
431
        $errors[] = $this->validator->validate(
432
            $data['customer_zip02'],
433
            [
434
                new Assert\NotBlank(),
435
                new Assert\Type(['type' => 'numeric', 'message' => 'form.type.numeric.invalid']),
436
                new Assert\Length(
437
                    ['min' => $this->eccubeConfig['eccube_zip02_len'], 'max' => $this->eccubeConfig['eccube_zip02_len']]
438
                ),
439
            ]
440
        );
441
442
        $errors[] = $this->validator->validate(
443
            $data['customer_addr01'],
444
            [
445
                new Assert\NotBlank(),
446
                new Assert\Length(['max' => $this->eccubeConfig['eccube_address1_len']]),
447
            ]
448
        );
449
450
        $errors[] = $this->validator->validate(
451
            $data['customer_addr02'],
452
            [
453
                new Assert\NotBlank(),
454
                new Assert\Length(['max' => $this->eccubeConfig['eccube_address2_len']]),
455
            ]
456
        );
457
458
        $errors[] = $this->validator->validate(
459
            $data['customer_email'],
460
            [
461
                new Assert\NotBlank(),
462
                new Assert\Email(['strict' => true]),
463
            ]
464
        );
465
466
        return $errors;
467
    }
468
}
469