Failed Conditions
Pull Request — experimental/sf (#31)
by Kentaro
06:59
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 72.72%

Importance

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