Failed Conditions
Push — experimental/3.1 ( 965511...751c7a )
by chihiro
21s
created

NonMemberShoppingController::index()   C

Complexity

Conditions 11
Paths 12

Size

Total Lines 130
Code Lines 86

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 86
nc 12
nop 2
dl 0
loc 130
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 Eccube\Application;
28
use Eccube\Common\Constant;
29
use Eccube\Entity\Customer;
30
use Eccube\Entity\CustomerAddress;
31
use Eccube\Entity\Order;
32
use Eccube\Event\EccubeEvents;
33
use Eccube\Event\EventArgs;
34
use Eccube\Exception\CartException;
35
use Eccube\Form\Type\Front\NonMemberType;
36
use Eccube\Form\Type\Front\ShoppingShippingType;
37
use Symfony\Component\HttpFoundation\Request;
38
use Symfony\Component\HttpFoundation\Response;
39
use Symfony\Component\Validator\Constraints as Assert;
40
41
class NonMemberShoppingController extends AbstractShoppingController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
42
{
43
44
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
45
     * 非会員処理
46
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
47
    public function index(Application $app, Request $request)
48
    {
49
        $cartService = $app['eccube.service.cart'];
50
51
        // カートチェック
52
        $response = $app->forward($app->path("shopping/checkToCart"));
53
        if ($response->isRedirection() || $response->getContent()) {
54
            return $response;
55
        }
56
57
        // ログイン済みの場合は, 購入画面へリダイレクト.
58
        if ($app->isGranted('ROLE_USER')) {
59
            return $app->redirect($app->url('shopping'));
60
        }
61
62
        $builder = $app['form.factory']->createBuilder(NonMemberType::class);
63
64
        $event = new EventArgs(
65
            array(
66
                'builder' => $builder,
67
            ),
68
            $request
69
        );
70
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_NONMEMBER_INITIALIZE, $event);
71
72
        $form = $builder->getForm();
73
74
        $form->handleRequest($request);
75
76
        if ($form->isSubmitted() && $form->isValid()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
77
78
            log_info('非会員お客様情報登録開始');
79
80
            $data = $form->getData();
81
            $Customer = new Customer();
82
            $Customer
83
                ->setName01($data['name01'])
84
                ->setName02($data['name02'])
85
                ->setKana01($data['kana01'])
86
                ->setKana02($data['kana02'])
87
                ->setCompanyName($data['company_name'])
88
                ->setEmail($data['email'])
89
                ->setTel01($data['tel01'])
90
                ->setTel02($data['tel02'])
91
                ->setTel03($data['tel03'])
92
                ->setZip01($data['zip01'])
93
                ->setZip02($data['zip02'])
94
                ->setZipCode($data['zip01'].$data['zip02'])
95
                ->setPref($data['pref'])
96
                ->setAddr01($data['addr01'])
97
                ->setAddr02($data['addr02']);
98
99
            // 非会員複数配送用
100
            $CustomerAddress = new CustomerAddress();
101
            $CustomerAddress
102
                ->setCustomer($Customer)
103
                ->setName01($data['name01'])
104
                ->setName02($data['name02'])
105
                ->setKana01($data['kana01'])
106
                ->setKana02($data['kana02'])
107
                ->setCompanyName($data['company_name'])
108
                ->setTel01($data['tel01'])
109
                ->setTel02($data['tel02'])
110
                ->setTel03($data['tel03'])
111
                ->setZip01($data['zip01'])
112
                ->setZip02($data['zip02'])
113
                ->setZipCode($data['zip01'].$data['zip02'])
114
                ->setPref($data['pref'])
115
                ->setAddr01($data['addr01'])
116
                ->setAddr02($data['addr02'])
117
                ->setDelFlg(Constant::DISABLED);
118
            $Customer->addCustomerAddress($CustomerAddress);
119
120
            // 受注情報を取得
121
            /** @var Order $Order */
122
            $Order = $app['eccube.service.shopping']->getOrder($app['config']['order_processing']);
123
124
            // 初回アクセス(受注データがない)の場合は, 受注情報を作成
125
            if (is_null($Order)) {
126
                // 受注情報を作成
127
                try {
128
                    // 受注情報を作成
129
//                    $Order = $app['eccube.service.shopping']->createOrder($Customer);
130
                    $Order = $app['eccube.helper.order']->createProcessingOrder(
131
                        $Customer, $Customer->getCustomerAddresses()->current(), $cartService->getCart()->getCartItems());
132
                    $cartService->setPreOrderId($Order->getPreOrderId());
133
                    $cartService->save();
134
                } catch (CartException $e) {
135
                    $app->addRequestError($e->getMessage());
136
                    return $app->redirect($app->url('cart'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
137
                }
138
            }
139
140
            $flowResult = $this->executePurchaseFlow($app, $Order);
141
            if ($flowResult->hasWarning() || $flowResult->hasError()) {
142
                return $app->redirect($app->url('cart'));
143
            }
144
145
            // 非会員用セッションを作成
146
            $nonMember = array();
147
            $nonMember['customer'] = $Customer;
148
            $nonMember['pref'] = $Customer->getPref()->getId();
149
            $app['session']->set($this->sessionKey, $nonMember);
150
151
            $customerAddresses = array();
152
            $customerAddresses[] = $CustomerAddress;
153
            $app['session']->set($this->sessionCustomerAddressKey, serialize($customerAddresses));
154
155
            $event = new EventArgs(
156
                array(
157
                    'form' => $form,
158
                    'Order' => $Order,
159
                ),
160
                $request
161
            );
162
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_NONMEMBER_COMPLETE, $event);
163
164
            if ($event->getResponse() !== null) {
165
                return $event->getResponse();
166
            }
167
168
            log_info('非会員お客様情報登録完了', array($Order->getId()));
169
170
            return $app->redirect($app->url('shopping'));
171
        }
172
173
        return $app->render('Shopping/nonmember.twig', array(
174
            'form' => $form->createView(),
175
        ));
176
    }
177
178
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
179
     * 非会員用複数配送設定時の新規お届け先の設定
180
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
181
    public function shippingMultipleEdit(Application $app, Request $request)
182
    {
183
        // カートチェック
184
        $response = $app->forward($app->path("shopping/checkToCart"));
185
        if ($response->isRedirection() || $response->getContent()) {
186
            return $response;
187
        }
188
189
        // 非会員用Customerを取得
190
        $Customer = $app['eccube.service.shopping']->getNonMember($this->sessionKey);
191
        $CustomerAddress = new CustomerAddress();
192
        $CustomerAddress->setCustomer($Customer);
193
        $Customer->addCustomerAddress($CustomerAddress);
194
195
        $builder = $app['form.factory']->createBuilder(ShoppingShippingType::class, $CustomerAddress);
196
197
        $event = new EventArgs(
198
            array(
199
                'builder' => $builder,
200
                'Customer' => $Customer,
201
            ),
202
            $request
203
        );
204
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_MULTIPLE_EDIT_INITIALIZE, $event);
205
206
        $form = $builder->getForm();
207
208
        $form->handleRequest($request);
209
210
        if ($form->isSubmitted() && $form->isValid()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
211
212
            log_info('非会員お届け先追加処理開始');
213
214
            // 非会員用のセッションに追加
215
            $customerAddresses = $app['session']->get($this->sessionCustomerAddressKey);
216
            $customerAddresses = unserialize($customerAddresses);
217
            $customerAddresses[] = $CustomerAddress;
218
            $app['session']->set($this->sessionCustomerAddressKey, serialize($customerAddresses));
219
220
            $event = new EventArgs(
221
                array(
222
                    'form' => $form,
223
                    'CustomerAddresses' => $customerAddresses,
224
                ),
225
                $request
226
            );
227
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_MULTIPLE_EDIT_COMPLETE, $event);
228
229
            log_info('非会員お届け先追加処理完了');
230
231
            return $app->redirect($app->url('shopping_shipping_multiple'));
232
        }
