Failed Conditions
Pull Request — experimental/3.1 (#2449)
by Kiyotaka
52:40
created

AdminController   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 389
Duplicated Lines 17.48 %

Coupling/Cohesion

Components 1
Dependencies 9

Test Coverage

Coverage 96.79%

Importance

Changes 0
Metric Value
dl 68
loc 389
ccs 181
cts 187
cp 0.9679
rs 10
c 0
b 0
f 0
wmc 24
lcom 1
cbo 9

10 Methods

Rating   Name   Duplication   Size   Complexity  
B getOrderEachStatus() 0 27 2
B getSalesByMonth() 30 30 2
B getSalesByDay() 30 30 2
B login() 0 25 2
B index() 8 127 5
B changePassword() 0 57 5
A searchNonStockProducts() 0 23 3
A findOrderStatus() 0 13 1
A countNonStockProducts() 0 14 1
A countCustomers() 0 17 1

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;
26
27
use Doctrine\ORM\NoResultException;
28
use Doctrine\ORM\Query\ResultSetMapping;
29
use Doctrine\ORM\QueryBuilder;
30
use Eccube\Application;
31
use Eccube\Common\Constant;
32
use Eccube\Controller\AbstractController;
33
use Eccube\Event\EccubeEvents;
34
use Eccube\Event\EventArgs;
35
use Eccube\Form\Type\Admin\ChangePasswordType;
36
use Eccube\Form\Type\Admin\LoginType;
37
use Eccube\Form\Type\Admin\SearchCustomerType;
38
use Eccube\Form\Type\Admin\SearchOrderType;
39
use Eccube\Form\Type\Admin\SearchProductType;
40
use Symfony\Component\Form\Form;
41
use Symfony\Component\HttpFoundation\Request;
42
43
class AdminController extends AbstractController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
44
{
45 3
    public function login(Application $app, Request $request)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
46
    {
47 3
        if ($app->isGranted('ROLE_ADMIN')) {
48
            return $app->redirect($app->url('admin_homepage'));
49
        }
50
51
        /* @var $form \Symfony\Component\Form\FormInterface */
52 3
        $builder = $app['form.factory']
53 3
            ->createNamedBuilder('', LoginType::class);
54
55 3
        $event = new EventArgs(
56
            array(
57 3
                'builder' => $builder,
58
            ),
59 3
            $request
60
        );
61 3
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ADMIM_LOGIN_INITIALIZE, $event);
62
63 3
        $form = $builder->getForm();
64
65 3
        return $app->render('login.twig', array(
66 3
            'error' => $app['security.last_error']($request),
67 3
            'form' => $form->createView(),
68
        ));
69
    }
70
71 4
    public function index(Application $app, Request $request)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
72
    {
73
        // install.phpのチェック.
74 4
        if (isset($app['config']['eccube_install']) && $app['config']['eccube_install'] == 1) {
75 4
            $file = $app['config']['root_dir'] . '/html/install.php';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
76 4 View Code Duplication
            if (file_exists($file)) {
77
                $message = $app->trans('admin.install.warning', array('installphpPath' => 'html/install.php'));
78
                $app->addWarning($message, 'admin');
79
            }
80 4
            $fileOnRoot = $app['config']['root_dir'] . '/install.php';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
81 4 View Code Duplication
            if (file_exists($fileOnRoot)) {
82 4
                $message = $app->trans('admin.install.warning', array('installphpPath' => 'install.php'));
83 4
                $app->addWarning($message, 'admin');
84
            }
85
        }
86
87
        // 受注マスター検索用フォーム
88 4
        $searchOrderBuilder = $app['form.factory']
89 4
            ->createBuilder(SearchOrderType::class);
90
        // 商品マスター検索用フォーム
91 4
        $searchProductBuilder = $app['form.factory']
92 4
            ->createBuilder(SearchProductType::class);
93
        // 会員マスター検索用フォーム
94 4
        $searchCustomerBuilder = $app['form.factory']
95 4
            ->createBuilder(SearchCustomerType::class);
96
97 4
        $event = new EventArgs(
98
            array(
99 4
                'searchOrderBuilder' => $searchOrderBuilder,
100 4
                'searchProductBuilder' => $searchProductBuilder,
101 4
                'searchCustomerBuilder' => $searchCustomerBuilder,
102
            ),
103 4
            $request
104
        );
105 4
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ADMIM_INDEX_INITIALIZE, $event);
106
107
        // 受注マスター検索用フォーム
108 4
        $searchOrderForm = $searchOrderBuilder->getForm();
109
110
        // 商品マスター検索用フォーム
111 4
        $searchProductForm = $searchProductBuilder->getForm();
112
113
        // 会員マスター検索用フォーム
114 4
        $searchCustomerForm = $searchCustomerBuilder->getForm();
115
116
        /**
117
         * 受注状況.
118
         */
119 4
        $excludes = array();
120 4
        $excludes[] = $app['config']['order_pending'];
121 4
        $excludes[] = $app['config']['order_processing'];
122 4
        $excludes[] = $app['config']['order_cancel'];
123 4
        $excludes[] = $app['config']['order_deliv'];
124
125 4
        $event = new EventArgs(
126
            array(
127 4
                'excludes' => $excludes,
128
            ),
129 4
            $request
130
        );
131 4
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ADMIM_INDEX_ORDER, $event);
132 4
        $excludes = $event->getArgument('excludes');
