Failed Conditions
Pull Request — experimental/sf (#3394)
by k-yamamura
50:41
created

OrderController::exportPdfDownload()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 62

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 6.1844

Importance

Changes 0
Metric Value
cc 6
nc 10
nop 1
dl 0
loc 62
rs 8.2068
c 0
b 0
f 0
ccs 24
cts 29
cp 0.8276
crap 6.1844

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
/*
4
 * This file is part of EC-CUBE
5
 *
6
 * Copyright(c) LOCKON CO.,LTD. All Rights Reserved.
7
 *
8
 * http://www.lockon.co.jp/
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Eccube\Controller\Admin\Order;
15
16
use Eccube\Common\Constant;
17
use Eccube\Controller\AbstractController;
18
use Eccube\Entity\ExportCsvRow;
19
use Eccube\Entity\Master\CsvType;
20
use Eccube\Entity\Master\OrderStatus;
21
use Eccube\Entity\Order;
22
use Eccube\Entity\OrderPdf;
23
use Eccube\Entity\Shipping;
24
use Eccube\Event\EccubeEvents;
25
use Eccube\Event\EventArgs;
26
use Eccube\Form\Type\Admin\OrderPdfType;
27
use Eccube\Form\Type\Admin\SearchOrderType;
28
use Eccube\Repository\CustomerRepository;
29
use Eccube\Repository\Master\OrderStatusRepository;
30
use Eccube\Repository\Master\PageMaxRepository;
31
use Eccube\Repository\Master\ProductStatusRepository;
32
use Eccube\Repository\Master\SexRepository;
33
use Eccube\Repository\OrderPdfRepository;
34
use Eccube\Repository\OrderRepository;
35
use Eccube\Repository\PaymentRepository;
36
use Eccube\Service\CsvExportService;
37
use Eccube\Service\OrderPdfService;
38
use Eccube\Service\OrderStateMachine;
39
use Eccube\Service\PurchaseFlow\PurchaseContext;
40
use Eccube\Service\PurchaseFlow\PurchaseException;
41
use Eccube\Service\PurchaseFlow\PurchaseFlow;
42
use Eccube\Util\FormUtil;
43
use Knp\Component\Pager\PaginatorInterface;
44
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
45
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
46
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
47
use Symfony\Component\Form\FormBuilder;
48
use Symfony\Component\HttpFoundation\RedirectResponse;
49
use Symfony\Component\HttpFoundation\Request;
50
use Symfony\Component\HttpFoundation\Response;
51
use Symfony\Component\HttpFoundation\StreamedResponse;
52
use Symfony\Component\Validator\Constraints as Assert;
53
use Symfony\Component\Validator\Validator\ValidatorInterface;
54
55
class OrderController extends AbstractController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
56
{
57
    /**
58
     * @var PurchaseFlow
59
     */
60
    protected $purchaseFlow;
61
62
    /**
63
     * @var CsvExportService
64
     */
65
    protected $csvExportService;
66
67
    /**
68
     * @var CustomerRepository
69
     */
70
    protected $customerRepository;
71
72
    /**
73
     * @var PaymentRepository
74
     */
75
    protected $paymentRepository;
76
77
    /**
78
     * @var SexRepository
79
     */
80
    protected $sexRepository;
81
82
    /**
83
     * @var OrderStatusRepository
84
     */
85
    protected $orderStatusRepository;
86
87
    /**
88
     * @var PageMaxRepository
89
     */
90
    protected $pageMaxRepository;
91
92
    /**
93
     * @var ProductStatusRepository
94
     */
95
    protected $productStatusRepository;
96
97
    /**
98
     * @var OrderRepository
99
     */
100
    protected $orderRepository;
101
102
    /** @var OrderPdfRepository */
103
    protected $orderPdfRepository;
104
105
    /** @var OrderPdfService */
106
    protected $orderPdfService;
107
108
    /**
109
     * @var ValidatorInterface
110
     */
111
    protected $validator;
112
113
    /**
114
     * @var OrderStateMachine
115
     */
116
    protected $orderStateMachine;
117
118
    /**
119
     * OrderController constructor.
120
     *
121
     * @param PurchaseFlow $orderPurchaseFlow
0 ignored issues
show
introduced by
Expected 12 spaces after parameter type; 1 found
Loading history...
122
     * @param CsvExportService $csvExportService
0 ignored issues
show
introduced by
Expected 8 spaces after parameter type; 1 found
Loading history...
123
     * @param CustomerRepository $customerRepository
0 ignored issues
show
introduced by
Expected 6 spaces after parameter type; 1 found
Loading history...
124
     * @param PaymentRepository $paymentRepository
0 ignored issues
show
introduced by
Expected 7 spaces after parameter type; 1 found
Loading history...
125
     * @param SexRepository $sexRepository
0 ignored issues
show
introduced by
Expected 11 spaces after parameter type; 1 found
Loading history...
126
     * @param OrderStatusRepository $orderStatusRepository
0 ignored issues
show
introduced by
Expected 3 spaces after parameter type; 1 found
Loading history...
127
     * @param PageMaxRepository $pageMaxRepository
0 ignored issues
show
introduced by
Expected 7 spaces after parameter type; 1 found
Loading history...
128
     * @param ProductStatusRepository $productStatusRepository
129
     * @param OrderRepository $orderRepository
0 ignored issues
show
introduced by
Expected 9 spaces after parameter type; 1 found
Loading history...
130
     * @param OrderPdfRepository $orderPdfRepository
0 ignored issues
show
introduced by
Expected 6 spaces after parameter type; 1 found
Loading history...
131
     * @param OrderPdfService $orderPdfService
0 ignored issues
show
introduced by
Expected 9 spaces after parameter type; 1 found
Loading history...
132
     * @param ValidatorInterface $validator
0 ignored issues
show
introduced by
Expected 6 spaces after parameter type; 1 found
Loading history...
133
     * @param OrderStateMachine $orderStateMachine ;
0 ignored issues
show
introduced by
Expected 7 spaces after parameter type; 1 found
Loading history...
introduced by
Expected 7 spaces after parameter name; 1 found
Loading history...
134
     */
135 28
    public function __construct(
136
        PurchaseFlow $orderPurchaseFlow,
137
        CsvExportService $csvExportService,
138
        CustomerRepository $customerRepository,
139
        PaymentRepository $paymentRepository,
140
        SexRepository $sexRepository,
141
        OrderStatusRepository $orderStatusRepository,
142
        PageMaxRepository $pageMaxRepository,
143
        ProductStatusRepository $productStatusRepository,
144
        OrderRepository $orderRepository,
145
        OrderPdfRepository $orderPdfRepository,
146
        OrderPdfService $orderPdfService,
147
        ValidatorInterface $validator,
148
        OrderStateMachine $orderStateMachine
149
    ) {
150 28
        $this->purchaseFlow = $orderPurchaseFlow;
151 28
        $this->csvExportService = $csvExportService;
152 28
        $this->customerRepository = $customerRepository;
153 28
        $this->paymentRepository = $paymentRepository;
154 28
        $this->sexRepository = $sexRepository;
155 28
        $this->orderStatusRepository = $orderStatusRepository;
156 28
        $this->pageMaxRepository = $pageMaxRepository;
157 28
        $this->productStatusRepository = $productStatusRepository;
158 28
        $this->orderRepository = $orderRepository;
159 28
        $this->orderPdfRepository = $orderPdfRepository;
160 28
        $this->orderPdfService = $orderPdfService;
161 28
        $this->validator = $validator;
162 28
        $this->orderStateMachine = $orderStateMachine;
163
    }
164
165
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$page_no" missing
Loading history...
introduced by
Doc comment for parameter "$paginator" missing
Loading history...
166
     * 受注一覧画面.
167
     *
168
     * - 検索条件, ページ番号, 表示件数はセッションに保持されます.
169
     * - クエリパラメータでresume=1が指定された場合、検索条件, ページ番号, 表示件数をセッションから復旧します.
170
     * - 各データの, セッションに保持するアクションは以下の通りです.
171
     *   - 検索ボタン押下時
172
     *      - 検索条件をセッションに保存します
173
     *      - ページ番号は1で初期化し、セッションに保存します。
174
     *   - 表示件数変更時
175
     *      - クエリパラメータpage_countをセッションに保存します。
176
     *      - ただし, mtb_page_maxと一致しない場合, eccube_default_page_countが保存されます.
177
     *   - ページング時
178
     *      - URLパラメータpage_noをセッションに保存します.
179
     *   - 初期表示
180
     *      - 検索条件は空配列, ページ番号は1で初期化し, セッションに保存します.
181
     *
182
     * @Route("/%eccube_admin_route%/order", name="admin_order")
183
     * @Route("/%eccube_admin_route%/order/page/{page_no}", requirements={"page_no" = "\d+"}, name="admin_order_page")
184
     * @Template("@admin/Order/index.twig")
185
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
186 10
    public function index(Request $request, $page_no = null, PaginatorInterface $paginator)
0 ignored issues
show
Coding Style introduced by
Parameters which have default values should be placed at the end.

If you place a parameter with a default value before a parameter with a default value, the default value of the first parameter will never be used as it will always need to be passed anyway:

// $a must always be passed; it's default value is never used.
function someFunction($a = 5, $b) { }
Loading history...
187
    {
188 10
        $builder = $this->formFactory
189 10
            ->createBuilder(SearchOrderType::class);
190
191 10
        $event = new EventArgs(
192
            [
193 10
                'builder' => $builder,
194
            ],
195 10
            $request
196
        );
197 10
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_INDEX_INITIALIZE, $event);
198
199 10
        $searchForm = $builder->getForm();
200
201
        /**
202
         * ページの表示件数は, 以下の順に優先される.
203
         * - リクエストパラメータ
204
         * - セッション
205
         * - デフォルト値
206
         * また, セッションに保存する際は mtb_page_maxと照合し, 一致した場合のみ保存する.
207
         **/
208 10
        $page_count = $this->session->get('eccube.admin.order.search.page_count',
209 10
            $this->eccubeConfig->get('eccube_default_page_count'));
210
211 10
        $page_count_param = (int) $request->get('page_count');
212 10
        $pageMaxis = $this->pageMaxRepository->findAll();
213
214 10
        if ($page_count_param) {
215 1
            foreach ($pageMaxis as $pageMax) {
216 1
                if ($page_count_param == $pageMax->getName()) {
217
                    $page_count = $pageMax->getName();
218
                    $this->session->set('eccube.admin.order.search.page_count', $page_count);
219 1
                    break;
220
                }
221
            }
222
        }
223
224 10
        if ('POST' === $request->getMethod()) {
225 6
            $searchForm->handleRequest($request);
226
227 6
            if ($searchForm->isValid()) {
228
                /**
229
                 * 検索が実行された場合は, セッションに検索条件を保存する.
230
                 * ページ番号は最初のページ番号に初期化する.
231
                 */
232 5
                $page_no = 1;
233 5
                $searchData = $searchForm->getData();
234
235
                // 検索条件, ページ番号をセッションに保持.
236 5
                $this->session->set('eccube.admin.order.search', FormUtil::getViewData($searchForm));
237 5
                $this->session->set('eccube.admin.order.search.page_no', $page_no);
238
            } else {
239
                // 検索エラーの際は, 詳細検索枠を開いてエラー表示する.
240
                return [
241 6
                    'searchForm' => $searchForm->createView(),
242
                    'pagination' => [],
243 1
                    'pageMaxis' => $pageMaxis,
244 1
                    'page_no' => $page_no,
245 1
                    'page_count' => $page_count,
246
                    'has_errors' => true,
247
                ];
248
            }
249
        } else {
250 5
            if (null !== $page_no || $request->get('resume')) {
251
                /*
252
                 * ページ送りの場合または、他画面から戻ってきた場合は, セッションから検索条件を復旧する.
253
                 */
254 1
                if ($page_no) {
255
                    // ページ送りで遷移した場合.
256 1
                    $this->session->set('eccube.admin.order.search.page_no', (int) $page_no);
257
                } else {
258
                    // 他画面から遷移した場合.
259
                    $page_no = $this->session->get('eccube.admin.order.search.page_no', 1);
260
                }
261 1
                $viewData = $this->session->get('eccube.admin.order.search', []);
262 1
                $searchData = FormUtil::submitAndGetData($searchForm, $viewData);
263
            } else {
264
                /**
265
                 * 初期表示の場合.
266
                 */
267 4
                $page_no = 1;
268 4
                $viewData = [];
269
270 4
                if ($statusId = (int) $request->get('order_status_id')) {
271
                    $viewData = ['status' => $statusId];
272
                }
273
274 4
                $searchData = FormUtil::submitAndGetData($searchForm, $viewData);
275
276
                // セッション中の検索条件, ページ番号を初期化.
277 4
                $this->session->set('eccube.admin.order.search', $viewData);
278 4
                $this->session->set('eccube.admin.order.search.page_no', $page_no);
279
            }
280
        }
281
282 10
        $qb = $this->orderRepository->getQueryBuilderBySearchDataForAdmin($searchData);
283
284 10
        $event = new EventArgs(
285
            [
286 10
                'qb' => $qb,
287 10
                'searchData' => $searchData,
288
            ],
289 10
            $request
290
        );
291
292 10
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_INDEX_SEARCH, $event);
293
294 10
        $pagination = $paginator->paginate(
295 10
            $qb,
296 10
            $page_no,
297 10
            $page_count
298
        );
