Failed Conditions
Push — experimental/sf ( fbc478...690bfa )
by Kiyotaka
339:17 queued 330:43
created

OrderController::updateOrderStatus()   F

Complexity

Conditions 14
Paths 327

Size

Total Lines 69

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 29
CRAP Score 18.915

Importance

Changes 0
Metric Value
cc 14
nc 327
nop 2
dl 0
loc 69
ccs 29
cts 41
cp 0.7073
crap 18.915
rs 3.753
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\OrderPdf;
21
use Eccube\Event\EccubeEvents;
22
use Eccube\Event\EventArgs;
23
use Eccube\Form\Type\Admin\OrderPdfType;
24
use Eccube\Form\Type\Admin\SearchOrderType;
25
use Eccube\Repository\CustomerRepository;
26
use Eccube\Repository\Master\OrderStatusRepository;
27
use Eccube\Repository\Master\PageMaxRepository;
28
use Eccube\Repository\Master\ProductStatusRepository;
29
use Eccube\Repository\Master\SexRepository;
30
use Eccube\Repository\OrderPdfRepository;
31
use Eccube\Repository\OrderRepository;
32
use Eccube\Repository\PaymentRepository;
33
use Eccube\Service\CsvExportService;
34
use Eccube\Service\MailService;
35
use Eccube\Service\OrderPdfService;
36
use Eccube\Service\OrderStateMachine;
37
use Eccube\Util\FormUtil;
38
use Knp\Component\Pager\PaginatorInterface;
39
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
40
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
41
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
42
use Symfony\Component\Form\FormBuilder;
43
use Symfony\Component\HttpFoundation\Response;
44
use Symfony\Component\HttpFoundation\Request;
45
use Symfony\Component\HttpFoundation\StreamedResponse;
46
use Eccube\Entity\Master\OrderStatus;
47
use Symfony\Component\HttpFoundation\RedirectResponse;
48
use Eccube\Entity\Order;
49
use Eccube\Entity\Shipping;
50
use Eccube\Service\PurchaseFlow\PurchaseFlow;
51
use Symfony\Component\Validator\Constraints as Assert;
52
use Symfony\Component\Validator\Validator\ValidatorInterface;
53
54
class OrderController extends AbstractController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
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
    protected $orderStateMachine;
116
117
    /**
118
     * @var MailService
119
     */
120
    protected $mailService;
121
122
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$mailService" missing
Loading history...
123
     * OrderController constructor.
124
     *
125
     * @param PurchaseFlow $orderPurchaseFlow
0 ignored issues
show
introduced by
Expected 12 spaces after parameter type; 1 found
Loading history...
126
     * @param CsvExportService $csvExportService
0 ignored issues
show
introduced by
Expected 8 spaces after parameter type; 1 found
Loading history...
127
     * @param CustomerRepository $customerRepository
0 ignored issues
show
introduced by
Expected 6 spaces after parameter type; 1 found
Loading history...
128
     * @param PaymentRepository $paymentRepository
0 ignored issues
show
introduced by
Expected 7 spaces after parameter type; 1 found
Loading history...
129
     * @param SexRepository $sexRepository
0 ignored issues
show
introduced by
Expected 11 spaces after parameter type; 1 found
Loading history...
130
     * @param OrderStatusRepository $orderStatusRepository
0 ignored issues
show
introduced by
Expected 3 spaces after parameter type; 1 found
Loading history...
131
     * @param PageMaxRepository $pageMaxRepository
0 ignored issues
show
introduced by
Expected 7 spaces after parameter type; 1 found
Loading history...
132
     * @param ProductStatusRepository $productStatusRepository
133
     * @param OrderRepository $orderRepository
0 ignored issues
show
introduced by
Expected 9 spaces after parameter type; 1 found
Loading history...
134
     * @param OrderPdfRepository $orderPdfRepository
0 ignored issues
show
introduced by
Expected 6 spaces after parameter type; 1 found
Loading history...
135
     * @param OrderPdfService $orderPdfService
