Failed Conditions
Pull Request — experimental/sf (#3336)
by
unknown
471:18 queued 461:42
created

OrderController::updateOrderStatus()   C

Complexity

Conditions 12
Paths 208

Size

Total Lines 59

Duplication

Lines 18
Ratio 30.51 %

Code Coverage

Tests 0
CRAP Score 156

Importance

Changes 0
Metric Value
cc 12
nc 208
nop 2
dl 18
loc 59
ccs 0
cts 36
cp 0
crap 156
rs 5.7211
c 0
b 0
f 0

How to fix   Long Method    Complexity   

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\Csv;
19
use Eccube\Entity\ExportCsvRow;
20
use Eccube\Entity\Master\CsvType;
21
use Eccube\Entity\OrderPdf;
22
use Eccube\Event\EccubeEvents;
23
use Eccube\Event\EventArgs;
24
use Eccube\Form\Type\Admin\OrderPdfType;
25
use Eccube\Form\Type\Admin\SearchOrderType;
26
use Eccube\Repository\CustomerRepository;
27
use Eccube\Repository\Master\OrderStatusRepository;
28
use Eccube\Repository\Master\PageMaxRepository;
29
use Eccube\Repository\Master\ProductStatusRepository;
30
use Eccube\Repository\Master\SexRepository;
31
use Eccube\Repository\OrderPdfRepository;
32
use Eccube\Repository\OrderRepository;
33
use Eccube\Repository\PaymentRepository;
34
use Eccube\Service\CsvExportService;
35
use Eccube\Service\OrderPdfService;
36
use Eccube\Service\OrderStateMachine;
37
use Eccube\Util\FormUtil;
38
use Knp\Component\Pager\PaginatorInterface;
39
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
40
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
41
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
42
use Symfony\Component\Form\FormBuilder;
43
use Symfony\Component\HttpFoundation\Response;
44
use Symfony\Component\HttpFoundation\Request;
45
use Symfony\Component\HttpFoundation\StreamedResponse;
46
use Eccube\Entity\Master\OrderStatus;
47
use Symfony\Component\HttpFoundation\RedirectResponse;
48
use Eccube\Entity\Order;
49
use Eccube\Entity\Shipping;
50
use Eccube\Service\PurchaseFlow\PurchaseContext;
51
use Eccube\Service\PurchaseFlow\PurchaseFlow;
52
use Eccube\Service\PurchaseFlow\PurchaseException;
53
use Symfony\Component\Validator\Constraints as Assert;
54
use Symfony\Component\Validator\Validator\ValidatorInterface;
55
56
class OrderController extends AbstractController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
57
{
58
    /**
59
     * @var PurchaseFlow
60
     */
61
    protected $purchaseFlow;
62
63
    /**
64
     * @var CsvExportService
65
     */
66
    protected $csvExportService;
67
68
    /**
69
     * @var CustomerRepository
70
     */
71
    protected $customerRepository;
72
73
    /**
74
     * @var PaymentRepository
75
     */
76
    protected $paymentRepository;
77
78
    /**
79
     * @var SexRepository
80
     */
81
    protected $sexRepository;
82
83
    /**
84
     * @var OrderStatusRepository
85
     */
86
    protected $orderStatusRepository;
87
88
    /**
89
     * @var PageMaxRepository
90
     */
91
    protected $pageMaxRepository;
92
93
    /**
94
     * @var ProductStatusRepository
95
     */
96
    protected $productStatusRepository;
97
98
    /**
99
     * @var OrderRepository
100
     */
101
    protected $orderRepository;
102
103
    /** @var OrderPdfRepository */
104
    protected $orderPdfRepository;
105
106
    /** @var OrderPdfService */
107
    protected $orderPdfService;
108
109
    /**
110
     * @var ValidatorInterface
111
     */
112
    protected $validator;
113
114
    /**
115
     * @var OrderStateMachine
116
     */
117
    protected $orderStateMachine;
118
119
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$orderStateMachine" missing
Loading history...
120
     * OrderController constructor.
121
     *
122
     * @param PurchaseFlow $orderPurchaseFlow
0 ignored issues
show
introduced by
Expected 12 spaces after parameter type; 1 found
Loading history...
123
     * @param CsvExportService $csvExportService
0 ignored issues
show
introduced by
Expected 8 spaces after parameter type; 1 found
Loading history...
124
     * @param CustomerRepository $customerRepository
0 ignored issues
show
introduced by
Expected 6 spaces after parameter type; 1 found
Loading history...
125
     * @param PaymentRepository $paymentRepository
0 ignored issues
show
introduced by
Expected 7 spaces after parameter type; 1 found
Loading history...
126
     * @param SexRepository $sexRepository
0 ignored issues
show
introduced by
Expected 11 spaces after parameter type; 1 found
Loading history...
127
     * @param OrderStatusRepository $orderStatusRepository
0 ignored issues
show
introduced by
Expected 3 spaces after parameter type; 1 found
Loading history...
128
     * @param PageMaxRepository $pageMaxRepository
0 ignored issues
show
introduced by
Expected 7 spaces after parameter type; 1 found
Loading history...
129
     * @param ProductStatusRepository $productStatusRepository
130
     * @param OrderRepository $orderRepository
0 ignored issues
show
introduced by
Expected 9 spaces after parameter type; 1 found
Loading history...
131
     * @param OrderPdfRepository $orderPdfRepository
0 ignored issues
show
introduced by
Expected 6 spaces after parameter type; 1 found
Loading history...
132
     * @param OrderPdfService $orderPdfService
0 ignored issues
show
introduced by
Expected 9 spaces after parameter type; 1 found
Loading history...
133
     * @param ValidatorInterface $validator
0 ignored issues
show
introduced by
Expected 6 spaces after parameter type; 1 found
Loading history...
134
     * @param OrderStateMachine $orderStateMachine;
0 ignored issues
show
Documentation introduced by
There is no parameter named $orderStateMachine;. Did you maybe mean $orderStateMachine?

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
Expected 7 spaces after parameter type; 1 found
Loading history...
introduced by
Doc comment for parameter $orderStateMachine; does not match actual variable name $orderStateMachine
Loading history...
135
     */
136 29
    public function __construct(
137
        PurchaseFlow $orderPurchaseFlow,
138
        CsvExportService $csvExportService,
139
        CustomerRepository $customerRepository,
140
        PaymentRepository $paymentRepository,
141
        SexRepository $sexRepository,
142
        OrderStatusRepository $orderStatusRepository,
143
        PageMaxRepository $pageMaxRepository,
144
        ProductStatusRepository $productStatusRepository,
145
        OrderRepository $orderRepository,
146
        OrderPdfRepository $orderPdfRepository,
147
        OrderPdfService $orderPdfService,
148
        ValidatorInterface $validator,
149
        OrderStateMachine $orderStateMachine
150
    ) {
151 29
        $this->purchaseFlow = $orderPurchaseFlow;
152 29
        $this->csvExportService = $csvExportService;
153 29
        $this->customerRepository = $customerRepository;
154 29
        $this->paymentRepository = $paymentRepository;
155 29
        $this->sexRepository = $sexRepository;
156 29
        $this->orderStatusRepository = $orderStatusRepository;
157 29
        $this->pageMaxRepository = $pageMaxRepository;
158 29
        $this->productStatusRepository = $productStatusRepository;
159 29
        $this->orderRepository = $orderRepository;
160 29
        $this->orderPdfRepository = $orderPdfRepository;
161 29
        $this->orderPdfService = $orderPdfService;
162 29
        $this->validator = $validator;
163 29
        $this->orderStateMachine = $orderStateMachine;
164
    }
165
166
    /**
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...
167
     * 受注一覧画面.
168
     *
169
     * - 検索条件, ページ番号, 表示件数はセッションに保持されます.
170
     * - クエリパラメータでresume=1が指定された場合、検索条件, ページ番号, 表示件数をセッションから復旧します.
171
     * - 各データの, セッションに保持するアクションは以下の通りです.
172
     *   - 検索ボタン押下時
173
     *      - 検索条件をセッションに保存します
174
     *      - ページ番号は1で初期化し、セッションに保存します。
175
     *   - 表示件数変更時
176
     *      - クエリパラメータpage_countをセッションに保存します。
177
     *      - ただし, mtb_page_maxと一致しない場合, eccube_default_page_countが保存されます.
178
     *   - ページング時
179
     *      - URLパラメータpage_noをセッションに保存します.
180
     *   - 初期表示
181
     *      - 検索条件は空配列, ページ番号は1で初期化し, セッションに保存します.
182
     *
183
     * @Route("/%eccube_admin_route%/order", name="admin_order")
184
     * @Route("/%eccube_admin_route%/order/page/{page_no}", requirements={"page_no" = "\d+"}, name="admin_order_page")
185
     * @Template("@admin/Order/index.twig")
186
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
187 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...
188
    {
189 10
        $builder = $this->formFactory
190 10
            ->createBuilder(SearchOrderType::class);
191
192 10
        $event = new EventArgs(
193
            [
194 10
                'builder' => $builder,
195
            ],
196 10
            $request
197
        );
198 10
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_INDEX_INITIALIZE, $event);
199
200 10
        $searchForm = $builder->getForm();
201
202
        /**
203
         * ページの表示件数は, 以下の順に優先される.
204
         * - リクエストパラメータ
205
         * - セッション
206
         * - デフォルト値
207
         * また, セッションに保存する際は mtb_page_maxと照合し, 一致した場合のみ保存する.
208
         **/
209 10
        $page_count = $this->session->get('eccube.admin.order.search.page_count',
210 10
                $this->eccubeConfig->get('eccube_default_page_count'));
211
212 10
        $page_count_param = (int) $request->get('page_count');
213 10
        $pageMaxis = $this->pageMaxRepository->findAll();
214
215 10
        if ($page_count_param) {
216 1
            foreach ($pageMaxis as $pageMax) {
217 1
                if ($page_count_param == $pageMax->getName()) {
218
                    $page_count = $pageMax->getName();
219
                    $this->session->set('eccube.admin.order.search.page_count', $page_count);
220 1
                    break;
221
                }
222
            }
223
        }
224
225 10
        if ('POST' === $request->getMethod()) {
226 6
            $searchForm->handleRequest($request);
227
228 6
            if ($searchForm->isValid()) {
229
                /**
230
                 * 検索が実行された場合は, セッションに検索条件を保存する.
231
                 * ページ番号は最初のページ番号に初期化する.
232
                 */
233 5
                $page_no = 1;
234 5
                $searchData = $searchForm->getData();
235
236
                // 検索条件, ページ番号をセッションに保持.
237 5
                $this->session->set('eccube.admin.order.search', FormUtil::getViewData($searchForm));
238 5
                $this->session->set('eccube.admin.order.search.page_no', $page_no);
239
            } else {
240
                // 検索エラーの際は, 詳細検索枠を開いてエラー表示する.
241
                return [
242 6
                    'searchForm' => $searchForm->createView(),
243
                    'pagination' => [],
244 1
                    'pageMaxis' => $pageMaxis,
245 1
                    'page_no' => $page_no,
246 1
                    'page_count' => $page_count,
247
                    'has_errors' => true,
248
                ];
249
            }
250
        } else {
251 5
            if (null !== $page_no || $request->get('resume')) {
252
                /*
253
                 * ページ送りの場合または、他画面から戻ってきた場合は, セッションから検索条件を復旧する.
254
                 */
255 1
                if ($page_no) {
256
                    // ページ送りで遷移した場合.
257 1
                    $this->session->set('eccube.admin.order.search.page_no', (int) $page_no);
258
                } else {
259
                    // 他画面から遷移した場合.
260
                    $page_no = $this->session->get('eccube.admin.order.search.page_no', 1);
261
                }
262 1
                $viewData = $this->session->get('eccube.admin.order.search', []);
263 1
                $searchData = FormUtil::submitAndGetData($searchForm, $viewData);
264
            } else {
265
                /**
266
                 * 初期表示の場合.
267
                 */
268 4
                $page_no = 1;
269 4
                $viewData = [];
270
271 4
                if ($statusId = (int) $request->get('order_status_id')) {
272
                    $viewData = ['status' => $statusId];
273
                }
274
275 4
                $searchData = FormUtil::submitAndGetData($searchForm, $viewData);
276
277
                // セッション中の検索条件, ページ番号を初期化.
278 4
                $this->session->set('eccube.admin.order.search', $viewData);
279 4
                $this->session->set('eccube.admin.order.search.page_no', $page_no);
280
            }
281
        }
282
283 10
        $qb = $this->orderRepository->getQueryBuilderBySearchDataForAdmin($searchData);
284
285 10
        $event = new EventArgs(
286
            [
287 10
                'qb' => $qb,
288 10
                'searchData' => $searchData,
289
            ],
290 10
            $request
291
        );
292
293 10
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_INDEX_SEARCH, $event);
294
295 10
        $pagination = $paginator->paginate(
296 10
            $qb,
297 10
            $page_no,
298 10
            $page_count
299
        );
300
301
        return [
302 10
            'searchForm' => $searchForm->createView(),
303 10
            'pagination' => $pagination,
304 10
            'pageMaxis' => $pageMaxis,
305 10
            'page_no' => $page_no,
306 10
            'page_count' => $page_count,
307
            'has_errors' => false,
308 10
            'OrderStatuses' => $this->orderStatusRepository->findBy([], ['sort_no' => 'ASC']),
309
        ];
310
    }