299
300
        return [
301 10
            'searchForm' => $searchForm->createView(),
302 10
            'pagination' => $pagination,
303 10
            'pageMaxis' => $pageMaxis,
304 10
            'page_no' => $page_no,
305 10
            'page_count' => $page_count,
306
            'has_errors' => false,
307 10
            'OrderStatuses' => $this->orderStatusRepository->findBy([], ['sort_no' => 'ASC']),
308
        ];
309
    }
310
311
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
312
     * @Method("POST")
313
     * @Route("/%eccube_admin_route%/order/bulk_delete", name="admin_order_bulk_delete")
314
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
315 1
    public function bulkDelete(Request $request)
316
    {
317 1
        $this->isTokenValid();
318 1
        $ids = $request->get('ids');
319 1
        foreach ($ids as $order_id) {
320 1
            $Order = $this->orderRepository
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $Order is correct as $this->orderRepository->find($order_id) (which targets Doctrine\ORM\EntityRepository::find()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
321 1
                ->find($order_id);
322 1
            if ($Order) {
323 1
                $this->entityManager->remove($Order);
324 1
                log_info('受注削除', [$Order->getId()]);
325
            }
326
        }
327
328 1
        $this->entityManager->flush();
329
330 1
        $this->addSuccess('admin.order.delete.complete', 'admin');
331
332 1
        return $this->redirect($this->generateUrl('admin_order', ['resume' => Constant::ENABLED]));
333
    }
334
335
    /**
336
     * 受注CSVの出力.
337
     *
338
     * @Route("/%eccube_admin_route%/order/export/order", name="admin_order_export_order")
339
     *
340
     * @param Request $request
341
     *
342
     * @return StreamedResponse
343
     */
344 1 View Code Duplication
    public function exportOrder(Request $request)
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...
345
    {
346 1
        $filename = 'order_'.(new \DateTime())->format('YmdHis').'.csv';
347 1
        $response = $this->exportCsv($request, CsvType::CSV_TYPE_ORDER, $filename);
348 1
        log_info('受注CSV出力ファイル名', [$filename]);
349
350 1
        return $response;
351
    }
352
353
    /**
354
     * 配送CSVの出力.
355
     *
356
     * @Route("/%eccube_admin_route%/order/export/shipping", name="admin_order_export_shipping")
357
     *
358
     * @param Request $request
359
     *
360
     * @return StreamedResponse
361
     */
362 View Code Duplication
    public function exportShipping(Request $request)
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...
363
    {
364
        $filename = 'shipping_'.(new \DateTime())->format('YmdHis').'.csv';
365
        $response = $this->exportCsv($request, CsvType::CSV_TYPE_SHIPPING, $filename);
366
        log_info('配送CSV出力ファイル名', [$filename]);
367
368
        return $response;
369
    }
370
371
    /**
372
     * @param Request $request
373
     * @param $csvTypeId
374
     * @param $fileName
375
     *
376
     * @return StreamedResponse
377
     */
378 1
    private function exportCsv(Request $request, $csvTypeId, $fileName)
379
    {
380
        // タイムアウトを無効にする.
381 1
        set_time_limit(0);
382
383
        // sql loggerを無効にする.
384 1
        $em = $this->entityManager;
385 1
        $em->getConfiguration()->setSQLLogger(null);
386
387 1
        $response = new StreamedResponse();
388 1
        $response->setCallback(function () use ($request, $csvTypeId) {
389
            // CSV種別を元に初期化.
390 1
            $this->csvExportService->initCsvType($csvTypeId);
391
392
            // ヘッダ行の出力.
393 1
            $this->csvExportService->exportHeader();
394
395
            // 受注データ検索用のクエリビルダを取得.
396 1
            $qb = $this->csvExportService
397 1
                ->getOrderQueryBuilder($request);
398
399
            // データ行の出力.
400 1
            $this->csvExportService->setExportQueryBuilder($qb);
401 1
            $this->csvExportService->exportData(function ($entity, $csvService) use ($request) {
402 1
                $Csvs = $csvService->getCsvs();
403
404 1
                $Order = $entity;
405 1
                $OrderItems = $Order->getOrderItems();
406
407 1
                foreach ($OrderItems as $OrderItem) {
408 1
                    $ExportCsvRow = new ExportCsvRow();
409
410
                    // CSV出力項目と合致するデータを取得.
411 1
                    foreach ($Csvs as $Csv) {
412
                        // 受注データを検索.
413 1
                        $ExportCsvRow->setData($csvService->getData($Csv, $Order));
414 1
                        if ($ExportCsvRow->isDataNull()) {
415
                            // 受注データにない場合は, 受注明細を検索.
416 1
                            $ExportCsvRow->setData($csvService->getData($Csv, $OrderItem));
417
                        }
418 1
                        if ($ExportCsvRow->isDataNull() && $Shipping = $OrderItem->getShipping()) {
419
                            // 受注明細データにない場合は, 出荷を検索.
420 1
                            $ExportCsvRow->setData($csvService->getData($Csv, $Shipping));
421
                        }
422
423 1
                        $event = new EventArgs(
424
                            [
425 1
                                'csvService' => $csvService,
426 1
                                'Csv' => $Csv,
427 1
                                'OrderItem' => $OrderItem,
428 1
                                'ExportCsvRow' => $ExportCsvRow,
429
                            ],
430 1
                            $request
431
                        );
432 1
                        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_CSV_EXPORT_ORDER, $event);
433
434 1
                        $ExportCsvRow->pushData();
435
                    }
436
437
                    //$row[] = number_format(memory_get_usage(true));
438
                    // 出力.
439 1
                    $csvService->fputcsv($ExportCsvRow->getRow());
440
                }
441 1
            });
442 1
        });
443
444 1
        $response->headers->set('Content-Type', 'application/octet-stream');
445 1
        $response->headers->set('Content-Disposition', 'attachment; filename='.$fileName);
446 1
        $response->send();
447
448 1
        return $response;
449
    }
