Completed
Push — sf/fix-composer17 ( 4beee7...e56c5b )
by Kiyotaka
187:50 queued 181:44
created

EditController   B

Complexity

Total Complexity 48

Size/Duplication

Total Lines 603
Duplicated Lines 2.32 %

Coupling/Cohesion

Components 1
Dependencies 33

Test Coverage

Coverage 83.08%

Importance

Changes 0
Metric Value
dl 14
loc 603
rs 8.5569
c 0
b 0
f 0
ccs 221
cts 266
cp 0.8308
wmc 48
lcom 1
cbo 33

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 29 1
F index() 6 194 23
B searchCustomerHtml() 0 83 7
B searchCustomerById() 0 53 5
B searchProduct() 8 84 8
A searchOrderItemType() 0 29 4

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like EditController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use EditController, and based on these observations, apply Extract Interface, too.

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 Doctrine\Common\Collections\ArrayCollection;
17
use Doctrine\Common\Collections\Criteria;
18
use Eccube\Controller\AbstractController;
19
use Eccube\Entity\Customer;
20
use Eccube\Entity\Master\CustomerStatus;
21
use Eccube\Entity\Master\OrderItemType;
22
use Eccube\Entity\Master\OrderStatus;
23
use Eccube\Entity\Order;
24
use Eccube\Entity\Shipping;
25
use Eccube\Event\EccubeEvents;
26
use Eccube\Event\EventArgs;
27
use Eccube\Form\Type\AddCartType;
28
use Eccube\Form\Type\Admin\OrderType;
29
use Eccube\Form\Type\Admin\SearchCustomerType;
30
use Eccube\Form\Type\Admin\SearchProductType;
31
use Eccube\Repository\CategoryRepository;
32
use Eccube\Repository\CustomerRepository;
33
use Eccube\Repository\DeliveryRepository;
34
use Eccube\Repository\Master\DeviceTypeRepository;
35
use Eccube\Repository\Master\OrderItemTypeRepository;
36
use Eccube\Repository\Master\OrderStatusRepository;
37
use Eccube\Repository\OrderRepository;
38
use Eccube\Repository\ProductRepository;
39
use Eccube\Service\OrderStateMachine;
40
use Eccube\Service\PurchaseFlow\Processor\OrderNoProcessor;
41
use Eccube\Service\PurchaseFlow\PurchaseContext;
42
use Eccube\Service\PurchaseFlow\PurchaseException;
43
use Eccube\Service\PurchaseFlow\PurchaseFlow;
44
use Eccube\Service\TaxRuleService;
45
use Knp\Component\Pager\Paginator;
46
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
47
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
48
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
49
use Symfony\Component\HttpFoundation\Request;
50
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
51
use Symfony\Component\Serializer\Serializer;
52
use Symfony\Component\Serializer\SerializerInterface;
53
54
class EditController extends AbstractController
55
{
56
    /**
57
     * @var TaxRuleService
58
     */
59
    protected $taxRuleService;
60
61
    /**
62
     * @var DeviceTypeRepository
63
     */
64
    protected $deviceTypeRepository;
65
66
    /**
67
     * @var ProductRepository
68
     */
69
    protected $productRepository;
70
71
    /**
72
     * @var CategoryRepository
73
     */
74
    protected $categoryRepository;
75
76
    /**
77
     * @var CustomerRepository
78
     */
79
    protected $customerRepository;
80
81
    /**
82
     * @var Serializer
83
     */
84
    protected $serializer;
85
86
    /**
87
     * @var DeliveryRepository
88
     */
89
    protected $deliveryRepository;
90
91
    /**
92
     * @var PurchaseFlow
93
     */
94
    protected $purchaseFlow;
95
96
    /**
97
     * @var OrderRepository
98
     */
99
    protected $orderRepository;
100
101
    /**
102
     * @var OrderNoProcessor
103
     */
104
    protected $orderNoProcessor;
105
106
    /**
107
     * @var OrderItemTypeRepository
108
     */
109
    protected $orderItemTypeRepository;
110
111
    /**
112
     * @var OrderStateMachine
113
     */
114
    protected $orderStateMachine;
115
116
    /**
117
     * @var OrderStatusRepository
118
     */
119
    protected $orderStatusRepository;
120
121
    /**
122
     * EditController constructor.
123
     *
124
     * @param TaxRuleService $taxRuleService
125
     * @param DeviceTypeRepository $deviceTypeRepository
126
     * @param ProductRepository $productRepository
127
     * @param CategoryRepository $categoryRepository
128
     * @param CustomerRepository $customerRepository
129
     * @param SerializerInterface $serializer
130
     * @param DeliveryRepository $deliveryRepository
131
     * @param PurchaseFlow $orderPurchaseFlow
132
     * @param OrderRepository $orderRepository
133
     * @param OrderNoProcessor $orderNoProcessor
134
     */
135 10
    public function __construct(
136
        TaxRuleService $taxRuleService,
137
        DeviceTypeRepository $deviceTypeRepository,
138
        ProductRepository $productRepository,
139
        CategoryRepository $categoryRepository,
140
        CustomerRepository $customerRepository,
141
        SerializerInterface $serializer,
142
        DeliveryRepository $deliveryRepository,
143
        PurchaseFlow $orderPurchaseFlow,
144
        OrderRepository $orderRepository,
145
        OrderNoProcessor $orderNoProcessor,
146
        OrderItemTypeRepository $orderItemTypeRepository,
147
        OrderStatusRepository $orderStatusRepository,
148
        OrderStateMachine $orderStateMachine
149
    ) {
150 10
        $this->taxRuleService = $taxRuleService;
151 10
        $this->deviceTypeRepository = $deviceTypeRepository;
152 10
        $this->productRepository = $productRepository;
153 10
        $this->categoryRepository = $categoryRepository;
154 10
        $this->customerRepository = $customerRepository;
155 10
        $this->serializer = $serializer;
0 ignored issues
show
Documentation Bug introduced by
$serializer is of type object<Symfony\Component...er\SerializerInterface>, but the property $serializer was declared to be of type object<Symfony\Component\Serializer\Serializer>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
156 10
        $this->deliveryRepository = $deliveryRepository;
157 10
        $this->purchaseFlow = $orderPurchaseFlow;
158 10
        $this->orderRepository = $orderRepository;
159 10
        $this->orderNoProcessor = $orderNoProcessor;
160 10
        $this->orderItemTypeRepository = $orderItemTypeRepository;
161 10
        $this->orderStatusRepository = $orderStatusRepository;
162 10
        $this->orderStateMachine = $orderStateMachine;
163
    }
164
165
    /**
166
     * 受注登録/編集画面.
167
     *
168
     * @Route("/%eccube_admin_route%/order/new", name="admin_order_new")
169
     * @Route("/%eccube_admin_route%/order/{id}/edit", requirements={"id" = "\d+"}, name="admin_order_edit")
170
     * @Template("@admin/Order/edit.twig")
171
     */
172 7
    public function index(Request $request, $id = null)
173
    {
174 7
        $TargetOrder = null;
0 ignored issues
show
Unused Code introduced by
$TargetOrder is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
175 7
        $OriginOrder = null;
0 ignored issues
show
Unused Code introduced by
$OriginOrder is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
176
177 7
        if (null === $id) {
178
            // 空のエンティティを作成.
179 3
            $TargetOrder = new Order();
180 3
            $TargetOrder->addShipping((new Shipping())->setOrder($TargetOrder));
181
        } else {
182 4
            $TargetOrder = $this->orderRepository->find($id);
183 4
            if (null === $TargetOrder) {
184
                throw new NotFoundHttpException();
185
            }
186
        }
187
188
        // 編集前の受注情報を保持
189 7
        $OriginOrder = clone $TargetOrder;
190 7
        $OriginItems = new ArrayCollection();
191 7
        foreach ($TargetOrder->getOrderItems() as $Item) {
192 4
            $OriginItems->add($Item);
193
        }
194
195 7
        $builder = $this->formFactory->createBuilder(OrderType::class, $TargetOrder);
196
197 7
        $event = new EventArgs(
198
            [
199 7
                'builder' => $builder,
200 7
                'OriginOrder' => $OriginOrder,
201 7
                'TargetOrder' => $TargetOrder,
202
            ],
203 7
            $request
204
        );
205 7
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_INDEX_INITIALIZE, $event);
206
207 7
        $form = $builder->getForm();
208
209 7
        $form->handleRequest($request);
210 7
        $purchaseContext = new PurchaseContext($OriginOrder, $OriginOrder->getCustomer());
211
212 7
        if ($form->isSubmitted() && $form['OrderItems']->isValid()) {
213 5
            $event = new EventArgs(
214
                [
215 5
                    'builder' => $builder,
216 5
                    'OriginOrder' => $OriginOrder,
217 5
                    'TargetOrder' => $TargetOrder,
218 5
                    'PurchaseContext' => $purchaseContext,
219
                ],
220 5
                $request
221
            );
222 5
            $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_INDEX_PROGRESS, $event);
223
224 5
            $flowResult = $this->purchaseFlow->validate($TargetOrder, $purchaseContext);
225
226 5
            if ($flowResult->hasWarning()) {
227
                foreach ($flowResult->getWarning() as $warning) {
228
                    $this->addWarning($warning->getMessage(), 'admin');
229
                }
230
            }
231
232 5
            if ($flowResult->hasError()) {
233
                foreach ($flowResult->getErrors() as $error) {
234
                    $this->addError($error->getMessage(), 'admin');
235
                }
236
            }
237
238
            // 登録ボタン押下
239 5
            switch ($request->get('mode')) {
240
                case 'register':
241 5
                    log_info('受注登録開始', [$TargetOrder->getId()]);
242
243 5
                    if (!$flowResult->hasError() && $form->isValid()) {
244
                        try {
245 5
                            $this->purchaseFlow->prepare($TargetOrder, $purchaseContext);
246 5
                            $this->purchaseFlow->commit($TargetOrder, $purchaseContext);
247
                        } catch (PurchaseException $e) {
248
                            $this->addError($e->getMessage(), 'admin');
249
                            break;
250
                        }
251
252 5
                        $OldStatus = $OriginOrder->getOrderStatus();
253 5
                        $NewStatus = $TargetOrder->getOrderStatus();
254
255
                        // ステータスが変更されている場合はステートマシンを実行.
256 5
                        if ($TargetOrder->getId() && $OldStatus->getId() != $NewStatus->getId()) {
257
                            // 発送済に変更された場合は, 発送日をセットする.
258 3
                            if ($NewStatus->getId() == OrderStatus::DELIVERED) {
259
                                $TargetOrder->getShippings()->map(function (Shipping $Shipping) {
260
                                    if (!$Shipping->isShipped()) {
261
                                        $Shipping->setShippingDate(new \DateTime());
262
                                    }
263
                                });
264
                            }
265
                            // ステートマシンでステータスは更新されるので, 古いステータスに戻す.
266 3
                            $TargetOrder->setOrderStatus($OldStatus);
267
                            // FormTypeでステータスの遷移チェックは行っているのでapplyのみ実行.
268 3
                            $this->orderStateMachine->apply($TargetOrder, $NewStatus);
269
                        }
270
271 5
                        $this->entityManager->persist($TargetOrder);
272 5
                        $this->entityManager->flush();
273
274 5
                        foreach ($OriginItems as $Item) {
275 3
                            if ($TargetOrder->getOrderItems()->contains($Item) === false) {
276 3
                                $this->entityManager->remove($Item);
277
                            }
278
                        }
279 5
                        $this->entityManager->flush();
280
281
                        // 新規登録時はMySQL対応のためflushしてから採番
282 5
                        $this->orderNoProcessor->process($TargetOrder, $purchaseContext);
283 5
                        $this->entityManager->flush();
284
285
                        // 会員の場合、購入回数、購入金額などを更新
286 5
                        if ($Customer = $TargetOrder->getCustomer()) {
287 5
                            $this->orderRepository->updateOrderSummary($Customer);
288 5
                            $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...
289
                        }
290
291 5
                        $event = new EventArgs(
292
                            [
293 5
                                'form' => $form,
294 5
                                'OriginOrder' => $OriginOrder,
295 5
                                'TargetOrder' => $TargetOrder,
296 5
                                'Customer' => $Customer,
297
                            ],
298 5
                            $request
299
                        );
300 5
                        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_INDEX_COMPLETE, $event);
301
302 5
                        $this->addSuccess('admin.order.save.complete', 'admin');
303
304 5
                        log_info('受注登録完了', [$TargetOrder->getId()]);
305
306 5
                        return $this->redirectToRoute('admin_order_edit', ['id' => $TargetOrder->getId()]);
307
                    }
308
309
                    break;
310
                default:
311
                    break;
312
            }