0 ignored issues
show
introduced by
Expected 9 spaces after parameter type; 1 found
Loading history...
136
     * @param ValidatorInterface $validator
0 ignored issues
show
introduced by
Expected 6 spaces after parameter type; 1 found
Loading history...
137
     * @param OrderStateMachine $orderStateMachine ;
0 ignored issues
show
introduced by
Expected 7 spaces after parameter type; 1 found
Loading history...
introduced by
Expected 7 spaces after parameter name; 1 found
Loading history...
138
     */
139 28
    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 28
        $this->purchaseFlow = $orderPurchaseFlow;
156 28
        $this->csvExportService = $csvExportService;
157 28
        $this->customerRepository = $customerRepository;
158 28
        $this->paymentRepository = $paymentRepository;
159 28
        $this->sexRepository = $sexRepository;
160 28
        $this->orderStatusRepository = $orderStatusRepository;
161 28
        $this->pageMaxRepository = $pageMaxRepository;
162 28
        $this->productStatusRepository = $productStatusRepository;
163 28
        $this->orderRepository = $orderRepository;
164 28
        $this->orderPdfRepository = $orderPdfRepository;
165 28
        $this->orderPdfService = $orderPdfService;
166 28
        $this->validator = $validator;
167 28
        $this->orderStateMachine = $orderStateMachine;
168 28
        $this->mailService = $mailService;
169
    }
170
171
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$page_no" missing
Loading history...
introduced by
Doc comment for parameter "$paginator" missing
Loading history...
172
     * 受注一覧画面.
173
     *
174
     * - 検索条件, ページ番号, 表示件数はセッションに保持されます.
175
     * - クエリパラメータでresume=1が指定された場合、検索条件, ページ番号, 表示件数をセッションから復旧します.
176
     * - 各データの, セッションに保持するアクションは以下の通りです.
177
     *   - 検索ボタン押下時
178
     *      - 検索条件をセッションに保存します
179
     *      - ページ番号は1で初期化し、セッションに保存します。
180
     *   - 表示件数変更時
181
     *      - クエリパラメータpage_countをセッションに保存します。
182
     *      - ただし, mtb_page_maxと一致しない場合, eccube_default_page_countが保存されます.
183
     *   - ページング時
184
     *      - URLパラメータpage_noをセッションに保存します.
185
     *   - 初期表示
186
     *      - 検索条件は空配列, ページ番号は1で初期化し, セッションに保存します.
187
     *
188
     * @Route("/%eccube_admin_route%/order", name="admin_order")
189
     * @Route("/%eccube_admin_route%/order/page/{page_no}", requirements={"page_no" = "\d+"}, name="admin_order_page")
190
     * @Template("@admin/Order/index.twig")
191
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
192 10
    public function index(Request $request, $page_no = null, PaginatorInterface $paginator)
0 ignored issues
show
Coding Style introduced by
Parameters which have default values should be placed at the end.

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

// $a must always be passed; it's default value is never used.
function someFunction($a = 5, $b) { }
Loading history...
193
    {
194 10
        $builder = $this->formFactory
195 10
            ->createBuilder(SearchOrderType::class);
196
197 10
        $event = new EventArgs(
198
            [
199 10
                'builder' => $builder,
200
            ],
201 10
            $request
202
        );
203 10
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_INDEX_INITIALIZE, $event);
204
205 10
        $searchForm = $builder->getForm();
206
207
        /**
208
         * ページの表示件数は, 以下の順に優先される.
209
         * - リクエストパラメータ
210
         * - セッション
211
         * - デフォルト値
212
         * また, セッションに保存する際は mtb_page_maxと照合し, 一致した場合のみ保存する.
213
         **/
214 10
        $page_count = $this->session->get('eccube.admin.order.search.page_count',
215 10
            $this->eccubeConfig->get('eccube_default_page_count'));
216
217 10
        $page_count_param = (int) $request->get('page_count');
218 10
        $pageMaxis = $this->pageMaxRepository->findAll();
