Completed
Push — 4.0 ( 5c2237...836544 )
by Ryo
06:47
created

OrderController::index()   C

Complexity

Conditions 10
Paths 24

Size

Total Lines 124

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 51
CRAP Score 10.0384

Importance

Changes 0
Metric Value
cc 10
nc 24
nop 3
dl 0
loc 124
ccs 51
cts 55
cp 0.9273
crap 10.0384
rs 6.1333
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\ExportCsvRow;
19
use Eccube\Entity\Master\CsvType;
20
use Eccube\Entity\Master\OrderStatus;
21
use Eccube\Entity\OrderPdf;
22
use Eccube\Entity\Shipping;
23
use Eccube\Event\EccubeEvents;
24
use Eccube\Event\EventArgs;
25
use Eccube\Form\Type\Admin\OrderPdfType;
26
use Eccube\Form\Type\Admin\SearchOrderType;
27
use Eccube\Repository\CustomerRepository;
28
use Eccube\Repository\Master\OrderStatusRepository;
29
use Eccube\Repository\Master\PageMaxRepository;
30
use Eccube\Repository\Master\ProductStatusRepository;
31
use Eccube\Repository\Master\SexRepository;
32
use Eccube\Repository\OrderPdfRepository;
33
use Eccube\Repository\OrderRepository;
34
use Eccube\Repository\PaymentRepository;
35
use Eccube\Repository\ProductStockRepository;
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\Template;
44
use Symfony\Component\Form\FormBuilder;
45
use Symfony\Component\HttpFoundation\RedirectResponse;
46
use Symfony\Component\HttpFoundation\Request;
47
use Symfony\Component\HttpFoundation\Response;
48
use Symfony\Component\HttpFoundation\StreamedResponse;
49
use Symfony\Component\Routing\Annotation\Route;
50
use Symfony\Component\Validator\Constraints as Assert;
51
use Symfony\Component\Validator\Validator\ValidatorInterface;
52
53
class OrderController extends AbstractController
54
{
55
    /**
56
     * @var PurchaseFlow
57
     */
58
    protected $purchaseFlow;
59
60
    /**
61
     * @var CsvExportService
62
     */
63
    protected $csvExportService;
64
65
    /**
66
     * @var CustomerRepository
67
     */
68
    protected $customerRepository;
69
70
    /**
71
     * @var PaymentRepository
72
     */
73
    protected $paymentRepository;
74
75
    /**
76
     * @var SexRepository
77
     */
78
    protected $sexRepository;
79
80
    /**
81
     * @var OrderStatusRepository
82
     */
83
    protected $orderStatusRepository;
84
85
    /**
86
     * @var PageMaxRepository
87
     */
88
    protected $pageMaxRepository;
89
90
    /**
91
     * @var ProductStatusRepository
92
     */
93
    protected $productStatusRepository;
94
95
    /**
96
     * @var OrderRepository
97
     */
98
    protected $orderRepository;
99
100
    /** @var OrderPdfRepository */
101
    protected $orderPdfRepository;
102
103
    /**
104
     * @var ProductStockRepository
105
     */
106
    protected $productStockRepository;
107
108
    /** @var OrderPdfService */
109
    protected $orderPdfService;
110
111
    /**
112
     * @var ValidatorInterface
113
     */
114
    protected $validator;
115
116
    /**
117
     * @var OrderStateMachine
118
     */
119
    protected $orderStateMachine;
120
121
    /**
122
     * @var MailService
123
     */
124
    protected $mailService;
125
126
    /**
127
     * OrderController constructor.
128
     *
129
     * @param PurchaseFlow $orderPurchaseFlow
130
     * @param CsvExportService $csvExportService
131
     * @param CustomerRepository $customerRepository
132
     * @param PaymentRepository $paymentRepository
133
     * @param SexRepository $sexRepository
134
     * @param OrderStatusRepository $orderStatusRepository
135
     * @param PageMaxRepository $pageMaxRepository
136
     * @param ProductStatusRepository $productStatusRepository
137
     * @param ProductStockRepository $productStockRepository
138
     * @param OrderRepository $orderRepository
139 28
     * @param OrderPdfRepository $orderPdfRepository
140
     * @param OrderPdfService $orderPdfService
141
     * @param ValidatorInterface $validator
142
     * @param OrderStateMachine $orderStateMachine ;
143
     */
144
    public function __construct(
145
        PurchaseFlow $orderPurchaseFlow,
146
        CsvExportService $csvExportService,
147
        CustomerRepository $customerRepository,
148
        PaymentRepository $paymentRepository,
149
        SexRepository $sexRepository,
150
        OrderStatusRepository $orderStatusRepository,
151
        PageMaxRepository $pageMaxRepository,
152
        ProductStatusRepository $productStatusRepository,
153
        ProductStockRepository $productStockRepository,
154
        OrderRepository $orderRepository,
155 28
        OrderPdfRepository $orderPdfRepository,
156 28
        OrderPdfService $orderPdfService,
157 28
        ValidatorInterface $validator,
158 28
        OrderStateMachine $orderStateMachine,
159 28
        MailService $mailService
160 28
    ) {
161 28
        $this->purchaseFlow = $orderPurchaseFlow;
162 28
        $this->csvExportService = $csvExportService;
163 28
        $this->customerRepository = $customerRepository;
164 28
        $this->paymentRepository = $paymentRepository;
165 28
        $this->sexRepository = $sexRepository;
166 28
        $this->orderStatusRepository = $orderStatusRepository;
167 28
        $this->pageMaxRepository = $pageMaxRepository;
168 28
        $this->productStatusRepository = $productStatusRepository;
169
        $this->productStockRepository = $productStockRepository;
170
        $this->orderRepository = $orderRepository;
171
        $this->orderPdfRepository = $orderPdfRepository;
172
        $this->orderPdfService = $orderPdfService;
173
        $this->validator = $validator;
174
        $this->orderStateMachine = $orderStateMachine;
175
        $this->mailService = $mailService;
176
    }
177
178
    /**
179
     * 受注一覧画面.
180
     *
181
     * - 検索条件, ページ番号, 表示件数はセッションに保持されます.
182
     * - クエリパラメータでresume=1が指定された場合、検索条件, ページ番号, 表示件数をセッションから復旧します.
183
     * - 各データの, セッションに保持するアクションは以下の通りです.
184
     *   - 検索ボタン押下時
185
     *      - 検索条件をセッションに保存します
186
     *      - ページ番号は1で初期化し、セッションに保存します。
187
     *   - 表示件数変更時
188
     *      - クエリパラメータpage_countをセッションに保存します。
189
     *      - ただし, mtb_page_maxと一致しない場合, eccube_default_page_countが保存されます.
190
     *   - ページング時
191
     *      - URLパラメータpage_noをセッションに保存します.
192 10
     *   - 初期表示
193
     *      - 検索条件は空配列, ページ番号は1で初期化し, セッションに保存します.
194 10
     *
195 10
     * @Route("/%eccube_admin_route%/order", name="admin_order")
196
     * @Route("/%eccube_admin_route%/order/page/{page_no}", requirements={"page_no" = "\d+"}, name="admin_order_page")
197 10
     * @Template("@admin/Order/index.twig")
198
     */
199 10
    public function index(Request $request, $page_no = null, PaginatorInterface $paginator)
200
    {
201 10
        $builder = $this->formFactory
202
            ->createBuilder(SearchOrderType::class);
203 10
204
        $event = new EventArgs(
205 10
            [
206
                'builder' => $builder,
207
            ],
208
            $request
209
        );
210
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_INDEX_INITIALIZE, $event);
211
212
        $searchForm = $builder->getForm();
213
214 10
        /**
215 10
         * ページの表示件数は, 以下の順に優先される.
216
         * - リクエストパラメータ
217 10
         * - セッション
218 10
         * - デフォルト値
219
         * また, セッションに保存する際は mtb_page_maxと照合し, 一致した場合のみ保存する.
220 10
         **/
221 1
        $page_count = $this->session->get('eccube.admin.order.search.page_count',
222 1
            $this->eccubeConfig->get('eccube_default_page_count'));
223
224
        $page_count_param = (int) $request->get('page_count');
225 1
        $pageMaxis = $this->pageMaxRepository->findAll();
226
227
        if ($page_count_param) {
228
            foreach ($pageMaxis as $pageMax) {
229
                if ($page_count_param == $pageMax->getName()) {
230 10
                    $page_count = $pageMax->getName();
231 6
                    $this->session->set('eccube.admin.order.search.page_count', $page_count);
232
                    break;
233 6
                }
234
            }
235
        }
236
237
        if ('POST' === $request->getMethod()) {
238 5
            $searchForm->handleRequest($request);
239 5
240
            if ($searchForm->isValid()) {
241
                /**
242 5
                 * 検索が実行された場合は, セッションに検索条件を保存する.
243 5
                 * ページ番号は最初のページ番号に初期化する.
244
                 */
245
                $page_no = 1;
246
                $searchData = $searchForm->getData();
247 6
248
                // 検索条件, ページ番号をセッションに保持.
249 1
                $this->session->set('eccube.admin.order.search', FormUtil::getViewData($searchForm));
250 1
                $this->session->set('eccube.admin.order.search.page_no', $page_no);
251 1
            } else {
252
                // 検索エラーの際は, 詳細検索枠を開いてエラー表示する.
253
                return [
254
                    'searchForm' => $searchForm->createView(),
255
                    'pagination' => [],
256 5
                    'pageMaxis' => $pageMaxis,
257
                    'page_no' => $page_no,
258
                    'page_count' => $page_count,
259
                    'has_errors' => true,
260 1
                ];
261
            }
262 1
        } else {
263
            if (null !== $page_no || $request->get('resume')) {
264
                /*
265
                 * ページ送りの場合または、他画面から戻ってきた場合は, セッションから検索条件を復旧する.
266
                 */
267 1
                if ($page_no) {
268 1
                    // ページ送りで遷移した場合.
269
                    $this->session->set('eccube.admin.order.search.page_no', (int) $page_no);
270
                } else {
271
                    // 他画面から遷移した場合.
272
                    $page_no = $this->session->get('eccube.admin.order.search.page_no', 1);
273 4
                }
274 4
                $viewData = $this->session->get('eccube.admin.order.search', []);
275
                $searchData = FormUtil::submitAndGetData($searchForm, $viewData);
276 4
            } else {
277
                /**
278
                 * 初期表示の場合.
279
                 */
280 4
                $page_no = 1;
281
                $viewData = [];
282
283 4
                if ($statusId = (int) $request->get('order_status_id')) {
284 4
                    $viewData = ['status' => $statusId];
285
                }
286
287
                $searchData = FormUtil::submitAndGetData($searchForm, $viewData);
288 10
289
                // セッション中の検索条件, ページ番号を初期化.
290 10
                $this->session->set('eccube.admin.order.search', $viewData);
291
                $this->session->set('eccube.admin.order.search.page_no', $page_no);
292 10
            }
293 10
        }
294
295 10
        $qb = $this->orderRepository->getQueryBuilderBySearchDataForAdmin($searchData);
296
297
        $event = new EventArgs(
298 10
            [
299
                'qb' => $qb,
300 10
                'searchData' => $searchData,
301 10
            ],
302 10
            $request
303 10
        );
304
305
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_INDEX_SEARCH, $event);
306
307 10
        $pagination = $paginator->paginate(
308 10
            $qb,
309 10
            $page_no,
310 10
            $page_count
311 10
        );