311
312
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
313
     * @Method("POST")
314
     * @Route("/%eccube_admin_route%/order/bulk_delete", name="admin_order_bulk_delete")
315
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
316 1
    public function bulkDelete(Request $request)
317
    {
318 1
        $this->isTokenValid();
319 1
        $ids = $request->get('ids');
320 1
        foreach ($ids as $order_id) {
321 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...
322 1
                ->find($order_id);
323 1
            if ($Order) {
324 1
                $this->entityManager->remove($Order);
325 1
                log_info('受注削除', [$Order->getId()]);
326
            }
327
        }
328
329 1
        $this->entityManager->flush();
330
331 1
        $this->addSuccess('admin.order.delete.complete', 'admin');
332
333 1
        return $this->redirect($this->generateUrl('admin_order', ['resume' => Constant::ENABLED]));
334
    }
335
336
    /**
337
     * 受注CSVの出力.
338
     *
339
     * @Route("/%eccube_admin_route%/order/export/order", name="admin_order_export_order")
340
     *
341
     * @param Request $request
342
     *
343
     * @return StreamedResponse
344
     */
345 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...
346
    {
347 1
        $filename = 'order_'.(new \DateTime())->format('YmdHis').'.csv';
348 1
        $response = $this->exportCsv($request, CsvType::CSV_TYPE_ORDER, $filename);
349 1
        log_info('受注CSV出力ファイル名', [$filename]);
350
351 1
        return $response;
352
    }