219
220 10
        if ($page_count_param) {
221 1
            foreach ($pageMaxis as $pageMax) {
222 1
                if ($page_count_param == $pageMax->getName()) {
223
                    $page_count = $pageMax->getName();
224
                    $this->session->set('eccube.admin.order.search.page_count', $page_count);
225 1
                    break;
226
                }
227
            }
228
        }
229
230 10
        if ('POST' === $request->getMethod()) {
231 6
            $searchForm->handleRequest($request);
232
233 6
            if ($searchForm->isValid()) {
234
                /**
235
                 * 検索が実行された場合は, セッションに検索条件を保存する.
236
                 * ページ番号は最初のページ番号に初期化する.
237
                 */
238 5
                $page_no = 1;
239 5
                $searchData = $searchForm->getData();
240
241
                // 検索条件, ページ番号をセッションに保持.
242 5
                $this->session->set('eccube.admin.order.search', FormUtil::getViewData($searchForm));
243 5
                $this->session->set('eccube.admin.order.search.page_no', $page_no);
244
            } else {
245
                // 検索エラーの際は, 詳細検索枠を開いてエラー表示する.
246
                return [
247 6
                    'searchForm' => $searchForm->createView(),
248
                    'pagination' => [],
249 1
                    'pageMaxis' => $pageMaxis,
250 1
                    'page_no' => $page_no,
251 1
                    'page_count' => $page_count,
252
                    'has_errors' => true,
253
                ];
254
            }
255
        } else {
256 5
            if (null !== $page_no || $request->get('resume')) {
257
                /*
258
                 * ページ送りの場合または、他画面から戻ってきた場合は, セッションから検索条件を復旧する.
259
                 */
260 1
                if ($page_no) {
261
                    // ページ送りで遷移した場合.
262 1
                    $this->session->set('eccube.admin.order.search.page_no', (int) $page_no);
263
                } else {
264
                    // 他画面から遷移した場合.
265
                    $page_no = $this->session->get('eccube.admin.order.search.page_no', 1);
266
                }
267 1
                $viewData = $this->session->get('eccube.admin.order.search', []);
268 1
                $searchData = FormUtil::submitAndGetData($searchForm, $viewData);
269
            } else {
270
                /**
271
                 * 初期表示の場合.
272
                 */
273 4
                $page_no = 1;
274 4
                $viewData = [];
275
276 4
                if ($statusId = (int) $request->get('order_status_id')) {
277
                    $viewData = ['status' => $statusId];
278
                }
279
280 4
                $searchData = FormUtil::submitAndGetData($searchForm, $viewData);
281
282
                // セッション中の検索条件, ページ番号を初期化.
283 4
                $this->session->set('eccube.admin.order.search', $viewData);
284 4
                $this->session->set('eccube.admin.order.search.page_no', $page_no);
285
            }
286
        }
287
288 10
        $qb = $this->orderRepository->getQueryBuilderBySearchDataForAdmin($searchData);
289
290 10
        $event = new EventArgs(
291
            [
292 10
                'qb' => $qb,
293 10
                'searchData' => $searchData,
294
            ],
295 10
            $request
296
        );
297
298 10
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_INDEX_SEARCH, $event);
299
300 10
        $pagination = $paginator->paginate(
301 10
            $qb,
302 10
            $page_no,
303 10
            $page_count
304
        );
305
306
        return [
307 10
            'searchForm' => $searchForm->createView(),
308 10
            'pagination' => $pagination,
309 10
            'pageMaxis' => $pageMaxis,
310 10
            'page_no' => $page_no,
311 10
            'page_count' => $page_count,
312
            'has_errors' => false,
313 10
            'OrderStatuses' => $this->orderStatusRepository->findBy([], ['sort_no' => 'ASC']),
314
        ];
315
    }
316
317
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
318
     * @Method("POST")
319
     * @Route("/%eccube_admin_route%/order/bulk_delete", name="admin_order_bulk_delete")
320
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
321 1
    public function bulkDelete(Request $request)
