Failed Conditions
Pull Request — experimental/sf (#29)
by Kentaro
50:12 queued 39:05
created

OrderController::bulkOrderStatus()   C

Complexity

Conditions 10
Paths 260

Size

Total Lines 74

Duplication

Lines 8
Ratio 10.81 %

Code Coverage

Tests 22
CRAP Score 21.65

Importance

Changes 0
Metric Value
cc 10
nc 260
nop 2
dl 8
loc 74
rs 5.4339
c 0
b 0
f 0
ccs 22
cts 43
cp 0.5116
crap 21.65

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