Failed Conditions
Pull Request — experimental/sf (#31)
by Kentaro
06:59
created

OrderController::updateOrderStatus()   F

Complexity

Conditions 14
Paths 327

Size

Total Lines 69

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 16.4888

Importance

Changes 0
Metric Value
cc 14
nc 327
nop 2
dl 0
loc 69
rs 3.753
c 0
b 0
f 0
ccs 23
cts 30
cp 0.7667
crap 16.4888

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\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\MailService;
38
use Eccube\Service\OrderPdfService;
39
use Eccube\Service\OrderStateMachine;
40
use Eccube\Service\PurchaseFlow\PurchaseFlow;
41
use Eccube\Util\FormUtil;
42
use Knp\Component\Pager\PaginatorInterface;
43
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
44
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
45
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
46
use Symfony\Component\Form\FormBuilder;
47
use Symfony\Component\HttpFoundation\RedirectResponse;
48
use Symfony\Component\HttpFoundation\Request;
49
use Symfony\Component\HttpFoundation\Response;
50
use Symfony\Component\HttpFoundation\StreamedResponse;
51
use Symfony\Component\Validator\Constraints as Assert;
52
use Symfony\Component\Validator\Validator\ValidatorInterface;
53
54
class OrderController extends AbstractController
55
{
56
    /**
57
     * @var PurchaseFlow
58
     */
59
    protected $purchaseFlow;
60
61
    /**
62
     * @var CsvExportService
63
     */
64
    protected $csvExportService;
65
66
    /**
67
     * @var CustomerRepository
68
     */
69
    protected $customerRepository;
70
71
    /**
72
     * @var PaymentRepository
73
     */
74
    protected $paymentRepository;
75
76
    /**
77
     * @var SexRepository
78
     */
79
    protected $sexRepository;
80
81
    /**
82
     * @var OrderStatusRepository
83
     */
84
    protected $orderStatusRepository;
85
86
    /**
87
     * @var PageMaxRepository
88
     */
89
    protected $pageMaxRepository;
90
91
    /**
92
     * @var ProductStatusRepository
93
     */
94
    protected $productStatusRepository;
95
96
    /**
97
     * @var OrderRepository
98
     */
99
    protected $orderRepository;
100
101
    /** @var OrderPdfRepository */
102
    protected $orderPdfRepository;
103
104
    /** @var OrderPdfService */
105
    protected $orderPdfService;
106
107
    /**
108
     * @var ValidatorInterface
109
     */
110
    protected $validator;
111
112
    /**
113
     * @var OrderStateMachine
114
     */
115 14
    protected $orderStateMachine;
116
117
    /**
118
     * @var MailService
119
     */
120
    protected $mailService;
121
122
    /**
123
     * OrderController constructor.
124
     *
125
     * @param PurchaseFlow $orderPurchaseFlow
126
     * @param CsvExportService $csvExportService
127 14
     * @param CustomerRepository $customerRepository
128 14
     * @param PaymentRepository $paymentRepository
129 14
     * @param SexRepository $sexRepository
130 14
     * @param OrderStatusRepository $orderStatusRepository
131 14
     * @param PageMaxRepository $pageMaxRepository
132 14
     * @param ProductStatusRepository $productStatusRepository
133 14
     * @param OrderRepository $orderRepository
134 14
     * @param OrderPdfRepository $orderPdfRepository
135 14
     * @param OrderPdfService $orderPdfService
136 14
     * @param ValidatorInterface $validator
137
     * @param OrderStateMachine $orderStateMachine ;
138
     */
139
    public function __construct(
140
        PurchaseFlow $orderPurchaseFlow,
141
        CsvExportService $csvExportService,
142
        CustomerRepository $customerRepository,
143
        PaymentRepository $paymentRepository,
144
        SexRepository $sexRepository,
145
        OrderStatusRepository $orderStatusRepository,
146
        PageMaxRepository $pageMaxRepository,
147
        ProductStatusRepository $productStatusRepository,
148
        OrderRepository $orderRepository,
149
        OrderPdfRepository $orderPdfRepository,
150
        OrderPdfService $orderPdfService,
151
        ValidatorInterface $validator,
152
        OrderStateMachine $orderStateMachine,
153
        MailService $mailService
154
    ) {
155
        $this->purchaseFlow = $orderPurchaseFlow;
156
        $this->csvExportService = $csvExportService;
157
        $this->customerRepository = $customerRepository;
158
        $this->paymentRepository = $paymentRepository;
159
        $this->sexRepository = $sexRepository;
160 8
        $this->orderStatusRepository = $orderStatusRepository;
161
        $this->pageMaxRepository = $pageMaxRepository;
162 8
        $this->productStatusRepository = $productStatusRepository;
163 8
        $this->orderRepository = $orderRepository;
164
        $this->orderPdfRepository = $orderPdfRepository;
165 8
        $this->orderPdfService = $orderPdfService;
166
        $this->validator = $validator;
167 8
        $this->orderStateMachine = $orderStateMachine;
168
        $this->mailService = $mailService;
169 8
    }
170
171 8
    /**
172
     * 受注一覧画面.
173 8
     *
174
     * - 検索条件, ページ番号, 表示件数はセッションに保持されます.
175
     * - クエリパラメータでresume=1が指定された場合、検索条件, ページ番号, 表示件数をセッションから復旧します.
176
     * - 各データの, セッションに保持するアクションは以下の通りです.
177
     *   - 検索ボタン押下時
178
     *      - 検索条件をセッションに保存します
179
     *      - ページ番号は1で初期化し、セッションに保存します。
180
     *   - 表示件数変更時
181
     *      - クエリパラメータpage_countをセッションに保存します。
182 8
     *      - ただし, mtb_page_maxと一致しない場合, eccube_default_page_countが保存されます.
183 8
     *   - ページング時
184
     *      - URLパラメータpage_noをセッションに保存します.
185 8
     *   - 初期表示
186 8
     *      - 検索条件は空配列, ページ番号は1で初期化し, セッションに保存します.
187
     *
188 8
     * @Route("/%eccube_admin_route%/order", name="admin_order")
189 1
     * @Route("/%eccube_admin_route%/order/page/{page_no}", requirements={"page_no" = "\d+"}, name="admin_order_page")
190 1
     * @Template("@admin/Order/index.twig")
191
     */
192
    public function index(Request $request, $page_no = null, PaginatorInterface $paginator)
193 1
    {
194
        $builder = $this->formFactory
195
            ->createBuilder(SearchOrderType::class);
196
197
        $event = new EventArgs(
198 8
            [
199 6
                'builder' => $builder,
200
            ],
201 6
            $request
202
        );
203
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_INDEX_INITIALIZE, $event);
204
205
        $searchForm = $builder->getForm();
206 5
207 5
        /**
208
         * ページの表示件数は, 以下の順に優先される.
209
         * - リクエストパラメータ
210 5
         * - セッション
211 5
         * - デフォルト値
212
         * また, セッションに保存する際は mtb_page_maxと照合し, 一致した場合のみ保存する.
213
         **/
214
        $page_count = $this->session->get('eccube.admin.order.search.page_count',
215 6
            $this->eccubeConfig->get('eccube_default_page_count'));
216
217 1
        $page_count_param = (int) $request->get('page_count');
218 1
        $pageMaxis = $this->pageMaxRepository->findAll();
219 1
220 View Code Duplication
        if ($page_count_param) {
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...
221
            foreach ($pageMaxis as $pageMax) {
222
                if ($page_count_param == $pageMax->getName()) {
223
                    $page_count = $pageMax->getName();
224 3
                    $this->session->set('eccube.admin.order.search.page_count', $page_count);
225
                    break;
226
                }
227
            }
228 1
        }
229
230 1
        if ('POST' === $request->getMethod()) {
231
            $searchForm->handleRequest($request);
232
233 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...
234
                /**
235 1
                 * 検索が実行された場合は, セッションに検索条件を保存する.
236 1
                 * ページ番号は最初のページ番号に初期化する.
237
                 */
238
                $page_no = 1;
239
                $searchData = $searchForm->getData();
240
241 2
                // 検索条件, ページ番号をセッションに保持.
242 2
                $this->session->set('eccube.admin.order.search', FormUtil::getViewData($searchForm));
243
                $this->session->set('eccube.admin.order.search.page_no', $page_no);
244 2
            } else {
245
                // 検索エラーの際は, 詳細検索枠を開いてエラー表示する.
246
                return [
247
                    'searchForm' => $searchForm->createView(),
248 2
                    'pagination' => [],
249
                    'pageMaxis' => $pageMaxis,
250
                    'page_no' => $page_no,
251 2
                    'page_count' => $page_count,
252 2
                    'has_errors' => true,
253
                ];
254
            }
255
        } else {
256 8
            if (null !== $page_no || $request->get('resume')) {
257
                /*
258 8
                 * ページ送りの場合または、他画面から戻ってきた場合は, セッションから検索条件を復旧する.
259
                 */
260 8
                if ($page_no) {
261 8
                    // ページ送りで遷移した場合.
262
                    $this->session->set('eccube.admin.order.search.page_no', (int) $page_no);
263 8
                } else {
264
                    // 他画面から遷移した場合.
265
                    $page_no = $this->session->get('eccube.admin.order.search.page_no', 1);
266 8
                }
267
                $viewData = $this->session->get('eccube.admin.order.search', []);
268 8
                $searchData = FormUtil::submitAndGetData($searchForm, $viewData);
269 8
            } else {
270 8
                /**
271 8
                 * 初期表示の場合.
272
                 */
273
                $page_no = 1;
274
                $viewData = [];
275 8
276 8
                if ($statusId = (int) $request->get('order_status_id')) {
277 8
                    $viewData = ['status' => $statusId];
278 8
                }
279 8
280
                $searchData = FormUtil::submitAndGetData($searchForm, $viewData);
281 8
282
                // セッション中の検索条件, ページ番号を初期化.
283
                $this->session->set('eccube.admin.order.search', $viewData);
284
                $this->session->set('eccube.admin.order.search.page_no', $page_no);
285
            }
286
        }
287
288
        $qb = $this->orderRepository->getQueryBuilderBySearchDataForAdmin($searchData);
289 1
290
        $event = new EventArgs(
291 1
            [
292 1
                'qb' => $qb,
293 1
                'searchData' => $searchData,
294 1
            ],
295 1
            $request
296 1
        );
297 1
298 1
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_INDEX_SEARCH, $event);
299
300
        $pagination = $paginator->paginate(
301
            $qb,
302 1
            $page_no,
303
            $page_count
304 1
        );