312
313 10
        return [
314
            'searchForm' => $searchForm->createView(),
315
            'pagination' => $pagination,
316
            'pageMaxis' => $pageMaxis,
317
            'page_no' => $page_no,
318
            'page_count' => $page_count,
319
            'has_errors' => false,
320
            'OrderStatuses' => $this->orderStatusRepository->findBy([], ['sort_no' => 'ASC']),
321 1
        ];
322
    }
323 1
324 1
    /**
325 1
     * @Route("/%eccube_admin_route%/order/bulk_delete", name="admin_order_bulk_delete", methods={"POST"})
326 1
     */
327 1
    public function bulkDelete(Request $request)
328 1
    {
329 1
        $this->isTokenValid();
330 1
        $ids = $request->get('ids');
331
        foreach ($ids as $order_id) {
332
            $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...
333
                ->find($order_id);
334 1
            if ($Order) {
335
                $this->entityManager->remove($Order);
336 1
                log_info('受注削除', [$Order->getId()]);
337
            }
338 1
        }
339
340
        $this->entityManager->flush();
341
342
        $this->addSuccess('admin.order.delete.complete', 'admin');
343
344
        return $this->redirect($this->generateUrl('admin_order', ['resume' => Constant::ENABLED]));
345
    }
346
347
    /**
348
     * 受注CSVの出力.
349
     *
350 1
     * @Route("/%eccube_admin_route%/order/export/order", name="admin_order_export_order")
351
     *
352 1
     * @param Request $request
353 1
     *
354 1
     * @return StreamedResponse
355
     */