133
134
        // 受注ステータスごとの受注件数.
135 4
        $Orders = $this->getOrderEachStatus($app['orm.em'], $excludes);
136
        // 受注ステータスの一覧.
137 4
        $OrderStatuses = $this->findOrderStatus($app['orm.em'], $excludes);
138
139
        /**
140
         * 売り上げ状況
141
         */
142 4
        $excludes = array();
143 4
        $excludes[] = $app['config']['order_processing'];
144 4
        $excludes[] = $app['config']['order_cancel'];
145 4
        $excludes[] = $app['config']['order_pending'];
146
147 4
        $event = new EventArgs(
148
            array(
149 4
                'excludes' => $excludes,
150
            ),
151 4
            $request
152
        );
153 4
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ADMIM_INDEX_SALES, $event);
154 4
        $excludes = $event->getArgument('excludes');
155
156
        // 今日の売上/件数
157 4
        $salesToday = $this->getSalesByDay($app['orm.em'], new \DateTime(), $excludes);
158
        // 昨日の売上/件数
159 4
        $salesYesterday = $this->getSalesByDay($app['orm.em'], new \DateTime('-1 day'), $excludes);
160
        // 今月の売上/件数
161 4
        $salesThisMonth = $this->getSalesByMonth($app['orm.em'], new \DateTime(), $excludes);
162
163
        /**
164
         * ショップ状況
165
         */
166
        // 在庫切れ商品数
167 4
        $countNonStockProducts = $this->countNonStockProducts($app['orm.em']);
168
        // 本会員数
169 4
        $countCustomers = $this->countCustomers($app['orm.em']);
170
171 4
        $event = new EventArgs(
172
            array(
173 4
                'Orders' => $Orders,
174 4
                'OrderStatuses' => $OrderStatuses,
175 4
                'salesThisMonth' => $salesThisMonth,
176 4
                'salesToday' => $salesToday,
177 4
                'salesYesterday' => $salesYesterday,
178 4
                'countNonStockProducts' => $countNonStockProducts,
179 4
                'countCustomers' => $countCustomers,
180
            ),
181 4
            $request
182
        );
183 4
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ADMIM_INDEX_COMPLETE, $event);
184
185 4
        return $app->render('index.twig', array(
186 4
            'searchOrderForm' => $searchOrderForm->createView(),
187 4
            'searchProductForm' => $searchProductForm->createView(),
188 4
            'searchCustomerForm' => $searchCustomerForm->createView(),
189 4
            'Orders' => $Orders,
190 4
            'OrderStatuses' => $OrderStatuses,
191 4
            'salesThisMonth' => $salesThisMonth,
192 4
            'salesToday' => $salesToday,
193 4
            'salesYesterday' => $salesYesterday,
194 4
            'countNonStockProducts' => $countNonStockProducts,
195 4
            'countCustomers' => $countCustomers,
196
        ));
197
    }
198
199
    /**
200
     * パスワード変更画面
201
     *
202
     * @param Application $app
203
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
204
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
205
     */
206 3
    public function changePassword(Application $app, Request $request)
207
    {
208 3
        $builder = $app['form.factory']
209 3
            ->createBuilder(ChangePasswordType::class);
210
211 3
        $event = new EventArgs(
212
            array(
213 3
                'builder' => $builder,
214
            ),
215 3
            $request
216
        );
217 3
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ADMIM_CHANGE_PASSWORD_INITIALIZE, $event);
218
219 3
        $form = $builder->getForm();