353
354
    /**
355
     * 配送CSVの出力.
356
     *
357
     * @Route("/%eccube_admin_route%/order/export/shipping", name="admin_order_export_shipping")
358
     *
359
     * @param Request $request
360
     *
361
     * @return StreamedResponse
362
     */
363 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...
364
    {
365
        $filename = 'shipping_'.(new \DateTime())->format('YmdHis').'.csv';
366
        $response = $this->exportCsv($request, CsvType::CSV_TYPE_SHIPPING, $filename);
367
        log_info('配送CSV出力ファイル名', [$filename]);
368
369
        return $response;
370
    }
371
372
    /**
373
     * @param Request $request
374
     * @param $csvTypeId
375
     * @param $fileName
376
     *
377
     * @return StreamedResponse
378
     */
379 1
    private function exportCsv(Request $request, $csvTypeId, $fileName)
380
    {
381
        // タイムアウトを無効にする.
382 1
        set_time_limit(0);
383
384
        // sql loggerを無効にする.
385 1
        $em = $this->entityManager;
386 1
        $em->getConfiguration()->setSQLLogger(null);
387
388 1
        $response = new StreamedResponse();
389 1
        $response->setCallback(function () use ($request, $csvTypeId) {
390
            // CSV種別を元に初期化.
391 1
            $this->csvExportService->initCsvType($csvTypeId);
392
393
            // ヘッダ行の出力.
394 1
            $this->csvExportService->exportHeader();
395
396
            // 受注データ検索用のクエリビルダを取得.
397 1
            $qb = $this->csvExportService
398 1
                ->getOrderQueryBuilder($request);
399
400
            // データ行の出力.
401 1
            $this->csvExportService->setExportQueryBuilder($qb);
402 1
            $this->csvExportService->exportData(function ($entity, $csvService) use ($request) {
403 1
                $Csvs = $csvService->getCsvs();
404
405 1
                $Order = $entity;
406 1
                $OrderItems = $Order->getOrderItems();
407
408 1
                foreach ($OrderItems as $OrderItem) {
409 1
                    $ExportCsvRow = new ExportCsvRow();
410
411
                    // CSV出力項目と合致するデータを取得.
412 1
                    foreach ($Csvs as $Csv) {
413
                        // 受注データを検索.
414 1
                        $ExportCsvRow->setData($csvService->getData($Csv, $Order));
415 1
                        if ($ExportCsvRow->isDataNull()) {
416
                            // 受注データにない場合は, 受注明細を検索.
417 1
                            $ExportCsvRow->setData($csvService->getData($Csv, $OrderItem));
418
                        }
419 1
                        if ($ExportCsvRow->isDataNull() && $Shipping = $OrderItem->getShipping()) {
420
                            // 受注明細データにない場合は, 出荷を検索.
421 1
                            $ExportCsvRow->setData($csvService->getData($Csv, $Shipping));
422
                        }
423
424 1
                        $event = new EventArgs(
425
                            [
426 1
                                'csvService' => $csvService,
427 1
                                'Csv' => $Csv,
428 1
                                'OrderItem' => $OrderItem,
429 1
                                'ExportCsvRow' => $ExportCsvRow,
430
                            ],
431 1
                            $request
432
                        );
433 1
                        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_CSV_EXPORT_ORDER, $event);
434
435 1
                        $ExportCsvRow->pushData();
436
                    }
437
438
                    //$row[] = number_format(memory_get_usage(true));
439
                    // 出力.
440 1
                    $csvService->fputcsv($ExportCsvRow->getRow());
441
                }
442 1
            });
443 1
        });
