Completed
Pull Request — master (#1922)
by chihiro
39:42
created

OrderController::exportOrder()   B

Complexity

Conditions 4
Paths 1

Size

Total Lines 64
Code Lines 30

Duplication

Lines 27
Ratio 42.19 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 30
nc 1
nop 2
dl 27
loc 64
ccs 0
cts 30
cp 0
crap 20
rs 8.8725
c 1
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 Eccube\Application;
28
use Eccube\Common\Constant;
29
use Eccube\Controller\AbstractController;
30
use Eccube\Entity\Master\CsvType;
31
use Eccube\Event\EccubeEvents;
32
use Eccube\Event\EventArgs;
33
use Symfony\Component\HttpFoundation\Request;
34
use Symfony\Component\HttpFoundation\StreamedResponse;
35
36
class OrderController extends AbstractController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
37
{
38
39 6
    public function index(Application $app, Request $request, $page_no = null)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
40
    {
41
42 6
        $session = $request->getSession();
43
44 6
        $builder = $app['form.factory']
45 6
            ->createBuilder('admin_search_order');
46
47 6
        $event = new EventArgs(
48
            array(
49 6
                'builder' => $builder,
50
            ),
51
            $request
52
        );
53 6
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_INDEX_INITIALIZE, $event);
54
55 6
        $searchForm = $builder->getForm();
56
57 6
        $pagination = array();
58
59 6
        $disps = $app['eccube.repository.master.disp']->findAll();
60 6
        $pageMaxis = $app['eccube.repository.master.page_max']->findAll();
61 6
        $page_count = $app['config']['default_page_count'];
62 6
        $page_status = null;
63 6
        $active = false;
64
65 6
        if ('POST' === $request->getMethod()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
66
67 4
            $searchForm->handleRequest($request);
68
69 4 View Code Duplication
            if ($searchForm->isValid()) {
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 4
                $searchData = $searchForm->getData();
71
72
                // paginator
73 4
                $qb = $app['eccube.repository.order']->getQueryBuilderBySearchDataForAdmin($searchData);
74
75 4
                $event = new EventArgs(
76
                    array(
77 4
                        'form' => $searchForm,
78 4
                        'qb' => $qb,
79
                    ),
80
                    $request
81
                );
82 4
                $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_INDEX_SEARCH, $event);
83
84 4
                $page_no = 1;
85 4
                $pagination = $app['paginator']()->paginate(
86
                    $qb,
87
                    $page_no,
88
                    $page_count,
89 4
                    array('wrap-queries' => true)
90
                );
91
92
                // sessionのデータ保持
93 4
                $session->set('eccube.admin.order.search', $searchData);
94 4
                $session->set('eccube.admin.order.search.page_no', $page_no);
95
            }
96
        } else {
97 4
            if (is_null($page_no) && $request->get('resume') != Constant::ENABLED) {
98
                // sessionを削除
99 2
                $session->remove('eccube.admin.order.search');
100 2
                $session->remove('eccube.admin.order.search.page_no');
101
            } else {
102
                // pagingなどの処理
103 2
                $searchData = $session->get('eccube.admin.order.search');
104 2
                if (is_null($page_no)) {
105
                    $page_no = intval($session->get('eccube.admin.order.search.page_no'));
106
                } else {
107 2
                    $session->set('eccube.admin.order.search.page_no', $page_no);
108
                }
109
110 2
                if (!is_null($searchData)) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
111
112
                    // 公開ステータス
113 2
                    $status = $request->get('status');
114 2
                    if (!empty($status)) {
115
                        if ($status != $app['config']['admin_product_stock_status']) {
116
                            $searchData['status']->clear();
117
                            $searchData['status']->add($status);
118
                        } else {
119
                            $searchData['stock_status'] = $app['config']['disabled'];
120
                        }
121
                        $page_status = $status;
122
                    }
123
                    // 表示件数
124 2
                    $pcount = $request->get('page_count');
125
126 2
                    $page_count = empty($pcount) ? $page_count : $pcount;
127
128 2
                    $qb = $app['eccube.repository.order']->getQueryBuilderBySearchDataForAdmin($searchData);
129
130 2
                    $event = new EventArgs(
131
                        array(
132 2
                            'form' => $searchForm,
133 2
                            'qb' => $qb,
134
                        ),
135
                        $request
136
                    );
137 2
                    $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_INDEX_SEARCH, $event);
138
139 2
                    $pagination = $app['paginator']()->paginate(
140
                        $qb,
141
                        $page_no,
142
                        $page_count,
143 2
                        array('wrap-queries' => true)
144
                    );
145
146
                    // セッションから検索条件を復元
147 2
                    if (!empty($searchData['status'])) {
148 2
                        $searchData['status'] = $app['eccube.repository.master.order_status']->find($searchData['status']);
149
                    }
150 2 View Code Duplication
                    if (count($searchData['sex']) > 0) {
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...
151 2
                        $sex_ids = array();
152 2
                        foreach ($searchData['sex'] as $Sex) {
153 2
                            $sex_ids[] = $Sex->getId();
154
                        }
155 2
                        $searchData['sex'] = $app['eccube.repository.master.sex']->findBy(array('id' => $sex_ids));
156
                    }
157 2 View Code Duplication
                    if (count($searchData['payment']) > 0) {
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...
158 2
                        $payment_ids = array();
159 2
                        foreach ($searchData['payment'] as $Payment) {
160 2
                            $payment_ids[] = $Payment->getId();
161
                        }
162 2
                        $searchData['payment'] = $app['eccube.repository.payment']->findBy(array('id' => $payment_ids));
163
                    }
164 2
                    $searchForm->setData($searchData);
165
                }
166
            }
