CategoryController   A
last analyzed

Complexity

Total Complexity 20

Size/Duplication

Total Lines 228
Duplicated Lines 30.7 %

Coupling/Cohesion

Components 0
Dependencies 9

Test Coverage

Coverage 63.33%

Importance

Changes 0
Metric Value
dl 70
loc 228
rs 10
c 0
b 0
f 0
ccs 19
cts 30
cp 0.6333
wmc 20
lcom 0
cbo 9

4 Methods

Rating   Name   Duplication   Size   Complexity  
C index() 25 93 11
B delete() 0 40 4
A moveRank() 15 15 3
A export() 30 66 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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\Admin\Product;
26
27
use Eccube\Application;
28
use Eccube\Controller\AbstractController;
29
use Eccube\Entity\Master\CsvType;
30
use Eccube\Event\EccubeEvents;
31
use Eccube\Event\EventArgs;
32
use Symfony\Component\HttpFoundation\Request;
33
use Symfony\Component\HttpFoundation\StreamedResponse;
34
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
35
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
36
37 3
class CategoryController extends AbstractController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
38
{
39 3
    public function index(Application $app, Request $request, $parent_id = null, $id = null)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
40
    {
41 1
        if ($parent_id) {
42
            $Parent = $app['eccube.repository.category']->find($parent_id);
43
            if (!$Parent) {
44
                throw new NotFoundHttpException('親カテゴリが存在しません');
45 2
            }
46 1
        } else {
47 3
            $Parent = null;
48
        }
49 1
        if ($id) {
50
            $TargetCategory = $app['eccube.repository.category']->find($id);
51
            if (!$TargetCategory) {
52
                throw new NotFoundHttpException('カテゴリが存在しません');
53
            }
54
            $Parent = $TargetCategory->getParent();
55
        } else {
56 2
            $TargetCategory = new \Eccube\Entity\Category();
57
            $TargetCategory->setParent($Parent);
58
            if ($Parent) {
59
                $TargetCategory->setLevel($Parent->getLevel() + 1);
60 1
            } else {
61 1
                $TargetCategory->setLevel(1);
62
            }
63
        }
64
65
        //
66
        $builder = $app['form.factory']
67
            ->createBuilder('admin_category', $TargetCategory);
68
69
        $event = new EventArgs(
70
            array(
71
                'builder' => $builder,
72
                'Parent' => $Parent,
73
                'TargetCategory' => $TargetCategory,
74
            ),
75
            $request
76
        );
77
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_PRODUCT_CATEGORY_INDEX_INITIALIZE, $event);
78
79
        $form = $builder->getForm();
80
81
        //
82
        if ($request->getMethod() === 'POST') {
83
            $form->handleRequest($request);
84
            if ($form->isValid()) {
85
                if ($app['config']['category_nest_level'] < $TargetCategory->getLevel()) {
86
                    throw new BadRequestHttpException('リクエストが不正です');
87
                }
88
                log_info('カテゴリ登録開始', array($id));
89
                $status = $app['eccube.repository.category']->save($TargetCategory);
90
91 View Code Duplication
                if ($status) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
92
93
                    log_info('カテゴリ登録完了', array($id));
94
95
                    $event = new EventArgs(
96 3
                        array(
97 3
                            'form' => $form,
98
                            'Parent' => $Parent,
99
                            'TargetCategory' => $TargetCategory,
100
                        ),
101
                        $request
102
                    );
103
                    $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_PRODUCT_CATEGORY_INDEX_COMPLETE, $event);
104
105 3
                    $app->addSuccess('admin.category.save.complete', 'admin');
106
107 1
                    if ($Parent) {
108
                        return $app->redirect($app->url('admin_product_category_show', array('parent_id' => $Parent->getId())));
109
                    } else {
110
                        return $app->redirect($app->url('admin_product_category'));
111
                    }
112 1
                } else {
113
                    log_info('カテゴリ登録エラー', array($id));
114
                    $app->addError('admin.category.save.error', 'admin');
115
                }
116
            }
117
        }
118
119
        $Categories = $app['eccube.repository.category']->getList($Parent);
120 1
121
        // ツリー表示のため、ルートからのカテゴリを取得
122
        $TopCategories = $app['eccube.repository.category']->getList(null);
123
124 1
        return $app->render('Product/category.twig', array(
125
            'form' => $form->createView(),
126 1
            'Parent' => $Parent,
127
            'Categories' => $Categories,
128
            'TopCategories' => $TopCategories,
129
            'TargetCategory' => $TargetCategory,
130
        ));
131 1
    }
132
133
    public function delete(Application $app, Request $request, $id)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
