Failed Conditions
Pull Request — experimental/3.1 (#2522)
by chihiro
38:22
created

OrderController::exportShipping()   B

Complexity

Conditions 6
Paths 1

Size

Total Lines 83
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
eloc 42
nc 1
nop 2
dl 0
loc 83
ccs 0
cts 42
cp 0
crap 42
rs 8.3634
c 0
b 0
f 0

How to fix   Long Method   

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\Admin\Order;
26
27
use Doctrine\ORM\EntityManager;
28
use Eccube\Annotation\Inject;
29
use Eccube\Annotation\Component;
30
use Eccube\Application;
31
use Eccube\Common\Constant;
32
use Eccube\Controller\AbstractController;
33
use Eccube\Entity\Master\CsvType;
34
use Eccube\Entity\Order;
35
use Eccube\Event\EccubeEvents;
36
use Eccube\Event\EventArgs;
37
use Eccube\Form\Type\Admin\SearchOrderType;
38
use Eccube\Repository\CustomerRepository;
39
use Eccube\Repository\Master\DispRepository;
40
use Eccube\Repository\Master\OrderStatusRepository;
41
use Eccube\Repository\Master\PageMaxRepository;
42
use Eccube\Repository\Master\SexRepository;
43
use Eccube\Repository\OrderRepository;
44
use Eccube\Repository\PaymentRepository;
45
use Eccube\Service\CsvExportService;
46
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
47
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
48
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
49
use Symfony\Component\EventDispatcher\EventDispatcher;
50
use Symfony\Component\Form\FormFactory;
51
use Symfony\Component\HttpFoundation\Request;
52
use Symfony\Component\HttpFoundation\StreamedResponse;
53
54
/**
55
 * @Component
56
 * @Route(service=OrderController::class)
57
 */
58
class OrderController extends AbstractController
59
{
60
    /**
61
     * @Inject(CsvExportService::class)
62
     * @var CsvExportService
63
     */
64
    protected $csvExportService;
65
66
    /**
67
     * @Inject(CustomerRepository::class)
68
     * @var CustomerRepository
69
     */
70
    protected $customerRepository;
71
72
    /**
73
     * @Inject("orm.em")
74
     * @var EntityManager
75
     */
76
    protected $entityManager;
77
78
    /**
79
     * @Inject(PaymentRepository::class)
80
     * @var PaymentRepository
81
     */
82
    protected $paymentRepository;
83
84
    /**
85
     * @Inject(SexRepository::class)
86
     * @var SexRepository
87
     */
88
    protected $sexRepository;
89
90
    /**
91
     * @Inject(OrderStatusRepository::class)
92
     * @var OrderStatusRepository
93
     */
94
    protected $orderStatusRepository;
95
96
    /**
97
     * @Inject("config")
98
     * @var array
99
     */
100
    protected $appConfig;
101
102
    /**
103
     * @Inject(PageMaxRepository::class)
104
     * @var PageMaxRepository
105
     */
106
    protected $pageMaxRepository;
107
108
    /**
109
     * @Inject(DispRepository::class)
110
     * @var DispRepository
111
     */
112
    protected $dispRepository;
113
114
    /**
115
     * @Inject("eccube.event.dispatcher")
116
     * @var EventDispatcher
117
     */
118
    protected $eventDispatcher;
119
120
    /**
121
     * @Inject("form.factory")
122
     * @var FormFactory
123
     */
124
    protected $formFactory;
125
126
    /**
127
     * @Inject(OrderRepository::class)
128
     * @var OrderRepository
129
     */
130
    protected $orderRepository;
131
132
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$page_no" missing
Loading history...
133
     * @Route("/{_admin}/order", name="admin_order")
134
     * @Route("/{_admin}/order/page/{page_no}", requirements={"page_no" = "\d+"}, name="admin_order_page")
135
     * @Template("Order/index.twig")
136
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
137 6
    public function index(Application $app, Request $request, $page_no = null)
138
    {
139
140 6
        $session = $request->getSession();
141
142 6
        $builder = $this->formFactory
143 6
            ->createBuilder(SearchOrderType::class);
144
145 6
        $event = new EventArgs(
146
            array(
147 6
                'builder' => $builder,
148
            ),
149 6
            $request
150
        );
151 6
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_INDEX_INITIALIZE, $event);
152
153 6
        $searchForm = $builder->getForm();
154
155 6
        $pagination = array();
156
157 6
        $disps = $this->dispRepository->findAll();
158 6
        $pageMaxis = $this->pageMaxRepository->findAll();
159 6
        $page_count = $this->appConfig['default_page_count'];
160 6
        $page_status = null;
161 6
        $active = false;
162
163 6
        if ('POST' === $request->getMethod()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
164
165 5
            $searchForm->handleRequest($request);
166
167 5 View Code Duplication
            if ($searchForm->isValid()) {
168 5
                $searchData = $searchForm->getData();
169
170
                // paginator
171 5
                $qb = $this->orderRepository->getQueryBuilderBySearchDataForAdmin($searchData);
172
173 5
                $event = new EventArgs(
174
                    array(
175 5
                        'form' => $searchForm,
176 5
                        'qb' => $qb,
177
                    ),
178 5
                    $request
179
                );
180 5
                $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_INDEX_SEARCH, $event);
181
182 5
                $page_no = 1;
183 5
                $pagination = $app['paginator']()->paginate(
184 5
                    $qb,
185 5
                    $page_no,
186 5
                    $page_count
187
                );
188
189
                // sessionのデータ保持
190 5
                $session->set('eccube.admin.order.search', $searchData);
191 5
                $session->set('eccube.admin.order.search.page_no', $page_no);
192
            }
193
        } else {
194 2
            if (is_null($page_no) && $request->get('resume') != Constant::ENABLED) {
195
                // sessionを削除
196 1
                $session->remove('eccube.admin.order.search');
197 1
                $session->remove('eccube.admin.order.search.page_no');
198
            } else {
199
                // pagingなどの処理
200 1
                $searchData = $session->get('eccube.admin.order.search');
201 1
                if (is_null($page_no)) {
202
                    $page_no = intval($session->get('eccube.admin.order.search.page_no'));
203
                } else {
204 1
                    $session->set('eccube.admin.order.search.page_no', $page_no);
205
                }
206
207 1
                if (!is_null($searchData)) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
208
209
                    // 公開ステータス
210 1
                    $status = $request->get('status');
211 1 View Code Duplication
                    if (!empty($status)) {
212
                        if ($status != $this->appConfig['admin_product_stock_status']) {
213
                            $searchData['status']->clear();
214
                            $searchData['status']->add($status);
215
                        } else {
216
                            $searchData['stock_status'] = $this->appConfig['disabled'];
217
                        }
218
                        $page_status = $status;
219
                    }
220
                    // 表示件数
221 1
                    $pcount = $request->get('page_count');
222
223 1
                    $page_count = empty($pcount) ? $page_count : $pcount;
224
225 1
                    $qb = $this->orderRepository->getQueryBuilderBySearchDataForAdmin($searchData);
226
227 1
                    $event = new EventArgs(
228
                        array(
229 1
                            'form' => $searchForm,
230 1
                            'qb' => $qb,
231
                        ),
232 1
                        $request
233
                    );
234 1
                    $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_INDEX_SEARCH, $event);
235
236 1
                    $pagination = $app['paginator']()->paginate(
237 1
                        $qb,
238 1
                        $page_no,
239 1
                        $page_count
240
                    );
241
242
                    // セッションから検索条件を復元
243 1 View Code Duplication
                    if (!empty($searchData['status'])) {
244 1
                        $searchData['status'] = $this->orderStatusRepository->find($searchData['status']);
245
                    }
246 1 View Code Duplication
                    if (count($searchData['multi_status']) > 0) {
247
                        $statusIds = array();
248
                        foreach ($searchData['multi_status'] as $Status) {
249
                            $statusIds[] = $Status->getId();
250
                        }
251
                        $searchData['multi_status'] = $this->orderStatusRepository->findBy(array('id' => $statusIds));
252
                    }
253 1
                    if (count($searchData['sex']) > 0) {
254 1
                        $sex_ids = array();
255 1
                        foreach ($searchData['sex'] as $Sex) {
256 1
                            $sex_ids[] = $Sex->getId();
257
                        }
258 1
                        $searchData['sex'] = $this->sexRepository->findBy(array('id' => $sex_ids));
259
                    }
260 1
                    if (count($searchData['payment']) > 0) {
261 1
                        $payment_ids = array();
262 1
                        foreach ($searchData['payment'] as $Payment) {
263 1
                            $payment_ids[] = $Payment->getId();
264
                        }
265 1
                        $searchData['payment'] = $this->paymentRepository->findBy(array('id' => $payment_ids));
266
                    }
267 1
                    $searchForm->setData($searchData);
268
                }
269
            }