450
451
    /**
452
     * @Route("/%eccube_admin_route%/order/export/pdf", name="admin_order_export_pdf")
453
     * @Template("@admin/Order/order_pdf.twig")
454
     *
455
     * @param Request $request
456
     *
457
     * @return array|RedirectResponse
458
     */
459 13
    public function exportPdf(Request $request)
0 ignored issues
show
introduced by
Declare public methods first, then protected ones and finally private ones
Loading history...
460
    {
461
        // requestから受注番号IDの一覧を取得する.
462 13
        $ids = $request->get('ids', []);
463
464 13
        if (count($ids) == 0) {
465 1
            $this->addError('admin.order.export.pdf.parameter.not.found', 'admin');
466 1
            log_info('The Order cannot found!');
467
468 1
            return $this->redirectToRoute('admin_order');
469
        }
470
471
        /** @var OrderPdf $OrderPdf */
472 12
        $OrderPdf = $this->orderPdfRepository->find($this->getUser());
473
474 12
        if (!$OrderPdf) {
475 11
            $OrderPdf = new OrderPdf();
476
            $OrderPdf
477 11
                ->setTitle(trans('admin.order.export.pdf.title.default'))
478 11
                ->setMessage1(trans('admin.order.export.pdf.message1.default'))
479 11
                ->setMessage2(trans('admin.order.export.pdf.message2.default'))
480 11
                ->setMessage3(trans('admin.order.export.pdf.message3.default'));
481
        }
482
483
        /**
484
         * @var FormBuilder
485
         */
486 12
        $builder = $this->formFactory->createBuilder(OrderPdfType::class, $OrderPdf);
487
488
        /* @var \Symfony\Component\Form\Form $form */
489 12
        $form = $builder->getForm();
490
491
        // Formへの設定
492 12
        $form->get('ids')->setData(implode(',', $ids));
493
494
        return [
495 12
            'form' => $form->createView(),
496
        ];
497
    }