322
    {
323 1
        $this->isTokenValid();
324 1
        $ids = $request->get('ids');
325 1
        foreach ($ids as $order_id) {
326 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...
327 1
                ->find($order_id);
328 1
            if ($Order) {
329 1
                $this->entityManager->remove($Order);
330 1
                log_info('受注削除', [$Order->getId()]);
331
            }
332
        }
333
334 1
        $this->entityManager->flush();
335
336 1
        $this->addSuccess('admin.order.delete.complete', 'admin');
337
338 1
        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 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...
351
    {
352 1
        $filename = 'order_'.(new \DateTime())->format('YmdHis').'.csv';
353 1
        $response = $this->exportCsv($request, CsvType::CSV_TYPE_ORDER, $filename);
354 1
        log_info('受注CSV出力ファイル名', [$filename]);
355
356 1
        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 $fileName
381
     *
382
     * @return StreamedResponse
383
     */
384 1
    private function exportCsv(Request $request, $csvTypeId, $fileName)
385
    {
386
        // タイムアウトを無効にする.
387 1
        set_time_limit(0);
388
389
        // sql loggerを無効にする.
390 1
        $em = $this->entityManager;
391 1
        $em->getConfiguration()->setSQLLogger(null);
392
393 1
        $response = new StreamedResponse();
394 1
        $response->setCallback(function () use ($request, $csvTypeId) {
395
            // CSV種別を元に初期化.
396 1
            $this->csvExportService->initCsvType($csvTypeId);
397
398
            // ヘッダ行の出力.
399 1
            $this->csvExportService->exportHeader();
400
401
            // 受注データ検索用のクエリビルダを取得.
402 1
            $qb = $this->csvExportService
403 1
                ->getOrderQueryBuilder($request);
404
405
            // データ行の出力.
406 1
            $this->csvExportService->setExportQueryBuilder($qb);
407 1
            $this->csvExportService->exportData(function ($entity, $csvService) use ($request) {
408 1
                $Csvs = $csvService->getCsvs();
409
410 1
                $Order = $entity;
411 1
                $OrderItems = $Order->getOrderItems();
412
413 1
                foreach ($OrderItems as $OrderItem) {
414 1
                    $ExportCsvRow = new ExportCsvRow();
415
416
                    // CSV出力項目と合致するデータを取得.
417 1
                    foreach ($Csvs as $Csv) {
418
                        // 受注データを検索.
419 1
                        $ExportCsvRow->setData($csvService->getData($Csv, $Order));
420 1
                        if ($ExportCsvRow->isDataNull()) {
421
                            // 受注データにない場合は, 受注明細を検索.
422 1
                            $ExportCsvRow->setData($csvService->getData($Csv, $OrderItem));
423
                        }
424 1
                        if ($ExportCsvRow->isDataNull() && $Shipping = $OrderItem->getShipping()) {
425
                            // 受注明細データにない場合は, 出荷を検索.
426 1
                            $ExportCsvRow->setData($csvService->getData($Csv, $Shipping));
427
                        }
428
429 1
                        $event = new EventArgs(
430
                            [
431 1
                                'csvService' => $csvService,
432 1
                                'Csv' => $Csv,
433 1
                                'OrderItem' => $OrderItem,
434 1
                                'ExportCsvRow' => $ExportCsvRow,
435
                            ],
436 1
                            $request
437
                        );
438 1
                        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_CSV_EXPORT_ORDER, $event);
439
440 1
                        $ExportCsvRow->pushData();
441
                    }
442
443
                    //$row[] = number_format(memory_get_usage(true));
444
                    // 出力.
445 1
                    $csvService->fputcsv($ExportCsvRow->getRow());
446
                }
447 1
            });
448 1
        });
449
450 1
        $response->headers->set('Content-Type', 'application/octet-stream');
451 1
        $response->headers->set('Content-Disposition', 'attachment; filename='.$fileName);
452 1
        $response->send();
453
454 1
        return $response;
455
    }
456
457
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$Shipping" missing
Loading history...
458
     * Update to order status
459
     *
460
     * @Method("PUT")
461
     * @Route("/%eccube_admin_route%/shipping/{id}/order_status", requirements={"id" = "\d+"}, name="admin_shipping_update_order_status")
462
     *
463
     * @param Request $request
0 ignored issues
show
introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
464
     * @param Shipping $shipping
0 ignored issues
show
Documentation introduced by
There is no parameter named $shipping. Did you maybe mean $Shipping?

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

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

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

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

Loading history...
introduced by
Doc comment for parameter $shipping does not match case of actual variable name $Shipping
Loading history...
465
     *
466
     * @return RedirectResponse
467
     */
468 2
    public function updateOrderStatus(Request $request, Shipping $Shipping)
0 ignored issues
show
introduced by
Declare public methods first, then protected ones and finally private ones
Loading history...
469
    {
470 2
        if (!($request->isXmlHttpRequest() && $this->isTokenValid())) {
471
            return $this->json(['status' => 'NG'], 400);
472
        }
473
474 2
        $Order = $Shipping->getOrder();
475 2
        $OrderStatus = $this->entityManager->find(OrderStatus::class, $request->get('order_status'));
476
477 2
        if (!$OrderStatus) {
478 1
            return $this->json(['status' => 'NG'], 400);
479
        }
480
481 1
        $result = [];
482
        try {
483 1
            if ($Order->getOrderStatus()->getId() == $OrderStatus->getId()) {
484
                log_info('対応状況一括変更スキップ');
485
                $result = ['message' => sprintf('%s:  ステータス変更をスキップしました', $Shipping->getId())];
486
            } else {
487 1
                if ($this->orderStateMachine->can($Order, $OrderStatus)) {
488 1
                    if ($OrderStatus->getId() == OrderStatus::DELIVERED) {
489 1
                        if (!$Shipping->isShipped()) {
490 1
                            $Shipping->setShippingDate(new \DateTime());
491
                        }
492 1
                        $allShipped = true;
493 1
                        foreach ($Order->getShippings() as $Ship) {
494 1
                            if (!$Ship->isShipped()) {
495
                                $allShipped = false;
496 1
                                break;
497
                            }
498
                        }
499 1
                        if ($allShipped) {
500 1
                            $this->orderStateMachine->apply($Order, $OrderStatus);
501
                        }
502
                    } else {
503
                        $this->orderStateMachine->apply($Order, $OrderStatus);
504
                    }
505
506 1
                    if ($request->get('notificationMail')) { // for SimpleStatusUpdate
507 1
                        $this->mailService->sendShippingNotifyMail($Shipping);
508 1
                        $Shipping->setMailSendDate(new \DateTime());
509 1
                        $result['mail'] = true;
510
                    } else {
511
                        $result['mail'] = false;
512
                    }
513 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...
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
516
                    // 会員の場合、購入回数、購入金額などを更新
517 1
                    if ($Customer = $Order->getCustomer()) {
518 1
                        $this->orderRepository->updateOrderSummary($Customer);
519 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...
520
                    }
521
                } else {
522
                    $from = $Order->getOrderStatus()->getName();
523
                    $to = $OrderStatus->getName();
524
                    $result = ['message' => sprintf('%s: %s から %s へのステータス変更はできません', $Shipping->getId(), $from, $to)];
525
                }
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 1
        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
0 ignored issues
show
introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
545
     * @param Shipping $shipping
546
     *
547
     * @return Response
548
     */
549 2
    public function updateTrackingNumber(Request $request, Shipping $shipping)
550
    {
551 2
        if (!($request->isXmlHttpRequest() && $this->isTokenValid())) {
552
            return $this->json(['status' => 'NG'], 400);
553
        }
554
555 2
        $trackingNumber = mb_convert_kana($request->get('tracking_number'), 'a', 'utf-8');
556
        /** @var \Symfony\Component\Validator\ConstraintViolationListInterface $errors */
557 2
        $errors = $this->validator->validate(
558 2
            $trackingNumber,
559
            [
560 2
                new Assert\Length(['max' => $this->eccubeConfig['eccube_stext_len']]),
561 2
                new Assert\Regex(
562 2
                    ['pattern' => '/^[0-9a-zA-Z-]+$/u', 'message' => trans('form.type.admin.nottrackingnumberstyle')]
563
                ),
564
            ]
565
        );
566
567 2
        if ($errors->count() != 0) {
568 1
            log_info('送り状番号入力チェックエラー');
569 1
            $messages = [];
570
            /** @var \Symfony\Component\Validator\ConstraintViolationInterface $error */
571 1
            foreach ($errors as $error) {
572 1
                $messages[] = $error->getMessage();
573
            }
574
575 1
            return $this->json(['status' => 'NG', 'messages' => $messages], 400);
576
        }
577
578
        try {
579 1
            $shipping->setTrackingNumber($trackingNumber);
580 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...
581 1
            log_info('送り状番号変更処理完了', [$shipping->getId()]);
582 1
            $message = ['status' => 'OK', 'shipping_id' => $shipping->getId(), 'tracking_number' => $trackingNumber];
583
584 1
            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 13
    public function exportPdf(Request $request)
601
    {
602
        // requestから出荷番号IDの一覧を取得する.
603 13
        $ids = $request->get('ids', []);
604
605 13
        if (count($ids) == 0) {
606 1
            $this->addError('admin.order.export.pdf.parameter.not.found', 'admin');
607 1
            log_info('The Order cannot found!');
608
609 1
            return $this->redirectToRoute('admin_order');
610
        }
611
612
        /** @var OrderPdf $OrderPdf */
613 12
        $OrderPdf = $this->orderPdfRepository->find($this->getUser());
614
615 12
        if (!$OrderPdf) {
616 11
            $OrderPdf = new OrderPdf();
617
            $OrderPdf
618 11
                ->setTitle(trans('admin.order.export.pdf.title.default'))
619 11
                ->setMessage1(trans('admin.order.export.pdf.message1.default'))
620 11
                ->setMessage2(trans('admin.order.export.pdf.message2.default'))
621 11
                ->setMessage3(trans('admin.order.export.pdf.message3.default'));
622
        }
623
624
        /**
625
         * @var FormBuilder
626
         */
627 12
        $builder = $this->formFactory->createBuilder(OrderPdfType::class, $OrderPdf);
628
629
        /* @var \Symfony\Component\Form\Form $form */
630 12
        $form = $builder->getForm();
631
632
        // Formへの設定
633 12
        $form->get('ids')->setData(implode(',', $ids));
634
635
        return [
636 12
            '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 10
    public function exportPdfDownload(Request $request)
649
    {
650
        /**
651
         * @var FormBuilder
652
         */
653 10
        $builder = $this->formFactory->createBuilder(OrderPdfType::class);
654
655
        /* @var \Symfony\Component\Form\Form $form */
656 10
        $form = $builder->getForm();
657 10
        $form->handleRequest($request);
658
659
        // Validation
660 10
        if (!$form->isValid()) {
661 7
            log_info('The parameter is invalid!');
662
663 7
            return $this->render('@admin/Order/order_pdf.twig', [
664 7
                'form' => $form->createView(),
665
            ]);
666
        }
667
668 3
        $arrData = $form->getData();
669
670
        // 購入情報からPDFを作成する
671 3
        $status = $this->orderPdfService->makePdf($arrData);
672
673
        // 異常終了した場合の処理
674 3
        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 3
        $response = new Response(
685 3
            $this->orderPdfService->outputPdf(),
686 3
            200,
687 3
            ['content-type' => 'application/pdf']
688
        );
689
690 3
        $downloadKind = $form->get('download_kind')->getData();
691
692
        // レスポンスヘッダーにContent-Dispositionをセットし、ファイル名を指定
693 3
        if ($downloadKind == 1) {
694 3
            $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 3
        log_info('OrderPdf download success!', ['Order ID' => implode(',', $request->get('ids', []))]);
700
701 3
        $isDefault = isset($arrData['default']) ? $arrData['default'] : false;
702 3
        if ($isDefault) {
703
            // Save input to DB
704 1
            $arrData['admin'] = $this->getUser();
705 1
            $this->orderPdfRepository->save($arrData);
706
        }
707
708 3
        return $response;
709
    }
710
}
711