270
        }
271
272
        return [
273 6
            'searchForm' => $searchForm->createView(),
274 6
            'pagination' => $pagination,
275 6
            'disps' => $disps,
276 6
            'pageMaxis' => $pageMaxis,
277 6
            'page_no' => $page_no,
278 6
            'page_status' => $page_status,
279 6
            'page_count' => $page_count,
280 6
            'active' => $active,
281
        ];
282
    }
283
284
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$id" missing
Loading history...
285
     * @Method("DELETE")
286
     * @Route("/{_admin}/order/{id}/delete", requirements={"id" = "\d+"}, name="admin_order_delete")
287
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
288 1
    public function delete(Application $app, Request $request, $id)
289
    {
290 1
        $this->isTokenValid($app);
291 1
        $session = $request->getSession();
292 1
        $page_no = intval($session->get('eccube.admin.order.search.page_no'));
293 1
        $page_no = $page_no ? $page_no : Constant::ENABLED;
294
295 1
        $Order = $this->orderRepository
296 1
            ->find($id);
297
298 1
        if (!$Order) {
299
            $app->deleteMessage();
300
            return $app->redirect($app->url('admin_order_page', array('page_no' => $page_no)).'?resume='.Constant::ENABLED);
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
301
        }
302
303 1
        log_info('受注削除開始', array($Order->getId()));
304
305
        // 出荷に紐付いている明細がある場合は削除できない.
306
        $hasShipping = $Order->getItems()->exists(function ($k, $v) {
307 1
            return false === is_null($v->getShipping());
308 1
        });
309 1
        if ($hasShipping) {
310
            log_info('受注削除失敗', [$Order->getId()]);
311
            $message = $app->trans('admin.delete.failed.foreign_key', ['%name%' => '受注']);
312
            $app->addError($message, 'admin');
313
314
            return $app->redirect($app->url('admin_order_page', array('page_no' => $page_no)).'?resume='.Constant::ENABLED);
315
        }
316
317 1
        $Customer = $Order->getCustomer();
318 1
        $OrderStatusId = $Order->getOrderStatus()->getId();
319
320 1
        $this->entityManager->remove($Order);
321 1
        $this->entityManager->flush();
322
323 1
        if ($Customer) {
324
            // 会員の場合、購入回数、購入金額などを更新
325 1
            $this->customerRepository->updateBuyData($app, $Customer, $OrderStatusId);
326
        }
327
328 1
        $event = new EventArgs(
329
            array(
330 1
                'Order' => $Order,
331 1
                'Customer' => $Customer,
332
            ),
333 1
            $request
334
        );
335 1
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_DELETE_COMPLETE, $event);
336
337 1
        $app->addSuccess('admin.order.delete.complete', 'admin');