498
499
    /**
500
     * @Route("/%eccube_admin_route%/order/export/pdf/download", name="admin_order_pdf_download")
501
     * @Template("@admin/Order/order_pdf.twig")
502
     *
503
     * @param Request $request
504
     *
505
     * @return Response
506
     */
507 10
    public function exportPdfDownload(Request $request)
508
    {
509
        /**
510
         * @var FormBuilder
511
         */
512 10
        $builder = $this->formFactory->createBuilder(OrderPdfType::class);
513
514
        /* @var \Symfony\Component\Form\Form $form */
515 10
        $form = $builder->getForm();
516 10
        $form->handleRequest($request);
517
518
        // Validation
519 10
        if (!$form->isValid()) {
520 7
            log_info('The parameter is invalid!');
521
522 7
            return $this->render('@admin/Order/order_pdf.twig', [
523 7
                'form' => $form->createView(),
524
            ]);
525
        }
526
527 3
        $arrData = $form->getData();
528
529
        // 購入情報からPDFを作成する
530 3
        $status = $this->orderPdfService->makePdf($arrData);
531
532
        // 異常終了した場合の処理
533 3
        if (!$status) {
534
            $this->addError('admin.order.export.pdf.download.failure', 'admin');
535
            log_info('Unable to create pdf files! Process have problems!');
536
537
            return $this->render('@admin/Order/order_pdf.twig', [
538
                'form' => $form->createView(),
539
            ]);
540
        }
541
542
        // ダウンロードする
543 3
        $response = new Response(
544 3
            $this->orderPdfService->outputPdf(),
545 3
            200,
546 3
            ['content-type' => 'application/pdf']
547
        );
548
549 3
        $downloadKind = $form->get('download_kind')->getData();
550
551
        // レスポンスヘッダーにContent-Dispositionをセットし、ファイル名をreceipt.pdfに指定
552 3
        if ($downloadKind == 1) {
553 3
            $response->headers->set('Content-Disposition', 'attachment; filename="'.$this->orderPdfService->getPdfFileName().'"');
554
        } else {
555
            $response->headers->set('Content-Disposition', 'inline; filename="'.$this->orderPdfService->getPdfFileName().'"');
556
        }
557
558 3
        log_info('OrderPdf download success!', ['Order ID' => implode(',', $request->get('ids', []))]);
559
560 3
        $isDefault = isset($arrData['default']) ? $arrData['default'] : false;
561 3
        if ($isDefault) {
562
            // Save input to DB
563 1
            $arrData['admin'] = $this->getUser();
564 1
            $this->orderPdfRepository->save($arrData);
565
        }
566
567 3
        return $response;
568
    }