356 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...
357
    {
358
        $filename = 'order_'.(new \DateTime())->format('YmdHis').'.csv';
359
        $response = $this->exportCsv($request, CsvType::CSV_TYPE_ORDER, $filename);
360
        log_info('受注CSV出力ファイル名', [$filename]);
361
362
        return $response;
363
    }
364
365
    /**
366
     * 配送CSVの出力.
367
     *
368
     * @Route("/%eccube_admin_route%/order/export/shipping", name="admin_order_export_shipping")
369
     *
370
     * @param Request $request
371
     *
372
     * @return StreamedResponse
373
     */
374 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...
375
    {
376
        $filename = 'shipping_'.(new \DateTime())->format('YmdHis').'.csv';
377
        $response = $this->exportCsv($request, CsvType::CSV_TYPE_SHIPPING, $filename);
378
        log_info('配送CSV出力ファイル名', [$filename]);
379
380
        return $response;
381
    }
382
383
    /**
384 1
     * @param Request $request
385
     * @param $csvTypeId
386
     * @param string $fileName
387 1
     *
388
     * @return StreamedResponse
389
     */
390 1
    private function exportCsv(Request $request, $csvTypeId, $fileName)
391 1
    {
392
        // タイムアウトを無効にする.
393 1
        set_time_limit(0);
394 1
395
        // sql loggerを無効にする.
396 1
        $em = $this->entityManager;
397
        $em->getConfiguration()->setSQLLogger(null);
398
399 1
        $response = new StreamedResponse();
400
        $response->setCallback(function () use ($request, $csvTypeId) {
401
            // CSV種別を元に初期化.
402 1
            $this->csvExportService->initCsvType($csvTypeId);
403 1
404
            // ヘッダ行の出力.
405
            $this->csvExportService->exportHeader();
406 1
407 1
            // 受注データ検索用のクエリビルダを取得.
408 1
            $qb = $this->csvExportService
409
                ->getOrderQueryBuilder($request);
410 1
411 1
            // データ行の出力.
412
            $this->csvExportService->setExportQueryBuilder($qb);
413 1
            $this->csvExportService->exportData(function ($entity, $csvService) use ($request) {
414 1
                $Csvs = $csvService->getCsvs();
415
416
                $Order = $entity;
417 1
                $OrderItems = $Order->getOrderItems();
418
419 1
                foreach ($OrderItems as $OrderItem) {
420 1
                    $ExportCsvRow = new ExportCsvRow();
421
422 1
                    // CSV出力項目と合致するデータを取得.
423
                    foreach ($Csvs as $Csv) {
424 1
                        // 受注データを検索.
425
                        $ExportCsvRow->setData($csvService->getData($Csv, $Order));
426 1
                        if ($ExportCsvRow->isDataNull()) {
427
                            // 受注データにない場合は, 受注明細を検索.
428
                            $ExportCsvRow->setData($csvService->getData($Csv, $OrderItem));
429 1
                        }
430
                        if ($ExportCsvRow->isDataNull() && $Shipping = $OrderItem->getShipping()) {
431 1
                            // 受注明細データにない場合は, 出荷を検索.
432 1
                            $ExportCsvRow->setData($csvService->getData($Csv, $Shipping));
433 1
                        }
434 1
435
                        $event = new EventArgs(
436 1
                            [
437
                                'csvService' => $csvService,
438 1
                                'Csv' => $Csv,
439
                                'OrderItem' => $OrderItem,
440 1
                                'ExportCsvRow' => $ExportCsvRow,
441
                            ],
442
                            $request
443
                        );
444
                        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_CSV_EXPORT_ORDER, $event);
445 1
446
                        $ExportCsvRow->pushData();
447 1
                    }
448 1
449
                    //$row[] = number_format(memory_get_usage(true));
450 1
                    // 出力.
451 1
                    $csvService->fputcsv($ExportCsvRow->getRow());
452 1
                }
453
            });
454 1
        });