338
339 1
        log_info('受注削除完了', array($Order->getId()));
340
341 1
        return $app->redirect($app->url('admin_order_page', array('page_no' => $page_no)).'?resume='.Constant::ENABLED);
342
    }
343
344
345
    /**
346
     * 受注CSVの出力.
347
     *
348
     * @Route("/order/export/order", name="admin_order_export_order")
349
     *
350
     * @param Application $app
351
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
352
     * @return StreamedResponse
353
     */
354
    public function exportOrder(Application $app, Request $request)
355
    {
356
357
        // タイムアウトを無効にする.
358
        set_time_limit(0);
359
360
        // sql loggerを無効にする.
361
        $em = $this->entityManager;
362
        $em->getConfiguration()->setSQLLogger(null);
363
364
        $response = new StreamedResponse();
365
        $response->setCallback(function () use ($app, $request) {
366
367
            // CSV種別を元に初期化.
368
            $this->csvExportService->initCsvType(CsvType::CSV_TYPE_ORDER);
369
370
            // ヘッダ行の出力.
371
            $this->csvExportService->exportHeader();
372
373
            // 受注データ検索用のクエリビルダを取得.
374
            $qb = $this->csvExportService
375
                ->getOrderQueryBuilder($request);
376
377
            // データ行の出力.
378
            $this->csvExportService->setExportQueryBuilder($qb);
379 View Code Duplication
            $this->csvExportService->exportData(function ($entity, $csvService) use ($app, $request) {
380
381
                $Csvs = $csvService->getCsvs();
382
383
                $Order = $entity;
384
                $OrderDetails = $Order->getOrderDetails();
385
386
                foreach ($OrderDetails as $OrderDetail) {
387
                    $ExportCsvRow = new \Eccube\Entity\ExportCsvRow();
388
389
                    // CSV出力項目と合致するデータを取得.
390
                    foreach ($Csvs as $Csv) {
391
                        // 受注データを検索.
392
                        $ExportCsvRow->setData($csvService->getData($Csv, $Order));
393
                        if ($ExportCsvRow->isDataNull()) {
394
                            // 受注データにない場合は, 受注明細を検索.
395
                            $ExportCsvRow->setData($csvService->getData($Csv, $OrderDetail));
396
                        }
397
398
                        $event = new EventArgs(
399
                            array(
400
                                'csvService' => $csvService,
401
                                'Csv' => $Csv,
402
                                'OrderDetail' => $OrderDetail,
403
                                'ExportCsvRow' => $ExportCsvRow,
404
                            ),
405
                            $request
406
                        );
407
                        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_CSV_EXPORT_ORDER, $event);
408
409
                        $ExportCsvRow->pushData();
410
                    }
411
412
                    //$row[] = number_format(memory_get_usage(true));
413
                    // 出力.
414
                    $csvService->fputcsv($ExportCsvRow->getRow());
415
                }
416
            });
417
        });