305
306 1
        return [
307
            'searchForm' => $searchForm->createView(),
308
            'pagination' => $pagination,
309
            'pageMaxis' => $pageMaxis,
310
            'page_no' => $page_no,
311
            'page_count' => $page_count,
312
            'has_errors' => false,
313
            'OrderStatuses' => $this->orderStatusRepository->findBy([], ['sort_no' => 'ASC']),
314
        ];
315
    }
316
317
    /**
318 1
     * @Method("POST")
319
     * @Route("/%eccube_admin_route%/order/bulk_delete", name="admin_order_bulk_delete")
320
     */
321 1
    public function bulkDelete(Request $request)
322
    {
323
        $this->isTokenValid();
324 1
        $ids = $request->get('ids');
325 1
        foreach ($ids as $order_id) {
326
            $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...
327 1
                ->find($order_id);
328 1
            if ($Order) {
329
                $this->entityManager->remove($Order);
330 1
                log_info('受注削除', [$Order->getId()]);
331
            }
332
        }
333
334
        $this->entityManager->flush();
335
336
        $this->addSuccess('admin.order.delete.complete', 'admin');
337
338
        return $this->redirect($this->generateUrl('admin_order', ['resume' => Constant::ENABLED]));
339
    }
340
341
    /**
342
     * 受注CSVの出力.
343
     *
344
     * @Route("/%eccube_admin_route%/order/export/order", name="admin_order_export_order")
345
     *
346
     * @param Request $request
347
     *
348
     * @return StreamedResponse
349
     */