134
    {
135
        $this->isTokenValid($app);
136
137
        $TargetCategory = $app['eccube.repository.category']->find($id);
138
        if (!$TargetCategory) {
139
            $app->deleteMessage();
140
            return $app->redirect($app->url('admin_product_category'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
141
        }
142
        $Parent = $TargetCategory->getParent();
143
144
        log_info('カテゴリ削除開始', array($id));
145
146
        $status = $app['eccube.repository.category']->delete($TargetCategory);
147
148
        if ($status === true) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
149
150
            log_info('カテゴリ削除完了', array($id));
151
152
            $event = new EventArgs(
153
                array(
154
                    'Parent' => $Parent,
155
                    'TargetCategory' => $TargetCategory,
156
                ),
157
                $request
158
            );
159
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_PRODUCT_CATEGORY_DELETE_COMPLETE, $event);
160
161
            $app->addSuccess('admin.category.delete.complete', 'admin');
162
        } else {
163
            log_info('カテゴリ削除エラー', array($id));
164
            $app->addError('admin.category.delete.error', 'admin');
165
        }
166
167
        if ($Parent) {
168
            return $app->redirect($app->url('admin_product_category_show', array('parent_id' => $Parent->getId())));
169
        } else {
170
            return $app->redirect($app->url('admin_product_category'));
171
        }
172
    }
173
174 View Code Duplication
    public function moveRank(Application $app, Request $request)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
175
    {
176
        if ($request->isXmlHttpRequest()) {
177
            $ranks = $request->request->all();
178
            foreach ($ranks as $categoryId => $rank) {
179
                /* @var $Category \Eccube\Entity\Category */
180
                $Category = $app['eccube.repository.category']
181
                    ->find($categoryId);
182
                $Category->setRank($rank);
183
                $app['orm.em']->persist($Category);
184
            }
185
            $app['orm.em']->flush();
186
        }
187
        return true;
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
188
    }
189
190
191
    /**
192
     * カテゴリCSVの出力.
193
     *
194
     * @param Application $app
195
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
196
     * @return StreamedResponse
197
     */
198
    public function export(Application $app, Request $request)
199
    {
200
        // タイムアウトを無効にする.
201
        set_time_limit(0);
202
203
        // sql loggerを無効にする.
204
        $em = $app['orm.em'];
205
        $em->getConfiguration()->setSQLLogger(null);
206
207
        $response = new StreamedResponse();
208
        $response->setCallback(function () use ($app, $request) {
209
210
            // CSV種別を元に初期化.
211
            $app['eccube.service.csv.export']->initCsvType(CsvType::CSV_TYPE_CATEGORY);
212
213
            // ヘッダ行の出力.
214
            $app['eccube.service.csv.export']->exportHeader();
215
216
            $qb = $app['eccube.repository.category']
217
                ->createQueryBuilder('c')
218
                ->orderBy('c.rank', 'DESC');
219
220
            // データ行の出力.
221
            $app['eccube.service.csv.export']->setExportQueryBuilder($qb);
222 View Code Duplication
            $app['eccube.service.csv.export']->exportData(function ($entity, $csvService) use ($app, $request) {
223
224
                $Csvs = $csvService->getCsvs();
225
226
                /** @var $Category \Eccube\Entity\Category */
227
                $Category = $entity;
228
229
                // CSV出力項目と合致するデータを取得.
230
                $ExportCsvRow = new \Eccube\Entity\ExportCsvRow();
231
                foreach ($Csvs as $Csv) {
232
                    $ExportCsvRow->setData($csvService->getData($Csv, $Category));
233
234
                    $event = new EventArgs(
235
                        array(
236
                            'csvService' => $csvService,
237
                            'Csv' => $Csv,
238
                            'Category' => $Category,
239
                            'ExportCsvRow' => $ExportCsvRow,
240
                        ),
241
                        $request
242
                    );
243
                    $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_PRODUCT_CATEGORY_CSV_EXPORT, $event);
244
245
                    $ExportCsvRow->pushData();
246
                }
247
248
                //$row[] = number_format(memory_get_usage(true));
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
249
                // 出力.
250
                $csvService->fputcsv($ExportCsvRow->getRow());
251
            });
252
        });
253
254
        $now = new \DateTime();
255
        $filename = 'category_' . $now->format('YmdHis') . '.csv';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
256
        $response->headers->set('Content-Type', 'application/octet-stream');
257
        $response->headers->set('Content-Disposition', 'attachment; filename=' . $filename);
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
258
        $response->send();
259
260
        log_info('カテゴリCSV出力ファイル名', array($filename));
261
262
        return $response;
263
    }
264
}
265