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

ProductController::index()   D

Complexity

Conditions 13
Paths 128

Size

Total Lines 154
Code Lines 90

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 59
CRAP Score 14.1924

Importance

Changes 0
Metric Value
cc 13
eloc 90
nc 128
nop 2
dl 0
loc 154
rs 4.6605
c 0
b 0
f 0
ccs 59
cts 73
cp 0.8082
crap 14.1924

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-2015 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
25
namespace Eccube\Controller;
26
27
use Eccube\Application;
28
use Eccube\Common\Constant;
29
use Eccube\Entity\ProductClass;
30
use Eccube\Event\EccubeEvents;
31
use Eccube\Event\EventArgs;
32
use Eccube\Exception\CartException;
33
use Eccube\Form\Type\AddCartType;
34
use Eccube\Form\Type\Master\ProductListMaxType;
35
use Eccube\Form\Type\Master\ProductListOrderByType;
36
use Eccube\Form\Type\SearchProductType;
37
use Eccube\Service\PurchaseFlow\PurchaseContext;
38
use Symfony\Component\HttpFoundation\Request;
39
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
40
41
class ProductController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
42
{
43
44 5
    private $title;
45
46 5
    public function __construct()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
47
    {
48
        $this->title = '';
49 2
    }
50
51 2
    public function index(Application $app, Request $request)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
52
    {
53
        $BaseInfo = $app['eccube.repository.base_info']->get();
54 2
55
        // Doctrine SQLFilter
56
        if ($BaseInfo->getNostockHidden() === Constant::ENABLED) {
57
            $app['orm.em']->getFilters()->enable('nostock_hidden');
58
        }
59 2
60 2
        // handleRequestは空のqueryの場合は無視するため
61
        if ($request->getMethod() === 'GET') {
62
            $request->query->set('pageno', $request->query->get('pageno', ''));
63
        }
64
65 2
        // searchForm
66 2
        /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
67 2
        $builder = $app['form.factory']->createNamedBuilder('', SearchProductType::class);
68 2
        $builder->setAttribute('freeze', true);
69 2
        $builder->setAttribute('freeze_display_text', false);
70
        if ($request->getMethod() === 'GET') {
71
            $builder->setMethod('GET');
72 2
        }
73
74 2
        $event = new EventArgs(
75
            array(
76
                'builder' => $builder,
77
            ),
78 2
            $request
79
        );
80
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_PRODUCT_INDEX_INITIALIZE, $event);
81 2
82
        /* @var $searchForm \Symfony\Component\Form\FormInterface */
83 2
        $searchForm = $builder->getForm();
84
85
        $searchForm->handleRequest($request);
86 2
87 2
        // paginator
88
        $searchData = $searchForm->getData();
89 2
        $qb = $app['eccube.repository.product']->getQueryBuilderBySearchData($searchData);
90
91 2
        $event = new EventArgs(
92 2
            array(
93
                'searchData' => $searchData,
94
                'qb' => $qb,
95
            ),
96 2
            $request
97 2
        );
98
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_PRODUCT_INDEX_SEARCH, $event);
99 2
        $searchData = $event->getArgument('searchData');
100
101 2
        $pagination = $app['paginator']()->paginate(
102 2
            $qb,
103
            !empty($searchData['pageno']) ? $searchData['pageno'] : 1,
104
            $searchData['disp_number']->getId()
105
        );
106 2
107 2
        // addCart form
108
        $forms = array();
109 2
        foreach ($pagination as $Product) {
110 2
            /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
111
            $builder = $app['form.factory']->createNamedBuilder('', AddCartType::class, null, array(
112
                'product' => $Product,
113 2
                'allow_extra_fields' => true,
114
            ));
115 2
            $addCartForm = $builder->getForm();
116
117
            if ($request->getMethod() === 'POST' && (string)$Product->getId() === $request->get('product_id')) {
0 ignored issues
show
Coding Style introduced by
As per coding-style, a cast statement should be followed by a single space.
Loading history...
118
                $addCartForm->handleRequest($request);
119
120
                if ($addCartForm->isValid()) {
121
                    $addCartData = $addCartForm->getData();
122
123
                    try {
124
                        $app['eccube.service.cart']->addProduct($addCartData['product_class_id'], $addCartData['quantity'])->save();
125
                    } catch (CartException $e) {
126
                        $app->addRequestError($e->getMessage());
127
                    }
128
129
                    $event = new EventArgs(
130
                        array(
131
                            'form' => $addCartForm,
132
                            'Product' => $Product,
133
                        ),
134
                        $request
135
                    );
136
                    $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_PRODUCT_INDEX_COMPLETE, $event);
137
138
                    if ($event->getResponse() !== null) {
139
                        return $event->getResponse();
140
                    }
141
142
                    return $app->redirect($app->url('cart'));
143
                }
144 2
            }