313
        }
314
315
        // 会員検索フォーム
316 2
        $builder = $this->formFactory
317 2
            ->createBuilder(SearchCustomerType::class);
318
319 2
        $event = new EventArgs(
320
            [
321 2
                'builder' => $builder,
322 2
                'OriginOrder' => $OriginOrder,
323 2
                'TargetOrder' => $TargetOrder,
324
            ],
325 2
            $request
326
        );
327 2
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_CUSTOMER_INITIALIZE, $event);
328
329 2
        $searchCustomerModalForm = $builder->getForm();
330
331
        // 商品検索フォーム
332 2
        $builder = $this->formFactory
333 2
            ->createBuilder(SearchProductType::class);
334
335 2
        $event = new EventArgs(
336
            [
337 2
                'builder' => $builder,
338 2
                'OriginOrder' => $OriginOrder,
339 2
                'TargetOrder' => $TargetOrder,
340
            ],
341 2
            $request
342
        );
343 2
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_PRODUCT_INITIALIZE, $event);
344
345 2
        $searchProductModalForm = $builder->getForm();
346
347
        // 配送業者のお届け時間
348 2
        $times = [];
349 2
        $deliveries = $this->deliveryRepository->findAll();
350 2 View Code Duplication
        foreach ($deliveries as $Delivery) {
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...
351 2
            $deliveryTiems = $Delivery->getDeliveryTimes();
352 2
            foreach ($deliveryTiems as $DeliveryTime) {
353 2
                $times[$Delivery->getId()][$DeliveryTime->getId()] = $DeliveryTime->getDeliveryTime();
354
            }
355
        }
