Completed
Push — master ( f67c79...748c93 )
by Yangsin
182:40 queued 176:37
created

AdminController   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 389
Duplicated Lines 17.48 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 92.78%

Importance

Changes 0
Metric Value
dl 68
loc 389
ccs 167
cts 180
cp 0.9278
rs 10
c 0
b 0
f 0
wmc 24
lcom 1
cbo 7

10 Methods

Rating   Name   Duplication   Size   Complexity  
B login() 0 25 2
B index() 8 127 5
B changePassword() 0 57 5
B searchNonStockProducts() 0 25 3
A findOrderStatus() 0 11 1
B getOrderEachStatus() 0 27 2
B getSalesByMonth() 30 30 2
B getSalesByDay() 30 30 2
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 Eccube\Application;
30
use Eccube\Common\Constant;
31
use Eccube\Controller\AbstractController;
32
use Eccube\Event\EccubeEvents;
33
use Eccube\Event\EventArgs;
34
use Symfony\Component\HttpFoundation\Request;
35
36
class AdminController extends AbstractController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
37
{
38 6
    public function login(Application $app, Request $request)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
39
    {
40 6
        if ($app->isGranted('ROLE_ADMIN')) {
41
            return $app->redirect($app->url('admin_homepage'));
42
        }
43
44
        /* @var $form \Symfony\Component\Form\FormInterface */
45 6
        $builder = $app['form.factory']
46 6
            ->createNamedBuilder('', 'admin_login');
47
48 6
        $event = new EventArgs(
49
            array(
50 6
                'builder' => $builder,
51
            ),
52
            $request
53
        );
54 6
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ADMIM_LOGIN_INITIALIZE, $event);
55
56 6
        $form = $builder->getForm();
57
58 6
        return $app->render('login.twig', array(
59 6
            'error' => $app['security.last_error']($request),
60 6
            'form' => $form->createView(),
61
        ));
62
    }
63
64 3
    public function index(Application $app, Request $request)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
65
    {
66
        // install.phpのチェック.
67 3
        if (isset($app['config']['eccube_install']) && $app['config']['eccube_install'] == 1) {
68 3
            $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...
69 3 View Code Duplication
            if (file_exists($file)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
70 3
                $message = $app->trans('admin.install.warning', array('installphpPath' => 'html/install.php'));
71 3
                $app->addWarning($message, 'admin');
72
            }
73 3
            $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...
74 3 View Code Duplication
            if (file_exists($fileOnRoot)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
75
                $message = $app->trans('admin.install.warning', array('installphpPath' => 'install.php'));
76
                $app->addWarning($message, 'admin');
77
            }
78
        }
79
80
        // 受注マスター検索用フォーム
81 3
        $searchOrderBuilder = $app['form.factory']
82 3
            ->createBuilder('admin_search_order');
83
        // 商品マスター検索用フォーム
84 3
        $searchProductBuilder = $app['form.factory']
85 3
            ->createBuilder('admin_search_product');
86
        // 会員マスター検索用フォーム
87 3
        $searchCustomerBuilder = $app['form.factory']
88 3
            ->createBuilder('admin_search_customer');
89
90 3
        $event = new EventArgs(
91
            array(
92 3
                'searchOrderBuilder' => $searchOrderBuilder,
93 3
                'searchProductBuilder' => $searchProductBuilder,
94 3
                'searchCustomerBuilder' => $searchCustomerBuilder,
95
            ),
96
            $request
97
        );
98 3
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ADMIM_INDEX_INITIALIZE, $event);
99
100
        // 受注マスター検索用フォーム
101 3
        $searchOrderForm = $searchOrderBuilder->getForm();
102
103
        // 商品マスター検索用フォーム
104 3
        $searchProductForm = $searchProductBuilder->getForm();
105
106
        // 会員マスター検索用フォーム
107 3
        $searchCustomerForm = $searchCustomerBuilder->getForm();
108
109
        /**
110
         * 受注状況.
111
         */