145
146
            $forms[$Product->getId()] = $addCartForm->createView();
147
        }
148 2
149 2
        // 表示件数
150
        $builder = $app['form.factory']->createNamedBuilder('disp_number', ProductListMaxType::class, null, array(
151
            'required' => false,
152
            'label' => '表示件数',
153 2
            'allow_extra_fields' => true,
154 2
        ));
155
        if ($request->getMethod() === 'GET') {
156
            $builder->setMethod('GET');
157 2
        }
158
159 2
        $event = new EventArgs(
160
            array(
161
                'builder' => $builder,
162
            ),
163 2
            $request
164
        );
165 2
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_PRODUCT_INDEX_DISP, $event);
166
167 2
        $dispNumberForm = $builder->getForm();
168
169
        $dispNumberForm->handleRequest($request);
170 2
171 2
        // ソート順
172
        $builder = $app['form.factory']->createNamedBuilder('orderby', ProductListOrderByType::class, null, array(
173
            'required' => false,
174
            'label' => '表示順',
175 2
            'allow_extra_fields' => true,
176 2
        ));
177
        if ($request->getMethod() === 'GET') {
178
            $builder->setMethod('GET');
179 2
        }
180
181 2
        $event = new EventArgs(
182
            array(
183
                'builder' => $builder,
184
            ),
185 2
            $request
186
        );
187 2
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_PRODUCT_INDEX_ORDER, $event);
188
189 2
        $orderByForm = $builder->getForm();
190
191 2
        $orderByForm->handleRequest($request);
192
193 2
        $Category = $searchForm->get('category_id')->getData();
194 2
195 2
        return $app->render('Product/list.twig', array(
196 2
            'subtitle' => $this->getPageTitle($searchData),
197 2
            'pagination' => $pagination,
198 2
            'search_form' => $searchForm->createView(),
199 2
            'disp_number_form' => $dispNumberForm->createView(),
200 2
            'order_by_form' => $orderByForm->createView(),
201
            'forms' => $forms,
202
            'Category' => $Category,
203
        ));
204 3
    }
205
206 3
    public function detail(Application $app, Request $request, $id)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
207 3
    {
208
        $BaseInfo = $app['eccube.repository.base_info']->get();
209
        if ($BaseInfo->getNostockHidden() === Constant::ENABLED) {
210
            $app['orm.em']->getFilters()->enable('nostock_hidden');
211
        }
212 3
213 3
        /* @var $Product \Eccube\Entity\Product */
214
        $Product = $app['eccube.repository.product']->get($id);
215
        if (!$request->getSession()->has('_security_admin') && $Product->getStatus()->getId() !== 1) {
216 3
            throw new NotFoundHttpException();
217
        }
218
        if (count($Product->getProductClasses()) < 1) {
219
            throw new NotFoundHttpException();
220
        }
221 3
222 3
        /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
223
        $builder = $app['form.factory']->createNamedBuilder('', AddCartType::class, null, array(
224
            'product' => $Product,
225
            'id_add_product_id' => false,
226 3
        ));
227
228 3
        $event = new EventArgs(
229 3
            array(
230
                'builder' => $builder,
231
                'Product' => $Product,
232
            ),
233 3
            $request
234
        );
235
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE, $event);
236 3
237
        /* @var $form \Symfony\Component\Form\FormInterface */
238 3
        $form = $builder->getForm();