569
570
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$Shipping" missing
Loading history...
571
     * Update to order status
572
     *
573
     * @Method("PUT")
574
     * @Route("/%eccube_admin_route%/shipping/{id}/order_status", requirements={"id" = "\d+"}, name="admin_shipping_update_order_status")
575
     *
576
     * @param Request $request
0 ignored issues
show
introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
577
     * @param Shipping $shipping
0 ignored issues
show
Documentation introduced by
There is no parameter named $shipping. Did you maybe mean $Shipping?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
introduced by
Doc comment for parameter $shipping does not match case of actual variable name $Shipping
Loading history...
578
     *
579
     * @return RedirectResponse
580
     */
581
    public function updateOrderStatus(Request $request, Shipping $Shipping)
582
    {
583
        if (!($request->isXmlHttpRequest() && $this->isTokenValid())) {
584
            return $this->json(['status' => 'NG'], 400);
585
        }
586
587
        $Order = $Shipping->getOrder();
588
        $OrderStatus = $this->entityManager->find(OrderStatus::class, $request->get('order_status'));
589
590
        $result = [];
591
        try {
592
            // 発送済みに変更された場合は、関連する出荷がすべて出荷済みになったら OrderStatus を変更する
593
            if (OrderStatus::DELIVERED == $OrderStatus->getId()) {
594
                if (!$Shipping->getShippingDate()) {
595
                    $Shipping->setShippingDate(new \DateTime());
596
                    $this->entityManager->flush($Shipping);
0 ignored issues
show
Unused Code introduced by
The call to EntityManagerInterface::flush() has too many arguments starting with $Shipping.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
597
                }
598
                $RelateShippings = $Order->getShippings();
599
                $allShipped = true;
600
                foreach ($RelateShippings as $RelateShipping) {
601
                    if (!$RelateShipping->getShippingDate()) {
602
                        $allShipped = false;
603
                        break;
604
                    }
605
                }
606 View Code Duplication
                if ($allShipped) {
607
                    if ($this->orderStateMachine->can($Order, $OrderStatus)) {
608
                        $this->orderStateMachine->apply($Order, $OrderStatus);
609
                    } else {
610
                        $from = $Order->getOrderStatus()->getName();
611
                        $to = $OrderStatus->getName();
612
                        $result = ['message' => sprintf('%s: %s から %s へのステータス変更はできません', $Shipping->getId(), $from, $to)];
613
                    }
614
                }
615 View Code Duplication
            } else {
616
                if ($this->orderStateMachine->can($Order, $OrderStatus)) {
617
                    $this->orderStateMachine->apply($Order, $OrderStatus);
618
                } else {
619
                    $from = $Order->getOrderStatus()->getName();
620
                    $to = $OrderStatus->getName();
621
                    $result = ['message' => sprintf('%s: %s から %s へのステータス変更はできません', $Shipping->getId(), $from, $to)];
622
                }
623
            }
624
            $this->entityManager->flush($Order);
0 ignored issues
show
Unused Code introduced by
The call to EntityManagerInterface::flush() has too many arguments starting with $Order.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
625
626
            // 会員の場合、購入回数、購入金額などを更新
627
            if ($Customer = $Order->getCustomer()) {
628
                $this->orderRepository->updateOrderSummary($Customer);
629
                $this->entityManager->flush($Customer);
0 ignored issues
show
Unused Code introduced by
The call to EntityManagerInterface::flush() has too many arguments starting with $Customer.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
630
            }
631
            log_info('対応状況一括変更処理完了', [$Order->getId()]);
632
        } catch (\Exception $e) {
633
            log_error('予期しないエラーです', [$e->getMessage()]);
634
635
            return $this->json(['status' => 'NG'], 500);
636
        }
637
638
        return $this->json(array_merge(['status' => 'OK'], $result));
639
    }