356
357
        return [
358 2
            'form' => $form->createView(),
359 2
            'searchCustomerModalForm' => $searchCustomerModalForm->createView(),
360 2
            'searchProductModalForm' => $searchProductModalForm->createView(),
361 2
            'Order' => $TargetOrder,
362 2
            'id' => $id,
363 2
            'shippingDeliveryTimes' => $this->serializer->serialize($times, 'json'),
364
        ];
365
    }
366
367
    /**
368
     * 顧客情報を検索する.
369
     *
370
     * @Route("/%eccube_admin_route%/order/search/customer/html", name="admin_order_search_customer_html")
371
     * @Route("/%eccube_admin_route%/order/search/customer/html/page/{page_no}", requirements={"page_No" = "\d+"}, name="admin_order_search_customer_html_page")
372
     * @Template("@admin/Order/search_customer.twig")
373
     *
374
     * @param Request $request
375
     * @param integer $page_no
376
     *
377
     * @return \Symfony\Component\HttpFoundation\JsonResponse
378
     */
379 1
    public function searchCustomerHtml(Request $request, $page_no = null, Paginator $paginator)
380
    {
381 1
        if ($request->isXmlHttpRequest() && $this->isTokenValid()) {
382 1
            log_debug('search customer start.');
383 1
            $page_count = $this->eccubeConfig['eccube_default_page_count'];
384 1
            $session = $this->session;
385
386 1
            if ('POST' === $request->getMethod()) {
387 1
                $page_no = 1;
388
389
                $searchData = [
390 1
                    'multi' => $request->get('search_word'),
391
                    'customer_status' => [
392 1
                        CustomerStatus::REGULAR,
393
                    ],
394
                ];
395
396 1
                $session->set('eccube.admin.order.customer.search', $searchData);
397 1
                $session->set('eccube.admin.order.customer.search.page_no', $page_no);
398
            } else {
399
                $searchData = (array) $session->get('eccube.admin.order.customer.search');
400
                if (is_null($page_no)) {
401
                    $page_no = intval($session->get('eccube.admin.order.customer.search.page_no'));
402
                } else {
403
                    $session->set('eccube.admin.order.customer.search.page_no', $page_no);
404
                }
405
            }
406
407 1
            $qb = $this->customerRepository->getQueryBuilderBySearchData($searchData);
408
409 1
            $event = new EventArgs(
410
                [
411 1
                    'qb' => $qb,
412 1
                    'data' => $searchData,
413
                ],
414 1
                $request
415
            );
416 1
            $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_CUSTOMER_SEARCH, $event);
417
418
            /** @var \Knp\Component\Pager\Pagination\SlidingPagination $pagination */
419 1
            $pagination = $paginator->paginate(
420 1
                $qb,
421 1
                $page_no,
422 1
                $page_count,
423 1
                ['wrap-queries' => true]
424
            );
425
426
            /** @var $Customers \Eccube\Entity\Customer[] */
427 1
            $Customers = $pagination->getItems();
428
429 1
            if (empty($Customers)) {
430
                log_debug('search customer not found.');
431
            }
432
433 1
            $data = [];
434 1
            $formatName = '%s%s(%s%s)';
435 1
            foreach ($Customers as $Customer) {
436 1
                $data[] = [
437 1
                    'id' => $Customer->getId(),
438 1
                    'name' => sprintf($formatName, $Customer->getName01(), $Customer->getName02(),
439 1
                        $Customer->getKana01(),
440 1
                        $Customer->getKana02()),
441 1
                    'phone_number' => $Customer->getPhoneNumber(),
442 1
                    'email' => $Customer->getEmail(),
443
                ];
444
            }
445
446 1
            $event = new EventArgs(
447
                [
448 1
                    'data' => $data,
449 1
                    'Customers' => $pagination,
450
                ],
451 1
                $request
452
            );
453 1
            $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_CUSTOMER_COMPLETE, $event);