167
        }
168
169 6
        return $app->render('Order/index.twig', array(
170 6
            'searchForm' => $searchForm->createView(),
171 6
            'pagination' => $pagination,
172 6
            'disps' => $disps,
173 6
            'pageMaxis' => $pageMaxis,
174 6
            'page_no' => $page_no,
175 6
            'page_status' => $page_status,
176 6
            'page_count' => $page_count,
177 6
            'active' => $active,
178
        ));
179
180
    }
181
182 2
    public function delete(Application $app, Request $request, $id)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
183
    {
184 2
        $this->isTokenValid($app);
185 2
        $session = $request->getSession();
186 2
        $page_no = intval($session->get('eccube.admin.order.search.page_no'));
187 2
        $page_no = $page_no ? $page_no : Constant::ENABLED;
188
189 2
        $Order = $app['orm.em']->getRepository('Eccube\Entity\Order')
190 2
            ->find($id);
191
192 2
        if (!$Order) {
193
            $app->deleteMessage();
194
            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...
195
        }
196
197 2
        log_info('受注削除開始', array($Order->getId()));
198
199 2
        $Order->setDelFlg(Constant::ENABLED);
200
201 2
        $app['orm.em']->persist($Order);
202 2
        $app['orm.em']->flush();
203
204 2
        $Customer = $Order->getCustomer();
205 2
        if ($Customer) {
206
            // 会員の場合、購入回数、購入金額などを更新
207 2
            $app['eccube.repository.customer']->updateBuyData($app, $Customer, $Order->getOrderStatus()->getId());
208
        }
209
210 2
        $event = new EventArgs(
211
            array(
212 2
                'Order' => $Order,
213 2
                'Customer' => $Customer,
214
            ),
215
            $request
216
        );
217 2
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_DELETE_COMPLETE, $event);
218
219 2
        $app->addSuccess('admin.order.delete.complete', 'admin');
220
221 2
        log_info('受注削除完了', array($Order->getId()));
222
223 2
        return $app->redirect($app->url('admin_order_page', array('page_no' => $page_no)).'?resume='.Constant::ENABLED);
224
    }
225
226
227
    /**
228
     * 受注CSVの出力.
229
     *
230
     * @param Application $app
231
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
232
     * @return StreamedResponse
233
     */
234
    public function exportOrder(Application $app, Request $request)