220 3
        $form->handleRequest($request);
221
222 3
        if ($form->isSubmitted() && $form->isValid()) {
223 1
            $password = $form->get('change_password')->getData();
224
225 1
            $Member = $app->user();
226
227 1
            $dummyMember = clone $Member;
228 1
            $dummyMember->setPassword($password);
229 1
            $salt = $dummyMember->getSalt();
230 1
            if (!isset($salt)) {
231
                $salt = $app['eccube.repository.member']->createSalt(5);
232
                $dummyMember->setSalt($salt);
233
            }
234
235 1
            $encryptPassword = $app['eccube.repository.member']->encryptPassword($dummyMember);
236
237
            $Member
238 1
                ->setPassword($encryptPassword)
239 1
                ->setSalt($salt);
240
241 1
            $status = $app['eccube.repository.member']->save($Member);
242 1
            if ($status) {
243 1
                $event = new EventArgs(
244
                    array(
245 1
                        'form' => $form,
246
                    ),
247 1
                    $request
248
                );
249 1
                $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ADMIN_CHANGE_PASSWORD_COMPLETE, $event);
250
251 1
                $app->addSuccess('admin.change_password.save.complete', 'admin');
252
253 1
                return $app->redirect($app->url('admin_change_password'));
254
            }
255
256
            $app->addError('admin.change_password.save.error', 'admin');
257
        }
258
259 2
        return $app->render('change_password.twig', array(
260 2
            'form' => $form->createView(),
261
        ));
262
    }
263
264
    /**
265
     * 在庫なし商品の検索結果を表示する.
266
     *
267
     * @param Application $app
268
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
269
     * @return \Symfony\Component\HttpFoundation\Response
270
     */
271 2
    public function searchNonStockProducts(Application $app, Request $request)
272
    {
273
        // 商品マスター検索用フォーム
274
        /* @var Form $form */
275 2
        $form = $app['form.factory']
276 2
            ->createBuilder(SearchProductType::class)
277 2
            ->getForm();
278
279 2
        $form->handleRequest($request);
280 2
        if ($form->isSubmitted() && $form->isValid()) {
281
            // 在庫なし商品の検索条件をセッションに付与し, 商品マスタへリダイレクトする.
282 1
            $searchData = array();
283 1
            $searchData['stock_status'] = Constant::DISABLED;
284 1
            $session = $request->getSession();
285 1
            $session->set('eccube.admin.product.search', $searchData);
286
287 1
            return $app->redirect($app->url('admin_product_page', array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
288 1
                'page_no' => 1,
289 1
                'status' => $app['config']['admin_product_stock_status'])));
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 12 spaces, but found 16.
Loading history...
290
        }
291
292 1
        return $app->redirect($app->url('admin_homepage'));
293
    }
294
295 4
    protected function findOrderStatus($em, array $excludes)
296
    {
297
        /* @var $qb QueryBuilder */
298
        $qb = $em
299 4
            ->getRepository('Eccube\Entity\Master\OrderStatus')
300 4
            ->createQueryBuilder('os');
301
302
        return $qb
303 4
            ->where($qb->expr()->notIn('os.id', $excludes))
304 4
            ->orderBy('os.rank', 'ASC')
305 4
            ->getQuery()
306 4
            ->getResult();
307
    }
308
309 4
    protected function getOrderEachStatus($em, array $excludes)
310
    {
311 4
        $sql = 'SELECT
312
                    t1.status as status,
313
                    COUNT(t1.order_id) as count
314
                FROM
315
                    dtb_order t1
316
                WHERE
317
                    t1.del_flg = 0
318
                    AND t1.status NOT IN (:excludes)
319
                GROUP BY
320
                    t1.status
321
                ORDER BY
322
                    t1.status';
323 4
        $rsm = new ResultSetMapping();;
0 ignored issues
show
Coding Style introduced by
It is generally recommended to place each PHP statement on a line by itself.

Let’s take a look at an example:

// Bad
$a = 5; $b = 6; $c = 7;

// Good
$a = 5;
$b = 6;
$c = 7;
Loading history...
324 4
        $rsm->addScalarResult('status', 'status');
325 4
        $rsm->addScalarResult('count', 'count');
326 4
        $query = $em->createNativeQuery($sql, $rsm);
327 4
        $query->setParameters(array(':excludes' => $excludes));
328 4
        $result = $query->getResult();
329 4
        $orderArray = array();
330 4
        foreach ($result as $row) {
331 1
            $orderArray[$row['status']] = $row['count'];
332
        }
333
334 4
        return $orderArray;
335
    }