454 1
            $data = $event->getArgument('data');
455
456
            return [
457 1
                'data' => $data,
458 1
                'pagination' => $pagination,
459
            ];
460
        }
461
    }
462
463
    /**
464
     * 顧客情報を検索する.
465
     *
466
     * @Method("POST")
467
     * @Route("/%eccube_admin_route%/order/search/customer/id", name="admin_order_search_customer_by_id")
468
     *
469
     * @param Request $request
470
     *
471
     * @return \Symfony\Component\HttpFoundation\JsonResponse
472
     */
473 1
    public function searchCustomerById(Request $request)
474
    {
475 1
        if ($request->isXmlHttpRequest() && $this->isTokenValid()) {
476 1
            log_debug('search customer by id start.');
477
478
            /** @var $Customer \Eccube\Entity\Customer */
479 1
            $Customer = $this->customerRepository
480 1
                ->find($request->get('id'));
481
482 1
            $event = new EventArgs(
483
                [
484 1
                    'Customer' => $Customer,
485
                ],
486 1
                $request
487
            );
488 1
            $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_CUSTOMER_BY_ID_INITIALIZE, $event);
489
490 1
            if (is_null($Customer)) {
491
                log_debug('search customer by id not found.');
492
493
                return $this->json([], 404);
494
            }
495
496 1
            log_debug('search customer by id found.');
497
498
            $data = [
499 1
                'id' => $Customer->getId(),
500 1
                'name01' => $Customer->getName01(),
501 1
                'name02' => $Customer->getName02(),
502 1
                'kana01' => $Customer->getKana01(),
503 1
                'kana02' => $Customer->getKana02(),
504 1
                'postal_code' => $Customer->getPostalCode(),
505 1
                'pref' => is_null($Customer->getPref()) ? null : $Customer->getPref()->getId(),
506 1
                'addr01' => $Customer->getAddr01(),
507 1
                'addr02' => $Customer->getAddr02(),
508 1
                'email' => $Customer->getEmail(),
509 1
                'phone_number' => $Customer->getPhoneNumber(),
510 1
                'company_name' => $Customer->getCompanyName(),
511
            ];
512
513 1
            $event = new EventArgs(
514
                [
515 1
                    'data' => $data,
516 1
                    'Customer' => $Customer,
517
                ],
518 1
                $request
519
            );
520 1
            $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_CUSTOMER_BY_ID_COMPLETE, $event);