235
    {
236
237
        // タイムアウトを無効にする.
238
        set_time_limit(0);
239
240
        // sql loggerを無効にする.
241
        $em = $app['orm.em'];
242
        $em->getConfiguration()->setSQLLogger(null);
243
244
        $response = new StreamedResponse();
245
        $response->setCallback(function () use ($app, $request) {
246
247
            // CSV種別を元に初期化.
248
            $app['eccube.service.csv.export']->initCsvType(CsvType::CSV_TYPE_ORDER);
249
250
            // ヘッダ行の出力.
251
            $app['eccube.service.csv.export']->exportHeader();
252
253
            // 受注データ検索用のクエリビルダを取得.
254
            $qb = $app['eccube.service.csv.export']
255
                ->getOrderQueryBuilder($request);
256
257
            // データ行の出力.
258
            $app['eccube.service.csv.export']->setExportQueryBuilder($qb);
259 View Code Duplication
            $app['eccube.service.csv.export']->exportData(function ($entity, $csvService) {
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...
260
261
                $Csvs = $csvService->getCsvs();
262
263
                $Order = $entity;
264
                $OrderDetails = $Order->getOrderDetails();
265
266
                foreach ($OrderDetails as $OrderDetail) {
267
                    $row = array();
268
269
                    // CSV出力項目と合致するデータを取得.
270
                    foreach ($Csvs as $Csv) {
271
                        // 受注データを検索.
272
                        $data = $csvService->getData($Csv, $Order);
273
                        if (is_null($data)) {
274
                            // 受注データにない場合は, 受注明細を検索.
275
                            $data = $csvService->getData($Csv, $OrderDetail);
276
                        }
277
                        $row[] = $data;
278
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
279
                    }
280
281
                    //$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...
282
                    // 出力.
283
                    $csvService->fputcsv($row);
284
                }
285
            });
286
        });
287
288
        $now = new \DateTime();
289
        $filename = 'order_' . $now->format('YmdHis') . '.csv';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
290
        $response->headers->set('Content-Type', 'application/octet-stream');
291
        $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...
292
        $response->send();
293
294
        log_info('受注CSV出力ファイル名', array($filename));
295
296
        return $response;
297
    }
298
299
    /**
300
     * 配送CSVの出力.
301
     *
302
     * @param Application $app
303
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
304
     * @return StreamedResponse
305
     */
306
    public function exportShipping(Application $app, Request $request)
307
    {
308
        // タイムアウトを無効にする.
309
        set_time_limit(0);
310
311
        // sql loggerを無効にする.
312
        $em = $app['orm.em'];
313
        $em->getConfiguration()->setSQLLogger(null);
314
315
        $response = new StreamedResponse();
316
        $response->setCallback(function () use ($app, $request) {
317
318
            // CSV種別を元に初期化.
319
            $app['eccube.service.csv.export']->initCsvType(CsvType::CSV_TYPE_SHIPPING);
320
321
            // ヘッダ行の出力.
322
            $app['eccube.service.csv.export']->exportHeader();
323
324
            // 受注データ検索用のクエリビルダを取得.
325
            $qb = $app['eccube.service.csv.export']
326
                ->getOrderQueryBuilder($request);
327
328
            // データ行の出力.
329
            $app['eccube.service.csv.export']->setExportQueryBuilder($qb);
330
            $app['eccube.service.csv.export']->exportData(function ($entity, $csvService) {
331
332
                $Csvs = $csvService->getCsvs();
333
334
                /** @var $Order \Eccube\Entity\Order */
335
                $Order = $entity;
336
                /** @var $Shippings \Eccube\Entity\Shipping[] */
337
                $Shippings = $Order->getShippings();
338
339
                foreach ($Shippings as $Shipping) {
340
                    /** @var $ShipmentItems \Eccube\Entity\ShipmentItem */
341
                    $ShipmentItems = $Shipping->getShipmentItems();
342
                    foreach ($ShipmentItems as $ShipmentItem) {
343
                        $row = array();
344
345
                        // CSV出力項目と合致するデータを取得.
346
                        foreach ($Csvs as $Csv) {
347
                            // 受注データを検索.
348
                            $data = $csvService->getData($Csv, $Order);
349
                            if (is_null($data)) {
350
                                // 配送情報を検索.
351
                                $data = $csvService->getData($Csv, $Shipping);
352
                            }
353
                            if (is_null($data)) {
354
                                // 配送商品を検索.
355
                                $data = $csvService->getData($Csv, $ShipmentItem);
356
                            }
357
                            $row[] = $data;
358
                        }
359
                        //$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...
360
                        // 出力.
361
                        $csvService->fputcsv($row);
362
                    }
363
                }
364
            });
365
        });
366
367
        $now = new \DateTime();
368
        $filename = 'shipping_' . $now->format('YmdHis') . '.csv';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
369
        $response->headers->set('Content-Type', 'application/octet-stream');
370
        $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...
371
        $response->send();
372
373
        log_info('配送CSV出力ファイル名', array($filename));
374
375
        return $response;
376
    }
377
}
378