444
445 1
        $response->headers->set('Content-Type', 'application/octet-stream');
446 1
        $response->headers->set('Content-Disposition', 'attachment; filename='.$fileName);
447 1
        $response->send();
448
449 1
        return $response;
450
    }
451
452
    /**
453
     * @Route("/%eccube_admin_route%/order/export/pdf", name="admin_order_export_pdf")
454
     * @Template("@admin/Order/order_pdf.twig")
455
     *
456
     * @param Request $request
457
     *
458
     * @return array|RedirectResponse
459
     */
460 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...
461
    {
462
        // requestから受注番号IDの一覧を取得する.
463 13
        $ids = $request->get('ids', []);
464
465 13
        if (count($ids) == 0) {
466 1
            $this->addError('admin.order.export.pdf.parameter.not.found', 'admin');
467 1
            log_info('The Order cannot found!');
468
469 1
            return $this->redirectToRoute('admin_order');
470
        }
471
472
        /** @var OrderPdf $OrderPdf */
473 12
        $OrderPdf = $this->orderPdfRepository->find($this->getUser());
474
475 12
        if (!$OrderPdf) {
476 11
            $OrderPdf = new OrderPdf();
477
            $OrderPdf
478 11
                ->setTitle(trans('admin.order.export.pdf.title.default'))
479 11
                ->setMessage1(trans('admin.order.export.pdf.message1.default'))
480 11
                ->setMessage2(trans('admin.order.export.pdf.message2.default'))
481 11
                ->setMessage3(trans('admin.order.export.pdf.message3.default'));
482
        }
483
484
        /**
485
         * @var FormBuilder
486
         */
487 12
        $builder = $this->formFactory->createBuilder(OrderPdfType::class, $OrderPdf);
488
489
        /* @var \Symfony\Component\Form\Form $form */
490 12
        $form = $builder->getForm();
491
492
        // Formへの設定
493 12
        $form->get('ids')->setData(implode(',', $ids));
494
495
        return [
496 12
            'form' => $form->createView(),
497
        ];
498
    }