640
641
    /**
642
     * Bulk action to order status
643
     *
644
     * @Method("POST")
645
     * @Route("/%eccube_admin_route%/order/bulk/order-status/{id}", requirements={"id" = "\d+"}, name="admin_order_bulk_order_status")
646
     *
647
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
648
     * @param OrderStatus $OrderStatus
649
     *
650
     * @return RedirectResponse
651
     *
652
     * @deprecated 使用していない
653
     */
654 2
    public function bulkOrderStatus(Request $request, OrderStatus $OrderStatus)
655
    {
656 2
        $this->isTokenValid();
657
658
        /** @var Order[] $Orders */
659 2
        $Orders = $this->orderRepository->findBy(['id' => $request->get('ids')]);
660
661 2
        $count = 0;
662 2
        foreach ($Orders as $Order) {
663
            try {
664
                // TODO: should support event for plugin customize
665
                // 編集前の受注情報を保持
666 2
                $OriginOrder = clone $Order;
667
668 2
                $Order->setOrderStatus($OrderStatus);
669
670 2
                $purchaseContext = new PurchaseContext($OriginOrder, $OriginOrder->getCustomer());
671
672 2
                $flowResult = $this->purchaseFlow->validate($Order, $purchaseContext);
673 2
                if ($flowResult->hasWarning()) {
674 1
                    foreach ($flowResult->getWarning() as $warning) {
675 1
                        $msg = $this->translator->trans('admin.order.index.bulk_warning', [
676 1
                            '%orderId%' => $Order->getId(),
677 1
                            '%message%' => $warning->getMessage(),
678
                        ]);
679 1
                        $this->addWarning($msg, 'admin');
680
                    }
681
                }
682
683 2
                if ($flowResult->hasError()) {
684
                    foreach ($flowResult->getErrors() as $error) {
685
                        $msg = $this->translator->trans('admin.order.index.bulk_error', [
686
                            '%orderId%' => $Order->getId(),
687
                            '%message%' => $error->getMessage(),
688
                        ]);
689
                        $this->addError($msg, 'admin');
690
                    }
691
                    continue;
692
                }
693
694
                try {
695 2
                    $this->purchaseFlow->commit($Order, $purchaseContext);
696
                } catch (PurchaseException $e) {
697
                    $msg = $this->translator->trans('admin.order.index.bulk_error', [
698
                        '%orderId%' => $Order->getId(),
699
                        '%message%' => $e->getMessage(),
700
                    ]);
701
                    $this->addError($msg, 'admin');
702
                    continue;
703
                }
704
705 2
                $this->orderRepository->save($Order);
706
707 2
                $count++;
708
            } catch (\Exception $e) {
709 2
                $this->addError('#'.$Order->getId().': '.$e->getMessage(), 'admin');
710
            }
711
        }
712
        try {
713 2 View Code Duplication
            if ($count) {
714 2
                $this->entityManager->flush();
715 2
                $msg = $this->translator->trans('admin.order.index.bulk_order_status_success_count', [
716 2
                    '%count%' => $count,
717 2
                    '%status%' => $OrderStatus->getName(),
718
                ]);
719 2
                $this->addSuccess($msg, 'admin');
720
            }
721
        } catch (\Exception $e) {
722
            log_error('Bulk order status error', [$e]);
723
            $this->addError('admin.flash.register_failed', 'admin');
724
        }
725
726 2
        return $this->redirectToRoute('admin_order', ['resume' => Constant::ENABLED]);
727
    }
