Failed Conditions
Push — experimental/3.1 ( 3d2ede...2919b9 )
by Yangsin
28:59
created

AdminController   B

Complexity

Total Complexity 23

Size/Duplication

Total Lines 432
Duplicated Lines 15.74 %

Coupling/Cohesion

Components 1
Dependencies 16

Test Coverage

Coverage 97.79%

Importance

Changes 0
Metric Value
dl 68
loc 432
ccs 177
cts 181
cp 0.9779
rs 8.4614
c 0
b 0
f 0
wmc 23
lcom 1
cbo 16

10 Methods

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