455
456
        $response->headers->set('Content-Type', 'application/octet-stream');
457
        $response->headers->set('Content-Disposition', 'attachment; filename='.$fileName);
458
        $response->send();
459
460
        return $response;
461
    }
462
463
    /**
464
     * Update to order status
465
     *
466
     * @Route("/%eccube_admin_route%/shipping/{id}/order_status", requirements={"id" = "\d+"}, name="admin_shipping_update_order_status", methods={"PUT"})
467
     *
468 2
     * @param Request $request
469
     * @param Shipping $Shipping
470 2
     *
471
     * @return \Symfony\Component\HttpFoundation\JsonResponse
472
     */
473
    public function updateOrderStatus(Request $request, Shipping $Shipping)
474 2
    {
475 2
        if (!($request->isXmlHttpRequest() && $this->isTokenValid())) {
476
            return $this->json(['status' => 'NG'], 400);
477 2
        }
478 1
479
        $Order = $Shipping->getOrder();
480
        $OrderStatus = $this->entityManager->find(OrderStatus::class, $request->get('order_status'));
481 1
482
        if (!$OrderStatus) {
483 1
            return $this->json(['status' => 'NG'], 400);
484
        }
485
486
        $result = [];
487 1
        try {
488 1
            if ($Order->getOrderStatus()->getId() == $OrderStatus->getId()) {
489 1
                log_info('対応状況一括変更スキップ');
490 1
                $result = ['message' => sprintf('%s:  ステータス変更をスキップしました', $Shipping->getId())];
491
            } else {
492 1
                if ($this->orderStateMachine->can($Order, $OrderStatus)) {
493 1
                    if ($OrderStatus->getId() == OrderStatus::DELIVERED) {
494 1
                        if (!$Shipping->isShipped()) {
495
                            $Shipping->setShippingDate(new \DateTime());
496 1
                        }
497
                        $allShipped = true;
498
                        foreach ($Order->getShippings() as $Ship) {
499 1
                            if (!$Ship->isShipped()) {
500 1
                                $allShipped = false;
501
                                break;
502
                            }
503
                        }
504
                        if ($allShipped) {
505
                            $this->orderStateMachine->apply($Order, $OrderStatus);
506 1
                        }
507 1
                    } else {
508 1
                        $this->orderStateMachine->apply($Order, $OrderStatus);
509 1
                    }
510
511
                    if ($request->get('notificationMail')) { // for SimpleStatusUpdate
512
                        $this->mailService->sendShippingNotifyMail($Shipping);
513 1
                        $Shipping->setMailSendDate(new \DateTime());
514 1
                        $result['mail'] = true;
515
                    } else {
516
                        $result['mail'] = false;
517 1
                    }
518 1
                    // 対応中・キャンセルの更新時は商品在庫を増減させているので商品情報を更新
519 1
                    if ($OrderStatus->getId() == OrderStatus::IN_PROGRESS || $OrderStatus->getId() == OrderStatus::CANCEL) {
520
                        foreach ($Order->getOrderItems() as $OrderItem) {
521
                            $ProductClass = $OrderItem->getProductClass();
522
                            if ($OrderItem->isProduct() && !$ProductClass->isStockUnlimited()) {
523
                                $this->entityManager->flush($ProductClass);
0 ignored issues
show
Unused Code introduced by
The call to EntityManagerInterface::flush() has too many arguments starting with $ProductClass.

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...
524
                                $ProductStock = $this->productStockRepository->findOneBy(['ProductClass' => $ProductClass]);
525
                                $this->entityManager->flush($ProductStock);
0 ignored issues
show
Unused Code introduced by
The call to EntityManagerInterface::flush() has too many arguments starting with $ProductStock.

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...
526
                            }
527 1
                        }
528
                    }
529
                    $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...
530
                    $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...
531
532
                    // 会員の場合、購入回数、購入金額などを更新
533
                    if ($Customer = $Order->getCustomer()) {
534
                        $this->orderRepository->updateOrderSummary($Customer);
535 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...
536
                    }
537
                } else {
538
                    $from = $Order->getOrderStatus()->getName();
539
                    $to = $OrderStatus->getName();
540
                    $result = ['message' => sprintf('%s: %s から %s へのステータス変更はできません', $Shipping->getId(), $from, $to)];
541
                }
542
543
                log_info('対応状況一括変更処理完了', [$Order->getId()]);
544
            }
545
        } catch (\Exception $e) {
546
            log_error('予期しないエラーです', [$e->getMessage()]);
547
548
            return $this->json(['status' => 'NG'], 500);
549 2
        }
550
551 2
        return $this->json(array_merge(['status' => 'OK'], $result));
552
    }