112 3
        $excludes = array();
113 3
        $excludes[] = $app['config']['order_pending'];
114 3
        $excludes[] = $app['config']['order_processing'];
115 3
        $excludes[] = $app['config']['order_cancel'];
116 3
        $excludes[] = $app['config']['order_deliv'];
117
118 3
        $event = new EventArgs(
119
            array(
120 3
                'excludes' => $excludes,
121
            ),
122
            $request
123
        );
124 3
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ADMIM_INDEX_ORDER, $event);
125 3
        $excludes = $event->getArgument('excludes');
126
127
        // 受注ステータスごとの受注件数.
128 3
        $Orders = $this->getOrderEachStatus($app['orm.em'], $excludes);
129
        // 受注ステータスの一覧.
130 3
        $OrderStatuses = $this->findOrderStatus($app['orm.em'], $excludes);
131
132
        /**
133
         * 売り上げ状況
134
         */
135 3
        $excludes = array();
136 3
        $excludes[] = $app['config']['order_processing'];
137 3
        $excludes[] = $app['config']['order_cancel'];
138 3
        $excludes[] = $app['config']['order_pending'];
139
140 3
        $event = new EventArgs(
141
            array(
142 3
                'excludes' => $excludes,
143
            ),
144
            $request
145
        );
146 3
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ADMIM_INDEX_SALES, $event);
147 3
        $excludes = $event->getArgument('excludes');
148
149
        // 今日の売上/件数
150 3
        $salesToday = $this->getSalesByDay($app['orm.em'], new \DateTime(), $excludes);
151
        // 昨日の売上/件数
152 3
        $salesYesterday = $this->getSalesByDay($app['orm.em'], new \DateTime('-1 day'), $excludes);
153
        // 今月の売上/件数
154 3
        $salesThisMonth = $this->getSalesByMonth($app['orm.em'], new \DateTime(), $excludes);
155
156
        /**
157
         * ショップ状況
158
         */
159
        // 在庫切れ商品数
160 3
        $countNonStockProducts = $this->countNonStockProducts($app['orm.em']);
161
        // 本会員数
162 3
        $countCustomers = $this->countCustomers($app['orm.em']);
163
164 3
        $event = new EventArgs(
165
            array(
166 3
                'Orders' => $Orders,
167 3
                'OrderStatuses' => $OrderStatuses,
168 3
                'salesThisMonth' => $salesThisMonth,
169 3
                'salesToday' => $salesToday,
170 3
                'salesYesterday' => $salesYesterday,
171 3
                'countNonStockProducts' => $countNonStockProducts,
172 3
                'countCustomers' => $countCustomers,
173
            ),
174
            $request
175
        );
176 3
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ADMIM_INDEX_COMPLETE, $event);
177
178 3
        return $app->render('index.twig', array(
179 3
            'searchOrderForm' => $searchOrderForm->createView(),
180 3
            'searchProductForm' => $searchProductForm->createView(),
181 3
            'searchCustomerForm' => $searchCustomerForm->createView(),
182 3
            'Orders' => $Orders,
183 3
            'OrderStatuses' => $OrderStatuses,
184 3
            'salesThisMonth' => $salesThisMonth,
185 3
            'salesToday' => $salesToday,
186 3
            'salesYesterday' => $salesYesterday,
187 3
            'countNonStockProducts' => $countNonStockProducts,
188 3
            'countCustomers' => $countCustomers,
189
        ));
190
    }
191
192
    /**
193
     * パスワード変更画面
194
     *
195
     * @param Application $app
196
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
197
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
198
     */
199 3
    public function changePassword(Application $app, Request $request)
200
    {
201 3
        $builder = $app['form.factory']
202 3
            ->createBuilder('admin_change_password');
203
204 3
        $event = new EventArgs(
205
            array(
206 3
                'builder' => $builder,
207
            ),
208
            $request
209
        );
210 3
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ADMIM_CHANGE_PASSWORD_INITIALIZE, $event);
211
212 3
        $form = $builder->getForm();