350 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...
351
    {
352
        $filename = 'order_'.(new \DateTime())->format('YmdHis').'.csv';
353
        $response = $this->exportCsv($request, CsvType::CSV_TYPE_ORDER, $filename);
354
        log_info('受注CSV出力ファイル名', [$filename]);
355
356
        return $response;
357
    }
358
359
    /**
360
     * 配送CSVの出力.
361
     *
362
     * @Route("/%eccube_admin_route%/order/export/shipping", name="admin_order_export_shipping")
363
     *
364
     * @param Request $request
365
     *
366
     * @return StreamedResponse
367
     */
368 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...
369
    {
370
        $filename = 'shipping_'.(new \DateTime())->format('YmdHis').'.csv';
371
        $response = $this->exportCsv($request, CsvType::CSV_TYPE_SHIPPING, $filename);
372
        log_info('配送CSV出力ファイル名', [$filename]);
373
374
        return $response;
375
    }
376
377
    /**
378
     * @param Request $request
379
     * @param $csvTypeId
380
     * @param string $fileName
381
     *
382 1
     * @return StreamedResponse
383
     */
384 1
    private function exportCsv(Request $request, $csvTypeId, $fileName)
385 1
    {
386 1
        // タイムアウトを無効にする.
387 1
        set_time_limit(0);
388 1
389
        // sql loggerを無効にする.
390
        $em = $this->entityManager;
391
        $em->getConfiguration()->setSQLLogger(null);
392
393
        $response = new StreamedResponse();
394
        $response->setCallback(function () use ($request, $csvTypeId) {
395
            // CSV種別を元に初期化.
396
            $this->csvExportService->initCsvType($csvTypeId);
397
398
            // ヘッダ行の出力.
399
            $this->csvExportService->exportHeader();
400
401
            // 受注データ検索用のクエリビルダを取得.
402
            $qb = $this->csvExportService
403
                ->getOrderQueryBuilder($request);
404
405
            // データ行の出力.
406 2
            $this->csvExportService->setExportQueryBuilder($qb);
407
            $this->csvExportService->exportData(function ($entity, $csvService) use ($request) {
408 2
                $Csvs = $csvService->getCsvs();
409
410
                $Order = $entity;
411 2
                $OrderItems = $Order->getOrderItems();
412
413 2
                foreach ($OrderItems as $OrderItem) {
414 2
                    $ExportCsvRow = new ExportCsvRow();
415
416
                    // CSV出力項目と合致するデータを取得.
417
                    foreach ($Csvs as $Csv) {
418 2
                        // 受注データを検索.
419
                        $ExportCsvRow->setData($csvService->getData($Csv, $Order));
420 2
                        if ($ExportCsvRow->isDataNull()) {
421
                            // 受注データにない場合は, 受注明細を検索.
422 2
                            $ExportCsvRow->setData($csvService->getData($Csv, $OrderItem));
423
                        }
424 2
                        if ($ExportCsvRow->isDataNull() && $Shipping = $OrderItem->getShipping()) {
425 2
                            // 受注明細データにない場合は, 出荷を検索.
426
                            $ExportCsvRow->setData($csvService->getData($Csv, $Shipping));
427
                        }
428
429
                        $event = new EventArgs(
430
                            [
431
                                'csvService' => $csvService,
432
                                'Csv' => $Csv,
433
                                'OrderItem' => $OrderItem,
434
                                'ExportCsvRow' => $ExportCsvRow,
435 2
                            ],
436
                            $request
437
                        );
438
                        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_CSV_EXPORT_ORDER, $event);
439
440
                        $ExportCsvRow->pushData();
441
                    }
442
443
                    //$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...
444
                    // 出力.
445
                    $csvService->fputcsv($ExportCsvRow->getRow());
446
                }
447 2
            });
448
        });