728
729
    /**
730
     * Update to Tracking number.
731
     *
732
     * @Method("PUT")
733
     * @Route("/%eccube_admin_route%/shipping/{id}/tracking_number", requirements={"id" = "\d+"}, name="admin_shipping_update_tracking_number")
734
     *
735
     * @param Request $request
0 ignored issues
show
introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
736
     * @param Shipping $shipping
737
     *
738
     * @return Response
739
     */
740 2
    public function updateTrackingNumber(Request $request, Shipping $shipping)
741
    {
742 2
        if (!($request->isXmlHttpRequest() && $this->isTokenValid())) {
743
            return $this->json(['status' => 'NG'], 400);
744
        }
745
746 2
        $trackingNumber = mb_convert_kana($request->get('tracking_number'), 'a', 'utf-8');
747
        /** @var \Symfony\Component\Validator\ConstraintViolationListInterface $errors */
748 2
        $errors = $this->validator->validate(
749 2
            $trackingNumber,
750
            [
751 2
                new Assert\Length(['max' => $this->eccubeConfig['eccube_stext_len']]),
752 2
                new Assert\Regex(
753 2
                    ['pattern' => '/^[0-9a-zA-Z-]+$/u', 'message' => trans('form.type.admin.nottrackingnumberstyle')]
754
                ),
755
            ]
756
        );
757
758 2
        if ($errors->count() != 0) {
759 1
            log_info('送り状番号入力チェックエラー');
760 1
            $messages = [];
761
            /** @var \Symfony\Component\Validator\ConstraintViolationInterface $error */
762 1
            foreach ($errors as $error) {
763 1
                $messages[] = $error->getMessage();
764
            }
765
766 1
            return $this->json(['status' => 'NG', 'messages' => $messages], 400);
767
        }
768
769
        try {
770 1
            $shipping->setTrackingNumber($trackingNumber);
771 1
            $this->entityManager->flush($shipping);
0 ignored issues
show
Unused Code introduced by
The call to EntityManagerInterface::flush() has too many arguments starting with $shipping.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
772 1
            log_info('送り状番号変更処理完了', [$shipping->getId()]);
773 1
            $message = ['status' => 'OK', 'shipping_id' => $shipping->getId(), 'tracking_number' => $trackingNumber];
774
775 1
            return $this->json($message);
776
        } catch (\Exception $e) {
777
            log_error('予期しないエラー', [$e->getMessage()]);
778
779
            return $this->json(['status' => 'NG'], 500);
780
        }
781
    }
782
}
783