213 3
        $form->handleRequest($request);
214
215 3
        if ($form->isSubmitted() && $form->isValid()) {
216 1
            $password = $form->get('change_password')->getData();
217
218 1
            $Member = $app->user();
219
220 1
            $dummyMember = clone $Member;
221 1
            $dummyMember->setPassword($password);
222 1
            $salt = $dummyMember->getSalt();
223 1
            if (!isset($salt)) {
224
                $salt = $app['eccube.repository.member']->createSalt(5);
225
                $dummyMember->setSalt($salt);
226
            }
227
228 1
            $encryptPassword = $app['eccube.repository.member']->encryptPassword($dummyMember);
229
230
            $Member
231 1
                ->setPassword($encryptPassword)
232 1
                ->setSalt($salt);
233
234 1
            $status = $app['eccube.repository.member']->save($Member);
235 1
            if ($status) {
236 1
                $event = new EventArgs(
237
                    array(
238 1
                        'form' => $form,
239
                    ),
240
                    $request
241
                );
242 1
                $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ADMIN_CHANGE_PASSWORD_COMPLETE, $event);
243
244 1
                $app->addSuccess('admin.change_password.save.complete', 'admin');
245
246 1
                return $app->redirect($app->url('admin_change_password'));
247
            }
248
249
            $app->addError('admin.change_password.save.error', 'admin');
250
        }
251
252 2
        return $app->render('change_password.twig', array(
253 2
            'form' => $form->createView(),
254
        ));
255
    }
256
257
    /**
258
     * 在庫なし商品の検索結果を表示する.
259
     *
260
     * @param Application $app
261
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
262
     * @return \Symfony\Component\HttpFoundation\Response
263
     */
264 2
    public function searchNonStockProducts(Application $app, Request $request)
265
    {
266
        // 商品マスター検索用フォーム
267 2
        $form = $app['form.factory']
268 2
            ->createBuilder('admin_search_product')
269 2
            ->getForm();
270
271 2
        if ('POST' === $request->getMethod()) {
272 2
            $form->handleRequest($request);
273
274 2
            if ($form->isValid()) {
275
                // 在庫なし商品の検索条件をセッションに付与し, 商品マスタへリダイレクトする.
276
                $searchData = array();
277
                $searchData['stock_status'] = Constant::DISABLED;
278
                $session = $request->getSession();
279
                $session->set('eccube.admin.product.search', $searchData);
280
281
                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...
282
                    'page_no' => 1,
283
                    '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 16 spaces, but found 20.
Loading history...
284
            }
285
        }
286
287 2
        return $app->redirect($app->url('admin_homepage'));
288
    }
289
290 3
    protected function findOrderStatus($em, array $excludes)
291
    {
292
        $qb = $em
293 3
            ->getRepository('Eccube\Entity\Master\OrderStatus')
294 3
            ->createQueryBuilder('os');
295
296
        return $qb
297 3
            ->where($qb->expr()->notIn('os.id', $excludes))
298 3
            ->getQuery()
299 3
            ->getResult();
300
    }
301
302 3
    protected function getOrderEachStatus($em, array $excludes)
303
    {
304
        $sql = 'SELECT
305
                    t1.status as status,
306
                    COUNT(t1.order_id) as count
307
                FROM
308
                    dtb_order t1
309
                WHERE
310
                    t1.del_flg = 0
311
                    AND t1.status NOT IN (:excludes)
312
                GROUP BY
313
                    t1.status
314
                ORDER BY
315 3
                    t1.status';
316 3
        $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...
317 3
        $rsm->addScalarResult('status', 'status');
318 3
        $rsm->addScalarResult('count', 'count');
319 3
        $query = $em->createNativeQuery($sql, $rsm);
320 3
        $query->setParameters(array(':excludes' => $excludes));
321 3
        $result = $query->getResult();
322 3
        $orderArray = array();
323 3
        foreach ($result as $row) {
324 3
            $orderArray[$row['status']] = $row['count'];
325
        }
326
327 3
        return $orderArray;
328
    }