449
450
        $response->headers->set('Content-Type', 'application/octet-stream');
451
        $response->headers->set('Content-Disposition', 'attachment; filename='.$fileName);
452
        $response->send();
453
454
        return $response;
455
    }
456
457 2
    /**
458
     * Update to order status
459 2
     *
460
     * @Method("PUT")
461 2
     * @Route("/%eccube_admin_route%/shipping/{id}/order_status", requirements={"id" = "\d+"}, name="admin_shipping_update_order_status")
462
     *
463
     * @param Request $request
464
     * @param Shipping $Shipping
465 2
     *
466 2
     * @return \Symfony\Component\HttpFoundation\JsonResponse
467 2
     */
468 2
    public function updateOrderStatus(Request $request, Shipping $Shipping)
469 2
    {
470
        if (!($request->isXmlHttpRequest() && $this->isTokenValid())) {
471 2
            return $this->json(['status' => 'NG'], 400);
472
        }
473
474
        $Order = $Shipping->getOrder();
475
        $OrderStatus = $this->entityManager->find(OrderStatus::class, $request->get('order_status'));
476
477
        if (!$OrderStatus) {
478 2
            return $this->json(['status' => 'NG'], 400);
479
        }
480
481
        $result = [];
482
        try {
483
            if ($Order->getOrderStatus()->getId() == $OrderStatus->getId()) {
484
                log_info('対応状況一括変更スキップ');
485
                $result = ['message' => sprintf('%s:  ステータス変更をスキップしました', $Shipping->getId())];
486
            } else {
487
                if ($this->orderStateMachine->can($Order, $OrderStatus)) {
488
                    if ($OrderStatus->getId() == OrderStatus::DELIVERED) {
489
                        if (!$Shipping->isShipped()) {
490
                            $Shipping->setShippingDate(new \DateTime());
491
                        }
492 2
                        $allShipped = true;
493
                        foreach ($Order->getShippings() as $Ship) {
494 2
                            if (!$Ship->isShipped()) {
495
                                $allShipped = false;
496
                                break;
497
                            }
498 2
                        }
499
                        if ($allShipped) {
500 2
                            $this->orderStateMachine->apply($Order, $OrderStatus);
501 2
                        }
502
                    } else {
503 2
                        $this->orderStateMachine->apply($Order, $OrderStatus);
504 2
                    }
505 2
506
                    if ($request->get('notificationMail')) { // for SimpleStatusUpdate
507
                        $this->mailService->sendShippingNotifyMail($Shipping);
508
                        $Shipping->setMailSendDate(new \DateTime());
509
                        $result['mail'] = true;
510 2
                    } else {
511 1
                        $result['mail'] = false;
512 1
                    }
513
                    $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...
514 1
                    $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...
515 1
516
                    // 会員の場合、購入回数、購入金額などを更新
517
                    if ($Customer = $Order->getCustomer()) {
518 1
                        $this->orderRepository->updateOrderSummary($Customer);
519
                        $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...
520
                    }
521
                } else {
522 1
                    $from = $Order->getOrderStatus()->getName();
523 1
                    $to = $OrderStatus->getName();
524 1
                    $result = ['message' => sprintf('%s: %s から %s へのステータス変更はできません', $Shipping->getId(), $from, $to)];
525 1
                }
526
527 1
                log_info('対応状況一括変更処理完了', [$Order->getId()]);
528
            }
529
        } catch (\Exception $e) {
530
            log_error('予期しないエラーです', [$e->getMessage()]);
531
532
            return $this->json(['status' => 'NG'], 500);
533
        }
534
535
        return $this->json(array_merge(['status' => 'OK'], $result));
536
    }