239 1
240
        if ($request->getMethod() === 'POST') {
241 1
            $form->handleRequest($request);
242
243
            if ($form->isValid()) {
244
                $addCartData = $form->getData();
245
                if ($addCartData['mode'] === 'add_favorite') {
246
                    if ($app->isGranted('ROLE_USER')) {
247
                        $Customer = $app->user();
248
                        $app['eccube.repository.customer_favorite_product']->addFavorite($Customer, $Product);
249
                        $app['session']->getFlashBag()->set('product_detail.just_added_favorite', $Product->getId());
250
251
                        $event = new EventArgs(
252
                            array(
253
                                'form' => $form,
254
                                'Product' => $Product,
255
                            ),
256
                            $request
257
                        );
258
                        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_PRODUCT_DETAIL_FAVORITE, $event);
259
260
                        if ($event->getResponse() !== null) {
261
                            return $event->getResponse();
262
                        }
263
264
                        return $app->redirect($app->url('product_detail', array('id' => $Product->getId())));
265
                    } else {
266
                        // 非会員の場合、ログイン画面を表示
267
                        //  ログイン後の画面遷移先を設定
268
                        $app->setLoginTargetPath($app->url('product_detail', array('id' => $Product->getId())));
269
                        $app['session']->getFlashBag()->set('eccube.add.favorite', true);
270
                        return $app->redirect($app->url('mypage_login'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
271
                    }
272
                } elseif ($addCartData['mode'] === 'add_cart') {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
273
274
                    log_info('カート追加処理開始', array('product_id' => $Product->getId(), 'product_class_id' => $addCartData['product_class_id'], 'quantity' => $addCartData['quantity']));
275
276
                    // カートを取得
277
                    $Cart = $app['eccube.service.cart']->getCart();
278
279
                    // カートへ追加
280
                    $app['eccube.service.cart']->addProduct($addCartData['product_class_id'], $addCartData['quantity']);
281
282
                    // 明細の正規化
283
                    $flow = $app['eccube.purchase.flow.cart'];
284
                    $result = $flow->calculate($Cart, PurchaseContext::create());
285
286
                    // 復旧不可のエラーが発生した場合は追加した明細を削除.
287
                    if ($result->hasError()) {
288
                        $Cart->removeCartItemByIdentifier(ProductClass::class, $addCartData['product_class_id']);
289
                        foreach ($result->getErrors() as $error) {
290
                            $app->addRequestError($error);
291
                        }
292
                    }
293
294
                    foreach ($result->getWarning() as $warning) {
295
                        $app->addRequestError($warning);
296 1
                    }
297
298
                    $app['eccube.service.cart']->save();
299
300 2
                    log_info('カート追加処理完了', array('product_id' => $Product->getId(), 'product_class_id' => $addCartData['product_class_id'], 'quantity' => $addCartData['quantity']));
301 2
302
                    $event = new EventArgs(
303
                        array(
304
                            'form' => $form,
305
                            'Product' => $Product,
306
                        ),
307
                        $request
308
                    );
309
                    $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_PRODUCT_DETAIL_COMPLETE, $event);
310
311 3
                    if ($event->getResponse() !== null) {
312 3
                        return $event->getResponse();
313
                    }
314
315
                    return $app->redirect($app->url('cart'));
316
                }
317 3
            }
318 3
        } else {
319 3
            $addFavorite = $app['session']->getFlashBag()->get('eccube.add.favorite');
320 3
            if (!empty($addFavorite)) {
321 3
                // お気に入り登録時にログインされていない場合、ログイン後にお気に入り追加処理を行う
322 3
                if ($app->isGranted('ROLE_USER')) {
323
                    $Customer = $app->user();
324
                    $app['eccube.repository.customer_favorite_product']->addFavorite($Customer, $Product);
325
                    $app['session']->getFlashBag()->set('product_detail.just_added_favorite', $Product->getId());
326
                }
327
            }
328
        }
329
330
        $is_favorite = false;
331
        if ($app->isGranted('ROLE_USER')) {
332 2
            $Customer = $app->user();
333
            $is_favorite = $app['eccube.repository.customer_favorite_product']->isFavorite($Customer, $Product);
334 2
        }
335
336 2
        return $app->render('Product/detail.twig', array(
337
            'title' => $this->title,
338
            'subtitle' => $Product->getName(),
339 2
            'form' => $form->createView(),
340
            'Product' => $Product,
341
            'is_favorite' => $is_favorite,
342
        ));
343
    }
344
345
    /**
346
     * ページタイトルの設定
347
     *
348
     * @param  null|array $searchData
349
     * @return str
350
     */
351
    private function getPageTitle($searchData)
352
    {
353
        if (isset($searchData['name']) && !empty($searchData['name'])) {
354
            return '検索結果';
355
        } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
356
            return $searchData['category_id']->getName();
357
        } else {
358
            return '全商品';
359
        }
360
    }
361
}
362