499
500
    /**
501
     * @Route("/%eccube_admin_route%/order/export/pdf/download", name="admin_order_pdf_download")
502
     * @Template("@admin/Order/order_pdf.twig")
503
     *
504
     * @param Request $request
505
     *
506
     * @return Response
507
     */
508 11
    public function exportPdfDownload(Request $request)
509
    {
510
        /**
511
         * @var FormBuilder
512
         */
513 11
        $builder = $this->formFactory->createBuilder(OrderPdfType::class);
514
515
        /* @var \Symfony\Component\Form\Form $form */
516 11
        $form = $builder->getForm();
517 11
        $form->handleRequest($request);
518
519
        // Validation
520 11
        if (!$form->isValid()) {
521 8
            log_info('The parameter is invalid!');
522
523 8
            return $this->render('@admin/Order/order_pdf.twig', [
524 8
                'form' => $form->createView(),
525
            ]);
526
        }
527
528 3
        $arrData = $form->getData();
529
530
        // 購入情報からPDFを作成する
531 3
        $status = $this->orderPdfService->makePdf($arrData);
532
533
        // 異常終了した場合の処理
534 3
        if (!$status) {
535
            $this->addError('admin.order.export.pdf.download.failure', 'admin');
536
            log_info('Unable to create pdf files! Process have problems!');
537
538
            return $this->render('@admin/Order/order_pdf.twig', [
539
                'form' => $form->createView(),
540
            ]);
541
        }
542
543
        // ダウンロードする
544 3
        $response = new Response(
545 3
            $this->orderPdfService->outputPdf(),
546 3
            200,
547 3
            ['content-type' => 'application/pdf']
548
        );
549
550
        // レスポンスヘッダーにContent-Dispositionをセットし、ファイル名をreceipt.pdfに指定
551 3
        $response->headers->set('Content-Disposition', 'attachment; filename="'.$this->orderPdfService->getPdfFileName().'"');
552 3
        log_info('OrderPdf download success!', ['Order ID' => implode(',', $request->get('ids', []))]);
553
554 3
        $isDefault = isset($arrData['default']) ? $arrData['default'] : false;
555 3
        if ($isDefault) {
556
            // Save input to DB
557 1
            $arrData['admin'] = $this->getUser();
558 1
            $this->orderPdfRepository->save($arrData);
559
        }
560
561 3
        return $response;
562
    }