537
538
    /**
539
     * Update to Tracking number.
540
     *
541
     * @Method("PUT")
542
     * @Route("/%eccube_admin_route%/shipping/{id}/tracking_number", requirements={"id" = "\d+"}, name="admin_shipping_update_tracking_number")
543
     *
544
     * @param Request $request
545
     * @param Shipping $shipping
546
     *
547
     * @return Response
548
     */
549
    public function updateTrackingNumber(Request $request, Shipping $shipping)
550
    {
551
        if (!($request->isXmlHttpRequest() && $this->isTokenValid())) {
552
            return $this->json(['status' => 'NG'], 400);
553
        }
554
555
        $trackingNumber = mb_convert_kana($request->get('tracking_number'), 'a', 'utf-8');
556
        /** @var \Symfony\Component\Validator\ConstraintViolationListInterface $errors */
557
        $errors = $this->validator->validate(
558
            $trackingNumber,
559
            [
560
                new Assert\Length(['max' => $this->eccubeConfig['eccube_stext_len']]),
561
                new Assert\Regex(
562
                    ['pattern' => '/^[0-9a-zA-Z-]+$/u', 'message' => trans('form.type.admin.nottrackingnumberstyle')]
563
                ),
564
            ]
565
        );
566
567
        if ($errors->count() != 0) {
568
            log_info('送り状番号入力チェックエラー');
569
            $messages = [];
570
            /** @var \Symfony\Component\Validator\ConstraintViolationInterface $error */
571
            foreach ($errors as $error) {
572
                $messages[] = $error->getMessage();
573
            }
574
575
            return $this->json(['status' => 'NG', 'messages' => $messages], 400);
576
        }
577
578
        try {
579
            $shipping->setTrackingNumber($trackingNumber);
580
            $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...
581
            log_info('送り状番号変更処理完了', [$shipping->getId()]);
582
            $message = ['status' => 'OK', 'shipping_id' => $shipping->getId(), 'tracking_number' => $trackingNumber];
583
584
            return $this->json($message);
585
        } catch (\Exception $e) {
586
            log_error('予期しないエラー', [$e->getMessage()]);
587
588
            return $this->json(['status' => 'NG'], 500);
589
        }
590
    }