521 1
            $data = $event->getArgument('data');
522
523 1
            return $this->json($data);
524
        }
525
    }
526
527
    /**
528
     * @Route("/%eccube_admin_route%/order/search/product", name="admin_order_search_product")
529
     * @Route("/%eccube_admin_route%/order/search/product/page/{page_no}", requirements={"page_no" = "\d+"}, name="admin_order_search_product_page")
530
     * @Template("@admin/Order/search_product.twig")
531
     */
532 1
    public function searchProduct(Request $request, $page_no = null, Paginator $paginator)
533
    {
534 1
        if ($request->isXmlHttpRequest() && $this->isTokenValid()) {
535 1
            log_debug('search product start.');
536 1
            $page_count = $this->eccubeConfig['eccube_default_page_count'];
537 1
            $session = $this->session;
538
539 1
            if ('POST' === $request->getMethod()) {
540 1
                $page_no = 1;
541
542
                $searchData = [
543 1
                    'id' => $request->get('id'),
544
                ];
545
546 1
                if ($categoryId = $request->get('category_id')) {
547
                    $Category = $this->categoryRepository->find($categoryId);
548
                    $searchData['category_id'] = $Category;
549
                }
550
551 1
                $session->set('eccube.admin.order.product.search', $searchData);
552 1
                $session->set('eccube.admin.order.product.search.page_no', $page_no);
553
            } else {
554
                $searchData = (array) $session->get('eccube.admin.order.product.search');
555
                if (is_null($page_no)) {
556
                    $page_no = intval($session->get('eccube.admin.order.product.search.page_no'));
557
                } else {
558
                    $session->set('eccube.admin.order.product.search.page_no', $page_no);
559
                }
560
            }
561
562 1
            $qb = $this->productRepository
563 1
                ->getQueryBuilderBySearchDataForAdmin($searchData);
564
565 1
            $event = new EventArgs(
566
                [
567 1
                    'qb' => $qb,
568 1
                    'searchData' => $searchData,
569
                ],
570 1
                $request
571
            );
572 1
            $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_PRODUCT_SEARCH, $event);
573
574
            /** @var \Knp\Component\Pager\Pagination\SlidingPagination $pagination */
575 1
            $pagination = $paginator->paginate(
576 1
                $qb,
577 1
                $page_no,
578 1
                $page_count,
579 1
                ['wrap-queries' => true]
580
            );
581
582
            /** @var $Products \Eccube\Entity\Product[] */
583 1
            $Products = $pagination->getItems();
584
585 1
            if (empty($Products)) {
586
                log_debug('search product not found.');
587
            }
588
589 1
            $forms = [];
590 1 View Code Duplication
            foreach ($Products as $Product) {
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...
591
                /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
592 1
                $builder = $this->formFactory->createNamedBuilder('', AddCartType::class, null, [
593 1
                    'product' => $Product,
594
                ]);
595 1
                $addCartForm = $builder->getForm();
596 1
                $forms[$Product->getId()] = $addCartForm->createView();
597
            }
598
599 1
            $event = new EventArgs(
600
                [
601 1
                    'forms' => $forms,
602 1
                    'Products' => $Products,
603 1
                    'pagination' => $pagination,
604
                ],
605 1
                $request
606
            );
607 1
            $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_PRODUCT_COMPLETE, $event);