418
419
        $now = new \DateTime();
420
        $filename = 'order_' . $now->format('YmdHis') . '.csv';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
421
        $response->headers->set('Content-Type', 'application/octet-stream');
422
        $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...
423
        $response->send();
424
425
        log_info('受注CSV出力ファイル名', array($filename));
426
427
        return $response;
428
    }
429
430
    /**
431
     * 配送CSVの出力.
432
     *
433
     * @Route("/order/export/shipping", name="admin_order_export_shipping")
434
     *
435
     * @param Application $app
436
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
437
     * @return StreamedResponse
438
     */
439
    public function exportShipping(Application $app, Request $request)
440
    {
441
        // タイムアウトを無効にする.
442
        set_time_limit(0);
443
444
        // sql loggerを無効にする.
445
        $em = $this->entityManager;
446
        $em->getConfiguration()->setSQLLogger(null);
447
448
        $response = new StreamedResponse();
449
        $response->setCallback(function () use ($app, $request) {
450
451
            // CSV種別を元に初期化.
452
            $this->csvExportService->initCsvType(CsvType::CSV_TYPE_SHIPPING);
453
454
            // ヘッダ行の出力.
455
            $this->csvExportService->exportHeader();
456
457
            // 受注データ検索用のクエリビルダを取得.
458
            $qb = $this->csvExportService
459
                ->getOrderQueryBuilder($request);
460
461
            // データ行の出力.
462
            $this->csvExportService->setExportQueryBuilder($qb);
463
            $this->csvExportService->exportData(function ($entity, $csvService) use ($app, $request) {
464
465
                $Csvs = $csvService->getCsvs();
466
467
                /** @var $Order \Eccube\Entity\Order */
468
                $Order = $entity;
469
                /** @var $Shippings \Eccube\Entity\Shipping[] */
470
                $Shippings = $Order->getShippings();
471
472
                foreach ($Shippings as $Shipping) {
473
                    /** @var $ShipmentItems \Eccube\Entity\ShipmentItem */
474
                    $ShipmentItems = $Shipping->getShipmentItems();
475
                    foreach ($ShipmentItems as $ShipmentItem) {
476
                        $ExportCsvRow = new \Eccube\Entity\ExportCsvRow();
477
478
                        // CSV出力項目と合致するデータを取得.
479
                        foreach ($Csvs as $Csv) {
480
                            // 受注データを検索.
481
                            $ExportCsvRow->setData($csvService->getData($Csv, $Order));
482
                            if ($ExportCsvRow->isDataNull()) {
483
                                // 配送情報を検索.
484
                                $ExportCsvRow->setData($csvService->getData($Csv, $Shipping));
485
                            }
486
                            if ($ExportCsvRow->isDataNull()) {
487
                                // 配送商品を検索.
488
                                $ExportCsvRow->setData($csvService->getData($Csv, $ShipmentItem));
489
                            }
490
491
                            $event = new EventArgs(
492
                                array(
493
                                    'csvService' => $csvService,
494
                                    'Csv' => $Csv,
495
                                    'ShipmentItem' => $ShipmentItem,
496
                                    'ExportCsvRow' => $ExportCsvRow,
497
                                ),
498
                                $request
499
                            );
500
                            $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_CSV_EXPORT_SHIPPING, $event);
501
502
                            $ExportCsvRow->pushData();
503
                        }
504
                        //$row[] = number_format(memory_get_usage(true));
505
                        // 出力.
506
                        $csvService->fputcsv($ExportCsvRow->getRow());
507
                    }
508
                }
509
            });
510
        });
511
512
        $now = new \DateTime();
513
        $filename = 'shipping_' . $now->format('YmdHis') . '.csv';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
514
        $response->headers->set('Content-Type', 'application/octet-stream');
515
        $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...
516
        $response->send();
517
518
        log_info('配送CSV出力ファイル名', array($filename));
519
520
        return $response;
521
    }
522
}
523