553
554
    /**
555 2
     * Update to Tracking number.
556
     *
557 2
     * @Route("/%eccube_admin_route%/shipping/{id}/tracking_number", requirements={"id" = "\d+"}, name="admin_shipping_update_tracking_number", methods={"PUT"})
558 2
     *
559
     * @param Request $request
560 2
     * @param Shipping $shipping
561 2
     *
562 2
     * @return Response
563
     */
564
    public function updateTrackingNumber(Request $request, Shipping $shipping)
565
    {
566
        if (!($request->isXmlHttpRequest() && $this->isTokenValid())) {
567 2
            return $this->json(['status' => 'NG'], 400);
568 1
        }
569 1
570
        $trackingNumber = mb_convert_kana($request->get('tracking_number'), 'a', 'utf-8');
571 1
        /** @var \Symfony\Component\Validator\ConstraintViolationListInterface $errors */
572 1
        $errors = $this->validator->validate(
573
            $trackingNumber,
574
            [
575 1
                new Assert\Length(['max' => $this->eccubeConfig['eccube_stext_len']]),
576
                new Assert\Regex(
577
                    ['pattern' => '/^[0-9a-zA-Z-]+$/u', 'message' => trans('form.type.admin.nottrackingnumberstyle')]
578
                ),
579 1
            ]
580 1
        );
581 1
582 1
        if ($errors->count() != 0) {
583
            log_info('送り状番号入力チェックエラー');
584 1
            $messages = [];
585
            /** @var \Symfony\Component\Validator\ConstraintViolationInterface $error */
586
            foreach ($errors as $error) {
587
                $messages[] = $error->getMessage();
588
            }
589
590
            return $this->json(['status' => 'NG', 'messages' => $messages], 400);
591
        }
592
593
        try {
594
            $shipping->setTrackingNumber($trackingNumber);
595
            $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...
596
            log_info('送り状番号変更処理完了', [$shipping->getId()]);
597
            $message = ['status' => 'OK', 'shipping_id' => $shipping->getId(), 'tracking_number' => $trackingNumber];
598
599
            return $this->json($message);
600 13
        } catch (\Exception $e) {
601
            log_error('予期しないエラー', [$e->getMessage()]);
602
603 13
            return $this->json(['status' => 'NG'], 500);
604
        }
605 13
    }