563
564
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$Shipping" missing
Loading history...
565
     * Update to order status
566
     *
567
     * @Method("PUT")
568
     * @Route("/%eccube_admin_route%/shipping/{id}/order_status", requirements={"id" = "\d+"}, name="admin_shipping_update_order_status")
569
     *
570
     * @param Request $request
0 ignored issues
show
introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
571
     * @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...
572
     *
573
     * @return RedirectResponse
574
     */
575
    public function updateOrderStatus(Request $request, Shipping $Shipping)
576
    {
577
        if (!($request->isXmlHttpRequest() && $this->isTokenValid())) {
578
            return $this->json(['status' => 'NG'], 400);
579
        }
580
581
        $Order = $Shipping->getOrder();
582
        $OrderStatus = $this->entityManager->find(OrderStatus::class, $request->get('order_status'));
583
584
        $result = [];
585
        try {
586
            // 発送済みに変更された場合は、関連する出荷がすべて出荷済みになったら OrderStatus を変更する
587
            if (OrderStatus::DELIVERED == $OrderStatus->getId()) {
588
                if (!$Shipping->getShippingDate()) {
589
                    $Shipping->setShippingDate(new \DateTime());
590
                    $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...
591
                }
592
                $RelateShippings = $Order->getShippings();
593
                $allShipped = true;
594
                foreach ($RelateShippings as $RelateShipping) {
595
                    if (!$RelateShipping->getShippingDate()) {
596
                        $allShipped = false;
597
                        break;
598
                    }
599
                }
600 View Code Duplication
                if ($allShipped) {
601
                    if ($this->orderStateMachine->can($Order, $OrderStatus)) {
602
                        $this->orderStateMachine->apply($Order, $OrderStatus);
603
                    } else {
604
                        $from = $Order->getOrderStatus()->getName();
605
                        $to = $OrderStatus->getName();
606
                        $result = ['message' => sprintf('%s: %s から %s へのステータス変更はできません', $Shipping->getId(), $from, $to)];
607
                    }
608
                }
609 View Code Duplication
            } else {
610
                if ($this->orderStateMachine->can($Order, $OrderStatus)) {
611
                    $this->orderStateMachine->apply($Order, $OrderStatus);
612
                } else {
613
                    $from = $Order->getOrderStatus()->getName();
614
                    $to = $OrderStatus->getName();
615
                    $result = ['message' => sprintf('%s: %s から %s へのステータス変更はできません', $Shipping->getId(), $from, $to)];
616
                }
617
            }
618
            $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...
619
620
            // 会員の場合、購入回数、購入金額などを更新
621
            if ($Customer = $Order->getCustomer()) {
622
                $this->orderRepository->updateOrderSummary($Customer);
623
                $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...
624
            }
625
            log_info('対応状況一括変更処理完了', [$Order->getId()]);
626
        } catch (\Exception $e) {
627
            log_error('予期しないエラーです', [$e->getMessage()]);
628
629
            return $this->json(['status' => 'NG'], 500);
630
        }
631
632
        return $this->json(array_merge(['status' => 'OK'], $result));
633
    }