233
234
        return $app->render('Shopping/shipping_multiple_edit.twig', array(
235
            'form' => $form->createView(),
236
        ));
237
    }
238
239
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
240
     * お客様情報の変更(非会員)
241
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
242
    public function customer(Application $app, Request $request)
243
    {
244
        if ($request->isXmlHttpRequest()) {
245
            try {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
246
247
                log_info('非会員お客様情報変更処理開始');
248
249
                $data = $request->request->all();
250
251
                // 入力チェック
252
                $errors = $this->customerValidation($app, $data);
253
254
                foreach ($errors as $error) {
255 View Code Duplication
                    if ($error->count() != 0) {
256
                        log_info('非会員お客様情報変更入力チェックエラー');
257
                        $response = new Response(json_encode('NG'), 400);
258
                        $response->headers->set('Content-Type', 'application/json');
259
                        return $response;
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
260
                    }
261
                }
262
263
                $pref = $app['eccube.repository.master.pref']->findOneBy(array('name' => $data['customer_pref']));
264 View Code Duplication
                if (!$pref) {
265
                    log_info('非会員お客様情報変更入力チェックエラー');
266
                    $response = new Response(json_encode('NG'), 400);
267
                    $response->headers->set('Content-Type', 'application/json');
268
                    return $response;
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
269
                }
270
271
                $Order = $app['eccube.service.shopping']->getOrder($app['config']['order_processing']);
272
                if (!$Order) {
273
                    log_info('カートが存在しません');
274
                    $app->addError('front.shopping.order.error');
275
                    return $app->redirect($app->url('shopping_error'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
276
                }
277
278
                $Order
279
                    ->setName01($data['customer_name01'])
280
                    ->setName02($data['customer_name02'])
281
                    ->setCompanyName($data['customer_company_name'])
282
                    ->setTel01($data['customer_tel01'])
283
                    ->setTel02($data['customer_tel02'])
284
                    ->setTel03($data['customer_tel03'])
285
                    ->setZip01($data['customer_zip01'])
286
                    ->setZip02($data['customer_zip02'])
287
                    ->setZipCode($data['customer_zip01'].$data['customer_zip02'])
288
                    ->setPref($pref)
289
                    ->setAddr01($data['customer_addr01'])
290
                    ->setAddr02($data['customer_addr02'])
291
                    ->setEmail($data['customer_email']);
292
293
                // 配送先を更新
294
                $app['orm.em']->flush();
295
296
                // 受注関連情報を最新状態に更新
297
                $app['orm.em']->refresh($Order);
298
299
                $event = new EventArgs(
300
                    array(
301
                        'Order' => $Order,
302
                        'data' => $data,
303
                    ),
304
                    $request
305
                );
306
                $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_SHOPPING_CUSTOMER_INITIALIZE, $event);
307
308
                log_info('非会員お客様情報変更処理完了', array($Order->getId()));
309
                $response = new Response(json_encode('OK'));
310
                $response->headers->set('Content-Type', 'application/json');
311
            } catch (\Exception $e) {
312
                log_error('予期しないエラー', array($e->getMessage()));
313
                $app['monolog']->error($e);
314
315
                $response = new Response(json_encode('NG'), 500);
316
                $response->headers->set('Content-Type', 'application/json');
317
            }
318
319
            return $response;
320
        }
321
    }
322
323
    /**
324
     * 非会員でのお客様情報変更時の入力チェック
325
     *
326
     * @param Application $app
327
     * @param array $data リクエストパラメータ
328
     * @return array
329
     */
330
    protected function customerValidation(Application $app, array $data)
331
    {
332
        // 入力チェック
333
        $errors = array();
334
335
        $errors[] = $app['validator']->validate($data['customer_name01'], array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
336
            new Assert\NotBlank(),
337
            new Assert\Length(array('max' => $app['config']['name_len'],)),
0 ignored issues
show
introduced by
Add a single space after each comma delimiter
Loading history...
338
            new Assert\Regex(array('pattern' => '/^[^\s ]+$/u', 'message' => 'form.type.name.firstname.nothasspace'))
339
        ));
340
341
        $errors[] = $app['validator']->validate($data['customer_name02'], array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
342
            new Assert\NotBlank(),
343
            new Assert\Length(array('max' => $app['config']['name_len'],)),
0 ignored issues
show
introduced by
Add a single space after each comma delimiter
Loading history...
344
            new Assert\Regex(array('pattern' => '/^[^\s ]+$/u', 'message' => 'form.type.name.firstname.nothasspace'))
345
        ));