606 1
607 1
    /**
608
     * @Route("/%eccube_admin_route%/order/export/pdf", name="admin_order_export_pdf")
609 1
     * @Template("@admin/Order/order_pdf.twig")
610
     *
611
     * @param Request $request
612
     *
613 12
     * @return array|RedirectResponse
614
     */
615 12
    public function exportPdf(Request $request)
616 11
    {
617
        // requestから出荷番号IDの一覧を取得する.
618 11
        $ids = $request->get('ids', []);
619 11
620 11
        if (count($ids) == 0) {
621 11
            $this->addError('admin.order.export.pdf.parameter.not.found', 'admin');
622
            log_info('The Order cannot found!');
623
624
            return $this->redirectToRoute('admin_order');
625
        }
626
627 12
        /** @var OrderPdf $OrderPdf */
628
        $OrderPdf = $this->orderPdfRepository->find($this->getUser());
629
630 12
        if (!$OrderPdf) {
631
            $OrderPdf = new OrderPdf();
632
            $OrderPdf
633 12
                ->setTitle(trans('admin.order.export.pdf.title.default'))
634
                ->setMessage1(trans('admin.order.export.pdf.message1.default'))
635
                ->setMessage2(trans('admin.order.export.pdf.message2.default'))
636 12
                ->setMessage3(trans('admin.order.export.pdf.message3.default'));
637
        }
638
639
        /**
640
         * @var FormBuilder
641
         */
642
        $builder = $this->formFactory->createBuilder(OrderPdfType::class, $OrderPdf);
643
644
        /* @var \Symfony\Component\Form\Form $form */
645
        $form = $builder->getForm();
646
647
        // Formへの設定
648 10
        $form->get('ids')->setData(implode(',', $ids));
649
650
        return [
651
            'form' => $form->createView(),
652
        ];
653 10
    }