634
635
    /**
636
     * Bulk action to order status
637
     *
638
     * @Method("POST")
639
     * @Route("/%eccube_admin_route%/order/bulk/order-status/{id}", requirements={"id" = "\d+"}, name="admin_order_bulk_order_status")
640
     *
641
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
642
     * @param OrderStatus $OrderStatus
643
     *
644
     * @return RedirectResponse
645
     *
646
     * @deprecated 使用していない
647
     */
648 2
    public function bulkOrderStatus(Request $request, OrderStatus $OrderStatus)
649
    {
650 2
        $this->isTokenValid();
651
652
        /** @var Order[] $Orders */
653 2
        $Orders = $this->orderRepository->findBy(['id' => $request->get('ids')]);
654
655 2
        $count = 0;
656 2
        foreach ($Orders as $Order) {
657
            try {
658
                // TODO: should support event for plugin customize
659
                // 編集前の受注情報を保持
660 2
                $OriginOrder = clone $Order;
661
662 2
                $Order->setOrderStatus($OrderStatus);
663
664 2
                $purchaseContext = new PurchaseContext($OriginOrder, $OriginOrder->getCustomer());
665
666 2
                $flowResult = $this->purchaseFlow->validate($Order, $purchaseContext);
667 2
                if ($flowResult->hasWarning()) {
668
                    foreach ($flowResult->getWarning() as $warning) {
669
                        $msg = $this->translator->trans('admin.order.index.bulk_warning', [
670
                          '%orderId%' => $Order->getId(),
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 28 spaces, but found 26.
Loading history...
671
                          '%message%' => $warning->getMessage(),
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 28 spaces, but found 26.
Loading history...
672
                        ]);
673
                        $this->addWarning($msg, 'admin');
674
                    }
675
                }
676
677 2
                if ($flowResult->hasError()) {
678
                    foreach ($flowResult->getErrors() as $error) {
679
                        $msg = $this->translator->trans('admin.order.index.bulk_error', [
680
                          '%orderId%' => $Order->getId(),
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 28 spaces, but found 26.
Loading history...
681
                          '%message%' => $error->getMessage(),
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 28 spaces, but found 26.
Loading history...
682
                        ]);
683
                        $this->addError($msg, 'admin');
684
                    }
685
                    continue;
686
                }
687
688
                try {
689 2
                    $this->purchaseFlow->commit($Order, $purchaseContext);
690
                } catch (PurchaseException $e) {
691
                    $msg = $this->translator->trans('admin.order.index.bulk_error', [
692
                      '%orderId%' => $Order->getId(),
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 24 spaces, but found 22.
Loading history...
693
                      '%message%' => $e->getMessage(),
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 24 spaces, but found 22.
Loading history...
694
                    ]);
695
                    $this->addError($msg, 'admin');
696
                    continue;
697
                }
698
699 2
                $this->orderRepository->save($Order);
700
701 2
                $count++;
702
            } catch (\Exception $e) {
703 2
                $this->addError('#'.$Order->getId().': '.$e->getMessage(), 'admin');
704
            }
705
        }
706
        try {
707 2 View Code Duplication
            if ($count) {
708 2
                $this->entityManager->flush();
709 2
                $msg = $this->translator->trans('admin.order.index.bulk_order_status_success_count', [
710 2
                    '%count%' => $count,
711 2
                    '%status%' => $OrderStatus->getName(),
712
                ]);
713 2
                $this->addSuccess($msg, 'admin');
714
            }
715
        } catch (\Exception $e) {
716
            log_error('Bulk order status error', [$e]);
717
            $this->addError('admin.flash.register_failed', 'admin');
718
        }
719
720 2
        return $this->redirectToRoute('admin_order', ['resume' => Constant::ENABLED]);
721
    }