346
347
        $errors[] = $app['validator']->validate($data['customer_company_name'], array(
348
            new Assert\Length(array('max' => $app['config']['stext_len'])),
349
        ));
350
351
        $errors[] = $app['validator']->validate($data['customer_tel01'], array(
352
            new Assert\NotBlank(),
353
            new Assert\Type(array('type' => 'numeric', 'message' => 'form.type.numeric.invalid')),
354
            new Assert\Length(array('max' => $app['config']['tel_len'], 'min' => $app['config']['tel_len_min'])),
355
        ));
356
357
        $errors[] = $app['validator']->validate($data['customer_tel02'], array(
358
            new Assert\NotBlank(),
359
            new Assert\Type(array('type' => 'numeric', 'message' => 'form.type.numeric.invalid')),
360
            new Assert\Length(array('max' => $app['config']['tel_len'], 'min' => $app['config']['tel_len_min'])),
361
        ));
362
363
        $errors[] = $app['validator']->validate($data['customer_tel03'], array(
364
            new Assert\NotBlank(),
365
            new Assert\Type(array('type' => 'numeric', 'message' => 'form.type.numeric.invalid')),
366
            new Assert\Length(array('max' => $app['config']['tel_len'], 'min' => $app['config']['tel_len_min'])),
367
        ));
368
369
        $errors[] = $app['validator']->validate($data['customer_zip01'], array(
370
            new Assert\NotBlank(),
371
            new Assert\Type(array('type' => 'numeric', 'message' => 'form.type.numeric.invalid')),
372
            new Assert\Length(array('min' => $app['config']['zip01_len'], 'max' => $app['config']['zip01_len'])),
373
        ));
374
375
        $errors[] = $app['validator']->validate($data['customer_zip02'], array(
376
            new Assert\NotBlank(),
377
            new Assert\Type(array('type' => 'numeric', 'message' => 'form.type.numeric.invalid')),
378
            new Assert\Length(array('min' => $app['config']['zip02_len'], 'max' => $app['config']['zip02_len'])),
379
        ));
380
381
        $errors[] = $app['validator']->validate($data['customer_addr01'], array(
382
            new Assert\NotBlank(),
383
            new Assert\Length(array('max' => $app['config']['address1_len'])),
384
        ));
385
386
        $errors[] = $app['validator']->validate($data['customer_addr02'], array(
387
            new Assert\NotBlank(),
388
            new Assert\Length(array('max' => $app['config']['address2_len'])),
389
        ));
390
391
        $errors[] = $app['validator']->validate($data['customer_email'], array(
392
            new Assert\NotBlank(),
393
            new Assert\Email(array('strict' => true)),
394
        ));
395
396
        return $errors;
397
    }
398
}