336
337 4 View Code Duplication
    protected function getSalesByMonth($em, $dateTime, array $excludes)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
338
    {
339
        // concat... for pgsql
340
        // http://stackoverflow.com/questions/1091924/substr-does-not-work-with-datatype-timestamp-in-postgres-8-3
341 4
        $dql = 'SELECT
342
                  SUBSTRING(CONCAT(o.order_date, \'\'), 1, 7) AS order_month,
343
                  SUM(o.payment_total) AS order_amount,
344
                  COUNT(o) AS order_count
345
                FROM
346
                  Eccube\Entity\Order o
347
                WHERE
348
                    o.del_flg = 0
349
                    AND o.OrderStatus NOT IN (:excludes)
350
                    AND SUBSTRING(CONCAT(o.order_date, \'\'), 1, 7) = SUBSTRING(:targetDate, 1, 7)
351
                GROUP BY
352
                  order_month';
353
354
        $q = $em
355 4
            ->createQuery($dql)
356 4
            ->setParameter(':excludes', $excludes)
357 4
            ->setParameter(':targetDate', $dateTime);
358
359 4
        $result = array();
360
        try {
361 4
            $result = $q->getSingleResult();
362 3
        } catch (NoResultException $e) {
363
            // 結果がない場合は空の配列を返す.
364
        }
365 4
        return $result;
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
366
    }
367
368 4 View Code Duplication
    protected function getSalesByDay($em, $dateTime, array $excludes)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
369
    {
370
        // concat... for pgsql
371
        // http://stackoverflow.com/questions/1091924/substr-does-not-work-with-datatype-timestamp-in-postgres-8-3
372 4
        $dql = 'SELECT
373
                  SUBSTRING(CONCAT(o.order_date, \'\'), 1, 10) AS order_day,
374
                  SUM(o.payment_total) AS order_amount,
375
                  COUNT(o) AS order_count
376
                FROM
377
                  Eccube\Entity\Order o
378
                WHERE
379
                    o.del_flg = 0
380
                    AND o.OrderStatus NOT IN (:excludes)
381
                    AND SUBSTRING(CONCAT(o.order_date, \'\'), 1, 10) = SUBSTRING(:targetDate, 1, 10)
382
                GROUP BY
383
                  order_day';
384
385
        $q = $em
386 4
            ->createQuery($dql)
387 4
            ->setParameter(':excludes', $excludes)
388 4
            ->setParameter(':targetDate', $dateTime);
389
390 4
        $result = array();
391
        try {
392 4
            $result = $q->getSingleResult();
393 3
        } catch (NoResultException $e) {
394
            // 結果がない場合は空の配列を返す.
395
        }
396 4
        return $result;
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
397
    }
398
399 4
    protected function countNonStockProducts($em)
400
    {
401
        /** @var $qb \Doctrine\ORM\QueryBuilder */
402 4
        $qb = $em->getRepository('Eccube\Entity\Product')
403 4
            ->createQueryBuilder('p')
404 4
            ->select('count(DISTINCT p.id)')
405 4
            ->innerJoin('p.ProductClasses', 'pc')
406 4
            ->where('pc.stock_unlimited = :StockUnlimited AND pc.stock = 0')
407 4
            ->setParameter('StockUnlimited', Constant::DISABLED);
408
409
        return $qb
410 4
            ->getQuery()
411 4
            ->getSingleScalarResult();
412
    }
413
414 4
    protected function countCustomers($em)
415
    {
416
        $Status = $em
417 4
            ->getRepository('Eccube\Entity\Master\CustomerStatus')
418 4
            ->find(2);
419
420
        /** @var $qb \Doctrine\ORM\QueryBuilder */
421 4
        $qb = $em->getRepository('Eccube\Entity\Customer')
422 4
            ->createQueryBuilder('c')
423 4
            ->select('count(c.id)')
424 4
            ->where('c.Status = :Status')
425 4
            ->setParameter('Status', $Status);
426
427
        return $qb
428 4
            ->getQuery()
429 4
            ->getSingleScalarResult();
430
    }
431
}
432