722
723
    /**
724
     * Update to Tracking number.
725
     *
726
     * @Method("PUT")
727
     * @Route("/%eccube_admin_route%/shipping/{id}/tracking_number", requirements={"id" = "\d+"}, name="admin_shipping_update_tracking_number")
728
     *
729
     * @param Request $request
0 ignored issues
show
introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
730
     * @param Shipping $shipping
731
     *
732
     * @return Response
733
     */
734 2
    public function updateTrackingNumber(Request $request, Shipping $shipping)
735
    {
736 2
        if (!($request->isXmlHttpRequest() && $this->isTokenValid())) {
737
            return $this->json(['status' => 'NG'], 400);
738
        }
739
740 2
        $trackingNumber = mb_convert_kana($request->get('tracking_number'), 'a', 'utf-8');
741
        /** @var \Symfony\Component\Validator\ConstraintViolationListInterface $errors */
742 2
        $errors = $this->validator->validate(
743 2
            $trackingNumber,
744
            [
745 2
                new Assert\Length(['max' => $this->eccubeConfig['eccube_stext_len']]),
746 2
                new Assert\Regex(
747 2
                    ['pattern' => '/^[0-9a-zA-Z-]+$/u', 'message' => trans('form.type.admin.nottrackingnumberstyle')]
748
                ),
749
            ]
750
        );
751
752 2
        if ($errors->count() != 0) {
753 1
            log_info('送り状番号入力チェックエラー');
754 1
            $messages = [];
755
            /** @var \Symfony\Component\Validator\ConstraintViolationInterface $error */
756 1
            foreach ($errors as $error) {
757 1
                $messages[] = $error->getMessage();
758
            }
759
760 1
            return $this->json(['status' => 'NG', 'messages' => $messages], 400);
761
        }
762
763
        try {
764 1
            $shipping->setTrackingNumber($trackingNumber);
765 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...
766 1
            log_info('送り状番号変更処理完了', [$shipping->getId()]);
767 1
            $message = ['status' => 'OK', 'shipping_id' => $shipping->getId(), 'tracking_number' => $trackingNumber];
768
769 1
            return $this->json($message);
770
        } catch (\Exception $e) {
771
            log_error('予期しないエラー', [$e->getMessage()]);
772
773
            return $this->json(['status' => 'NG'], 500);
774
        }
775
    }
776
}
777