329
330 3 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...
331
    {
332
        // concat... for pgsql
333
        // http://stackoverflow.com/questions/1091924/substr-does-not-work-with-datatype-timestamp-in-postgres-8-3
334
        $dql = 'SELECT
335
                  SUBSTRING(CONCAT(o.order_date, \'\'), 1, 7) AS order_month,
336
                  SUM(o.payment_total) AS order_amount,
337
                  COUNT(o) AS order_count
338
                FROM
339
                  Eccube\Entity\Order o
340
                WHERE
341
                    o.del_flg = 0
342
                    AND o.OrderStatus NOT IN (:excludes)
343
                    AND SUBSTRING(CONCAT(o.order_date, \'\'), 1, 7) = SUBSTRING(:targetDate, 1, 7)
344
                GROUP BY
345 3
                  order_month';
346
347
        $q = $em
348 3
            ->createQuery($dql)
349 3
            ->setParameter(':excludes', $excludes)
350 3
            ->setParameter(':targetDate', $dateTime);
351
352 3
        $result = array();
353
        try {
354 3
            $result = $q->getSingleResult();
355 2
        } catch (NoResultException $e) {
356
            // 結果がない場合は空の配列を返す.
357
        }
358 3
        return $result;
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
359
    }
360
361 3 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...
362
    {
363
        // concat... for pgsql
364
        // http://stackoverflow.com/questions/1091924/substr-does-not-work-with-datatype-timestamp-in-postgres-8-3
365
        $dql = 'SELECT
366
                  SUBSTRING(CONCAT(o.order_date, \'\'), 1, 10) AS order_day,
367
                  SUM(o.payment_total) AS order_amount,
368
                  COUNT(o) AS order_count
369
                FROM
370
                  Eccube\Entity\Order o
371
                WHERE
372
                    o.del_flg = 0
373
                    AND o.OrderStatus NOT IN (:excludes)
374
                    AND SUBSTRING(CONCAT(o.order_date, \'\'), 1, 10) = SUBSTRING(:targetDate, 1, 10)
375
                GROUP BY
376 3
                  order_day';
377
378
        $q = $em
379 3
            ->createQuery($dql)
380 3
            ->setParameter(':excludes', $excludes)
381 3
            ->setParameter(':targetDate', $dateTime);
382
383 3
        $result = array();
384
        try {
385 3
            $result = $q->getSingleResult();
386 2
        } catch (NoResultException $e) {
387
            // 結果がない場合は空の配列を返す.
388
        }
389 3
        return $result;
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
390
    }
391
392 3
    protected function countNonStockProducts($em)
393
    {
394
        /** @var $qb \Doctrine\ORM\QueryBuilder */
395 3
        $qb = $em->getRepository('Eccube\Entity\Product')
396 3
            ->createQueryBuilder('p')
397 3
            ->select('count(p.id)')
398 3
            ->innerJoin('p.ProductClasses', 'pc')
399 3
            ->where('pc.stock_unlimited = :StockUnlimited AND pc.stock = 0')
400 3
            ->setParameter('StockUnlimited', Constant::DISABLED);
401
402
        return $qb
403 3
            ->getQuery()
404 3
            ->getSingleScalarResult();
405
    }
406
407 3
    protected function countCustomers($em)
408
    {
409
        $Status = $em
410 3
            ->getRepository('Eccube\Entity\Master\CustomerStatus')
411 3
            ->find(2);
412
413
        /** @var $qb \Doctrine\ORM\QueryBuilder */
414 3
        $qb = $em->getRepository('Eccube\Entity\Customer')
415 3
            ->createQueryBuilder('c')
416 3
            ->select('count(c.id)')
417 3
            ->where('c.Status = :Status')
418 3
            ->setParameter('Status', $Status);
419
420
        return $qb
421 3
            ->getQuery()
422 3
            ->getSingleScalarResult();
423
    }
424
}