608
609
            return [
610 1
                'forms' => $forms,
611 1
                'Products' => $Products,
612 1
                'pagination' => $pagination,
613
            ];
614
        }
615
    }
616
617
    /**
618
     * その他明細情報を取得
619
     *
620
     * @Route("/%eccube_admin_route%/order/search/order_item_type", name="admin_order_search_order_item_type")
621
     * @Template("@admin/Order/order_item_type.twig")
622
     *
623
     * @param Request $request
624
     *
625
     * @return array
626
     */
627
    public function searchOrderItemType(Request $request)
628
    {
629
        if ($request->isXmlHttpRequest() && $this->isTokenValid()) {
630
            log_debug('search order item type start.');
631
632
            $criteria = Criteria::create();
633
            $criteria
634
                ->where($criteria->expr()->andX(
635
                    $criteria->expr()->neq('id', OrderItemType::PRODUCT),
636
                    $criteria->expr()->neq('id', OrderItemType::TAX)
637
                ))
638
                ->orderBy(['sort_no' => 'ASC']);
639
640
            $OrderItemTypes = $this->orderItemTypeRepository->matching($criteria);
641
642
            $forms = [];
643
            foreach ($OrderItemTypes as $OrderItemType) {
644
                /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
645
                $builder = $this->formFactory->createBuilder();
646
                $form = $builder->getForm();
647
                $forms[$OrderItemType->getId()] = $form->createView();
648
            }
649
650
            return [
651
                'forms' => $forms,
652
                'OrderItemTypes' => $OrderItemTypes,
653
            ];
654
        }
655
    }
656
}
657