654
655
    /**
656 10
     * @Route("/%eccube_admin_route%/order/export/pdf/download", name="admin_order_pdf_download")
657 10
     * @Template("@admin/Order/order_pdf.twig")
658
     *
659
     * @param Request $request
660 10
     *
661 7
     * @return Response
662
     */
663 7
    public function exportPdfDownload(Request $request)
664 7
    {
665
        /**
666
         * @var FormBuilder
667
         */
668 3
        $builder = $this->formFactory->createBuilder(OrderPdfType::class);
669
670
        /* @var \Symfony\Component\Form\Form $form */
671 3
        $form = $builder->getForm();
672
        $form->handleRequest($request);
673
674 3
        // Validation
675
        if (!$form->isValid()) {
676
            log_info('The parameter is invalid!');
677
678
            return $this->render('@admin/Order/order_pdf.twig', [
679
                'form' => $form->createView(),
680
            ]);
681
        }
682
683
        $arrData = $form->getData();
684 3
685 3
        // 購入情報からPDFを作成する
686 3
        $status = $this->orderPdfService->makePdf($arrData);
687 3
688
        // 異常終了した場合の処理
689
        if (!$status) {
690 3
            $this->addError('admin.order.export.pdf.download.failure', 'admin');
691
            log_info('Unable to create pdf files! Process have problems!');
692
693 3
            return $this->render('@admin/Order/order_pdf.twig', [
694 3
                'form' => $form->createView(),
695
            ]);
696
        }
697
698
        // ダウンロードする
699 3
        $response = new Response(
700
            $this->orderPdfService->outputPdf(),
701 3
            200,
702 3
            ['content-type' => 'application/pdf']
703
        );
704 1
705 1
        $downloadKind = $form->get('download_kind')->getData();
706
707
        // レスポンスヘッダーにContent-Dispositionをセットし、ファイル名を指定
708 3
        if ($downloadKind == 1) {
709
            $response->headers->set('Content-Disposition', 'attachment; filename="'.$this->orderPdfService->getPdfFileName().'"');
710
        } else {
711
            $response->headers->set('Content-Disposition', 'inline; filename="'.$this->orderPdfService->getPdfFileName().'"');
712
        }
713
714
        log_info('OrderPdf download success!', ['Order ID' => implode(',', $request->get('ids', []))]);
715
716
        $isDefault = isset($arrData['default']) ? $arrData['default'] : false;
717
        if ($isDefault) {
718
            // Save input to DB
719
            $arrData['admin'] = $this->getUser();
720
            $this->orderPdfRepository->save($arrData);
721
        }
722
723
        return $response;
724
    }
725
}
726