591
592
    /**
593
     * @Route("/%eccube_admin_route%/order/export/pdf", name="admin_order_export_pdf")
594
     * @Template("@admin/Order/order_pdf.twig")
595
     *
596
     * @param Request $request
597
     *
598
     * @return array|RedirectResponse
599
     */
600
    public function exportPdf(Request $request)
601
    {
602
        // requestから出荷番号IDの一覧を取得する.
603
        $ids = $request->get('ids', []);
604
605
        if (count($ids) == 0) {
606
            $this->addError('admin.order.export.pdf.parameter.not.found', 'admin');
607
            log_info('The Order cannot found!');
608
609
            return $this->redirectToRoute('admin_order');
610
        }
611
612
        /** @var OrderPdf $OrderPdf */
613
        $OrderPdf = $this->orderPdfRepository->find($this->getUser());
614
615
        if (!$OrderPdf) {
616
            $OrderPdf = new OrderPdf();
617
            $OrderPdf
618
                ->setTitle(trans('admin.order.export.pdf.title.default'))
619
                ->setMessage1(trans('admin.order.export.pdf.message1.default'))
620
                ->setMessage2(trans('admin.order.export.pdf.message2.default'))
621
                ->setMessage3(trans('admin.order.export.pdf.message3.default'));
622
        }
623
624
        /**
625
         * @var FormBuilder
626
         */
627
        $builder = $this->formFactory->createBuilder(OrderPdfType::class, $OrderPdf);
628
629
        /* @var \Symfony\Component\Form\Form $form */
630
        $form = $builder->getForm();
631
632
        // Formへの設定
633
        $form->get('ids')->setData(implode(',', $ids));
634
635
        return [
636
            'form' => $form->createView(),
637
        ];
638
    }
639
640
    /**
641
     * @Route("/%eccube_admin_route%/order/export/pdf/download", name="admin_order_pdf_download")
642
     * @Template("@admin/Order/order_pdf.twig")
643
     *
644
     * @param Request $request
645
     *
646
     * @return Response
647
     */
648
    public function exportPdfDownload(Request $request)
649
    {
650
        /**
651
         * @var FormBuilder
652
         */
653
        $builder = $this->formFactory->createBuilder(OrderPdfType::class);
654
655
        /* @var \Symfony\Component\Form\Form $form */
656
        $form = $builder->getForm();
657
        $form->handleRequest($request);
658
659
        // Validation
660
        if (!$form->isValid()) {
661
            log_info('The parameter is invalid!');
662
663
            return $this->render('@admin/Order/order_pdf.twig', [
664
                'form' => $form->createView(),
665
            ]);
666
        }
667
668
        $arrData = $form->getData();
669
670
        // 購入情報からPDFを作成する
671
        $status = $this->orderPdfService->makePdf($arrData);
672
673
        // 異常終了した場合の処理
674
        if (!$status) {
675
            $this->addError('admin.order.export.pdf.download.failure', 'admin');
676
            log_info('Unable to create pdf files! Process have problems!');
677
678
            return $this->render('@admin/Order/order_pdf.twig', [
679
                'form' => $form->createView(),
680
            ]);
681
        }
682
683
        // ダウンロードする
684
        $response = new Response(
685
            $this->orderPdfService->outputPdf(),
686
            200,
687
            ['content-type' => 'application/pdf']
688
        );
689
690
        $downloadKind = $form->get('download_kind')->getData();
691
692
        // レスポンスヘッダーにContent-Dispositionをセットし、ファイル名を指定
693
        if ($downloadKind == 1) {
694
            $response->headers->set('Content-Disposition', 'attachment; filename="'.$this->orderPdfService->getPdfFileName().'"');
695
        } else {
696
            $response->headers->set('Content-Disposition', 'inline; filename="'.$this->orderPdfService->getPdfFileName().'"');
697
        }
698
699
        log_info('OrderPdf download success!', ['Order ID' => implode(',', $request->get('ids', []))]);
700
701
        $isDefault = isset($arrData['default']) ? $arrData['default'] : false;
702
        if ($isDefault) {
703
            // Save input to DB
704
            $arrData['admin'] = $this->getUser();
705
            $this->orderPdfRepository->save($arrData);
706
        }
707
708
        return $response;
709
    }
710
}
711