EditController   C
last analyzed

Complexity

Total Complexity 64

Size/Duplication

Total Lines 734
Duplicated Lines 2.45 %

Coupling/Cohesion

Components 1
Dependencies 11

Test Coverage

Coverage 89.23%

Importance

Changes 0
Metric Value
dl 18
loc 734
ccs 323
cts 362
cp 0.8923
rs 5
c 0
b 0
f 0
wmc 64
lcom 1
cbo 11

8 Methods

Rating   Name   Duplication   Size   Complexity  
F index() 0 309 29
A searchCustomer() 9 54 4
B searchCustomerHtml() 9 82 6
B searchCustomerById() 0 59 4
C searchProduct() 0 85 7
A newOrder() 0 14 1
B calculate() 0 33 3
D updateDate() 0 42 10

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
 * This file is part of EC-CUBE
4
 *
5
 * Copyright(c) 2000-2015 LOCKON CO.,LTD. All Rights Reserved.
6
 *
7
 * http://www.lockon.co.jp/
8
 *
9
 * This program is free software; you can redistribute it and/or
10
 * modify it under the terms of the GNU General Public License
11
 * as published by the Free Software Foundation; either version 2
12
 * of the License, or (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22
 */
23
24
namespace Eccube\Controller\Admin\Order;
25
26
use Doctrine\Common\Collections\ArrayCollection;
27
use Eccube\Application;
28
use Eccube\Common\Constant;
29
use Eccube\Controller\AbstractController;
30
use Eccube\Entity\Master\DeviceType;
31
use Eccube\Entity\OrderDetail;
32
use Eccube\Entity\ShipmentItem;
33
use Eccube\Entity\Shipping;
34
use Eccube\Event\EccubeEvents;
35
use Eccube\Event\EventArgs;
36
use Symfony\Component\Form\FormError;
37
use Symfony\Component\HttpFoundation\Request;
38
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
39
40
class EditController extends AbstractController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
41
{
42 21
    public function index(Application $app, Request $request, $id = null)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
43
    {
44
        /* @var $softDeleteFilter \Eccube\Doctrine\Filter\SoftDeleteFilter */
45 21
        $softDeleteFilter = $app['orm.em']->getFilters()->getFilter('soft_delete');
46 21
        $softDeleteFilter->setExcludes(array(
47 21
            'Eccube\Entity\ProductClass',
48
            'Eccube\Entity\Product',
49
        ));
50
51 21
        $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...
52 21
        $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...
53 21
        $isNewOrder = false;
54
55 21
        if (is_null($id)) {
56
            // 空のエンティティを作成.
57 7
            $TargetOrder = $this->newOrder($app);
58 7
            $isNewOrder = true;
59
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
60
        } else {
61 14
            $TargetOrder = $app['eccube.repository.order']->find($id);
62 14
            if (is_null($TargetOrder)) {
63
                throw new NotFoundHttpException();
64
            }
65
        }
66
67
        // 編集前の受注情報を保持
68 21
        $OriginOrder = clone $TargetOrder;
69 21
        $OriginalOrderDetails = new ArrayCollection();
70
        // 編集前のお届け先情報を保持
71 21
        $OriginalShippings = new ArrayCollection();
72
        // 編集前のお届け先のアイテム情報を保持
73 21
        $OriginalShipmentItems = new ArrayCollection();
74
75
        // Save previous value before calculate
76 21
        $arrOldOrder = array();
77
78
        /** @var $OrderDetail OrderDetail*/
79 21
        foreach ($TargetOrder->getOrderDetails() as $OrderDetail) {
80 14
            $OriginalOrderDetails->add($OrderDetail);
81 21
            $arrOldOrder['OrderDetails'][$OrderDetail->getId()]['quantity'] = $OrderDetail->getQuantity();
82
        }
83
84
        // 編集前の情報を保持
85
        /** @var $tmpOriginalShippings Shipping*/
86 21
        foreach ($TargetOrder->getShippings() as $key => $tmpOriginalShippings) {
87 21
            $arrOldOrder['Shippings'][$key]['shipping_delivery_date'] = $tmpOriginalShippings->getShippingDeliveryDate();
88
            /** @var $tmpOriginalShipmentItem ShipmentItem*/
89 21
            foreach ($tmpOriginalShippings->getShipmentItems() as $tmpOriginalShipmentItem) {
90
                // アイテム情報
91 14
                $OriginalShipmentItems->add($tmpOriginalShipmentItem);
92 21
                $arrOldOrder['Shippings'][$key]['ShipmentItems'][$tmpOriginalShipmentItem->getId()]['quantity'] = $tmpOriginalShipmentItem->getQuantity();
93
            }
94
            // お届け先情報
95 21
            $OriginalShippings->add($tmpOriginalShippings);
96
        }
97
98 21
        $builder = $app['form.factory']
99 21
            ->createBuilder('order', $TargetOrder);
100
101 21
        $event = new EventArgs(
102
            array(
103 21
                'builder' => $builder,
104 21
                'OriginOrder' => $OriginOrder,
105 21
                'TargetOrder' => $TargetOrder,
106 21
                'OriginOrderDetails' => $OriginalOrderDetails,
107
            ),
108
            $request
109
        );
110 21
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_INDEX_INITIALIZE, $event);
111
112 21
        $form = $builder->getForm();
113
114 21
        if ('POST' === $request->getMethod()) {
115 15
            $form->handleRequest($request);
116
117 15
            $event = new EventArgs(
118
                array(
119 15
                    'builder' => $builder,
120 15
                    'OriginOrder' => $OriginOrder,
121 15
                    'TargetOrder' => $TargetOrder,
122 15
                    'OriginOrderDetails' => $OriginalOrderDetails,
123
                ),
124
                $request
125
            );
126 15
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_INDEX_PROGRESS, $event);
127
128
            // 入力情報にもとづいて再計算.
129 15
            $this->calculate($app, $TargetOrder);
130
131
            // 登録ボタン押下
132 15
            switch ($request->get('mode')) {
133 15
                case 'register':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
134
135 15
                    log_info('受注登録開始', array($TargetOrder->getId()));
136
137 15
                    if ($TargetOrder->getTotal() > $app['config']['max_total_fee']) {
138
                        log_info('受注登録入力チェックエラー', array($TargetOrder->getId()));
139
                        $form['charge']->addError(new FormError('合計金額の上限を超えております。'));
140 15
                    } elseif ($form->isValid()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
141
142 15
                        $BaseInfo = $app['eccube.repository.base_info']->get();
143
144
                        // お支払い方法の更新
145 15
                        $TargetOrder->setPaymentMethod($TargetOrder->getPayment()->getMethod());
146
147
                        // 配送業者・お届け時間の更新
148 15
                        $Shippings = $TargetOrder->getShippings();
149 15
                        foreach ($Shippings as $Shipping) {
150 15
                            $Shipping->setShippingDeliveryName($Shipping->getDelivery()->getName());
151 15
                            if (!is_null($Shipping->getDeliveryTime())) {
152 15
                                $Shipping->setShippingDeliveryTime($Shipping->getDeliveryTime()->getDeliveryTime());
153
                            } else {
154 15
                                $Shipping->setShippingDeliveryTime(null);
155
                            }
156
                        }
157
158
159
                        // 受注日/発送日/入金日の更新.
160 15
                        $this->updateDate($app, $TargetOrder, $OriginOrder);
161
162
                        // 受注明細で削除されているものをremove
163 15
                        foreach ($OriginalOrderDetails as $OrderDetail) {
164 11
                            if (false === $TargetOrder->getOrderDetails()->contains($OrderDetail)) {
165 15
                                $app['orm.em']->remove($OrderDetail);
166
                            }
167
                        }
168
169
170 15
                        if ($BaseInfo->getOptionMultipleShipping() == Constant::ENABLED) {
171 6
                            foreach ($TargetOrder->getOrderDetails() as $OrderDetail) {
172
                                /** @var $OrderDetail \Eccube\Entity\OrderDetail */
173 6
                                $OrderDetail->setOrder($TargetOrder);
174
                            }
175
176
                            /** @var \Eccube\Entity\Shipping $Shipping */
177 6
                            foreach ($Shippings as $Shipping) {
178 6
                                $shipmentItems = $Shipping->getShipmentItems();
179
                                /** @var \Eccube\Entity\ShipmentItem $ShipmentItem */
180 6
                                foreach ($shipmentItems as $ShipmentItem) {
181
                                    // 削除予定から商品アイテムを外す
182 6
                                    $OriginalShipmentItems->removeElement($ShipmentItem);
183 6
                                    $ShipmentItem->setOrder($TargetOrder);
184 6
                                    $ShipmentItem->setShipping($Shipping);
185 6
                                    $app['orm.em']->persist($ShipmentItem);
186
                                }
187
                                // 削除予定からお届け先情報を外す
188 6
                                $OriginalShippings->removeElement($Shipping);
189 6
                                $Shipping->setOrder($TargetOrder);
190 6
                                $app['orm.em']->persist($Shipping);
191
                            }
192
                            // 商品アイテムを削除する
193 6
                            foreach ($OriginalShipmentItems as $OriginalShipmentItem) {
194 6
                                $app['orm.em']->remove($OriginalShipmentItem);
195
                            }
196
                            // お届け先情報削除する
197 6
                            foreach ($OriginalShippings as $OriginalShipping) {
198 6
                                $app['orm.em']->remove($OriginalShipping);
199
                            }
200
                        } else {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
201
202 9
                            $NewShipmentItems = new ArrayCollection();
203
204 9
                            foreach ($TargetOrder->getOrderDetails() as $OrderDetail) {
205
                                /** @var $OrderDetail \Eccube\Entity\OrderDetail */
206 9
                                $OrderDetail->setOrder($TargetOrder);
207
208 9
                                $NewShipmentItem = new ShipmentItem();
209
                                $NewShipmentItem
210 9
                                    ->setProduct($OrderDetail->getProduct())
211 9
                                    ->setProductClass($OrderDetail->getProductClass())
212 9
                                    ->setProductName($OrderDetail->getProduct()->getName())
213 9
                                    ->setProductCode($OrderDetail->getProductClass()->getCode())
214 9
                                    ->setClassCategoryName1($OrderDetail->getClassCategoryName1())
215 9
                                    ->setClassCategoryName2($OrderDetail->getClassCategoryName2())
216 9
                                    ->setClassName1($OrderDetail->getClassName1())
217 9
                                    ->setClassName2($OrderDetail->getClassName2())
218 9
                                    ->setPrice($OrderDetail->getPrice())
219 9
                                    ->setQuantity($OrderDetail->getQuantity())
220 9
                                    ->setOrder($TargetOrder);
221 9
                                $NewShipmentItems[] = $NewShipmentItem;
222
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
223
                            }
224
                            // 配送商品の更新. delete/insert.
225 9
                            $Shippings = $TargetOrder->getShippings();
226 9
                            foreach ($Shippings as $Shipping) {
227 9
                                $ShipmentItems = $Shipping->getShipmentItems();
228 9
                                foreach ($ShipmentItems as $ShipmentItem) {
229 9
                                    $app['orm.em']->remove($ShipmentItem);
230
                                }
231 9
                                $ShipmentItems->clear();
232 9
                                foreach ($NewShipmentItems as $NewShipmentItem) {
233 9
                                    $NewShipmentItem->setShipping($Shipping);
234 9
                                    $ShipmentItems->add($NewShipmentItem);
235
                                }
236
                            }
237
                        }
238
239 15
                        $Customer = $TargetOrder->getCustomer();
240 15
                        if ($Customer) {
241
                            // 受注情報の会員情報を更新
242 15
                            $TargetOrder->setSex($Customer->getSex());
243 15
                            $TargetOrder->setJob($Customer->getJob());
244 15
                            $TargetOrder->setBirth($Customer->getBirth());
245
                        }
246
247 15
                        $app['orm.em']->persist($TargetOrder);
248 15
                        $app['orm.em']->flush();
249
250 15
                        if ($Customer) {
251
                            // 会員の場合、購入回数、購入金額などを更新
252 15
                            $app['eccube.repository.customer']->updateBuyData($app, $Customer, $isNewOrder);
253
                        }
254
255 15
                        $event = new EventArgs(
256
                            array(
257 15
                                'form' => $form,
258 15
                                'OriginOrder' => $OriginOrder,
259 15
                                'TargetOrder' => $TargetOrder,
260 15
                                'OriginOrderDetails' => $OriginalOrderDetails,
261 15
                                'Customer' => $Customer,
262
                            ),
263
                            $request
264
                        );
265 15
                        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_INDEX_COMPLETE, $event);
266
267 15
                        $app->addSuccess('admin.order.save.complete', 'admin');
268
269 15
                        log_info('受注登録完了', array($TargetOrder->getId()));
270
271 15
                        return $app->redirect($app->url('admin_order_edit', array('id' => $TargetOrder->getId())));
272
                    }
273
274
                    break;
275
276
                case 'add_delivery':
277
                    // お届け先情報の新規追加
278
279
                    $form = $builder->getForm();
280
281
                    $Shipping = new \Eccube\Entity\Shipping();
282
                    $Shipping->setDelFlg(Constant::DISABLED);
283
284
                    $TargetOrder->addShipping($Shipping);
285
286
                    $Shipping->setOrder($TargetOrder);
287
288
                    $form->setData($TargetOrder);
289
290
                    break;
291
292
                default:
293
                    break;
294
            }
295
        }
296
297
        // 会員検索フォーム
298 6
        $builder = $app['form.factory']
299 6
            ->createBuilder('admin_search_customer');
300
301 6
        $event = new EventArgs(
302
            array(
303 6
                'builder' => $builder,
304 6
                'OriginOrder' => $OriginOrder,
305 6
                'TargetOrder' => $TargetOrder,
306 6
                'OriginOrderDetails' => $OriginalOrderDetails,
307
            ),
308
            $request
309
        );
310 6
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_CUSTOMER_INITIALIZE, $event);
311
312 6
        $searchCustomerModalForm = $builder->getForm();
313
314
        // 商品検索フォーム
315 6
        $builder = $app['form.factory']
316 6
            ->createBuilder('admin_search_product');
317
318 6
        $event = new EventArgs(
319
            array(
320 6
                'builder' => $builder,
321 6
                'OriginOrder' => $OriginOrder,
322 6
                'TargetOrder' => $TargetOrder,
323 6
                'OriginOrderDetails' => $OriginalOrderDetails,
324
            ),
325
            $request
326
        );
327 6
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_PRODUCT_INITIALIZE, $event);
328
329 6
        $searchProductModalForm = $builder->getForm();
330
331
        // 配送業者のお届け時間
332 6
        $times = array();
333 6
        $deliveries = $app['eccube.repository.delivery']->findAll();
334 6
        foreach ($deliveries as $Delivery) {
335 6
            $deliveryTiems = $Delivery->getDeliveryTimes();
336 6
            foreach ($deliveryTiems as $DeliveryTime) {
337 6
                $times[$Delivery->getId()][$DeliveryTime->getId()] = $DeliveryTime->getDeliveryTime();
338
            }
339
        }
340
341 6
        return $app->render('Order/edit.twig', array(
342 6
            'form' => $form->createView(),
343 6
            'searchCustomerModalForm' => $searchCustomerModalForm->createView(),
344 6
            'searchProductModalForm' => $searchProductModalForm->createView(),
345 6
            'Order' => $TargetOrder,
346 6
            'id' => $id,
347 6
            'shippingDeliveryTimes' => $app['serializer']->serialize($times, 'json'),
348 6
            'arrOldOrder' => $arrOldOrder,
349
        ));
350
    }
351
352
    /**
353
     * 顧客情報を検索する.
354
     *
355
     * @param Application $app
356
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
357
     * @return \Symfony\Component\HttpFoundation\JsonResponse
358
     */
359 5
    public function searchCustomer(Application $app, Request $request)
360
    {
361 5
        if ($request->isXmlHttpRequest()) {
362 5
            $app['monolog']->addDebug('search customer start.');
363
364
            $searchData = array(
365 5
                'multi' => $request->get('search_word'),
366
            );
367
368 5
            $qb = $app['eccube.repository.customer']->getQueryBuilderBySearchData($searchData);
369
370 5
            $event = new EventArgs(
371
                array(
372 5
                    'qb' => $qb,
373 5
                    'data' => $searchData,
374
                ),
375
                $request
376
            );
377 5
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_CUSTOMER_SEARCH, $event);
378
379 5
            $Customers = $qb->getQuery()->getResult();
380
381
382 5
            if (empty($Customers)) {
383
                $app['monolog']->addDebug('search customer not found.');
384
            }
385
386 5
            $data = array();
387
388 5
            $formatTel = '%s-%s-%s';
389 5
            $formatName = '%s%s(%s%s)';
390 5 View Code Duplication
            foreach ($Customers as $Customer) {
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...
391 5
                $data[] = array(
392 5
                    'id' => $Customer->getId(),
393 5
                    'name' => sprintf($formatName, $Customer->getName01(), $Customer->getName02(), $Customer->getKana01(),
394 5
                        $Customer->getKana02()),
395 5
                    'tel' => sprintf($formatTel, $Customer->getTel01(), $Customer->getTel02(), $Customer->getTel03()),
396 5
                    'email' => $Customer->getEmail(),
397
                );
398
            }
399
400 5
            $event = new EventArgs(
401
                array(
402 5
                    'data' => $data,
403 5
                    'Customers' => $Customers,
404
                ),
405
                $request
406
            );
407 5
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_CUSTOMER_COMPLETE, $event);
408 5
            $data = $event->getArgument('data');
409
410 5
            return $app->json($data);
411
        }
412
    }
413
414
    /**
415
     * 顧客情報を検索する.
416
     *
417
     * @param Application $app
418
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
419
     * @param integer $page_no
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
420
     * @return \Symfony\Component\HttpFoundation\JsonResponse
421
     */
422 1
    public function searchCustomerHtml(Application $app, Request $request, $page_no = null)
423
    {
424 1
        if ($request->isXmlHttpRequest()) {
425 1
            $app['monolog']->addDebug('search customer start.');
426 1
            $page_count = $app['config']['default_page_count'];
427 1
            $session = $app['session'];
428
429 1
            if ('POST' === $request->getMethod()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
430
431 1
                $page_no = 1;
432
433
                $searchData = array(
434 1
                    'multi' => $request->get('search_word'),
435
                );
436
437 1
                $session->set('eccube.admin.order.customer.search', $searchData);
438 1
                $session->set('eccube.admin.order.customer.search.page_no', $page_no);
439
            } else {
440
                $searchData = (array)$session->get('eccube.admin.order.customer.search');
0 ignored issues
show
Coding Style introduced by
As per coding-style, a cast statement should be followed by a single space.
Loading history...
441
                if (is_null($page_no)) {
442
                    $page_no = intval($session->get('eccube.admin.order.customer.search.page_no'));
443
                } else {
444
                    $session->set('eccube.admin.order.customer.search.page_no', $page_no);
445
                }
446
            }
447
448 1
            $qb = $app['eccube.repository.customer']->getQueryBuilderBySearchData($searchData);
449
450 1
            $event = new EventArgs(
451
                array(
452 1
                    'qb' => $qb,
453 1
                    'data' => $searchData,
454
                ),
455
                $request
456
            );
457 1
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_CUSTOMER_SEARCH, $event);
458
459
            /** @var \Knp\Component\Pager\Pagination\SlidingPagination $pagination */
460 1
            $pagination = $app['paginator']()->paginate(
461
                $qb,
462
                $page_no,
463
                $page_count,
464 1
                array('wrap-queries' => true)
465
            );
466
467
            /** @var $Customers \Eccube\Entity\Customer[] */
468 1
            $Customers = $pagination->getItems();
469
470 1
            if (empty($Customers)) {
471
                $app['monolog']->addDebug('search customer not found.');
472
            }
473
474 1
            $data = array();
475
476 1
            $formatTel = '%s-%s-%s';
477 1
            $formatName = '%s%s(%s%s)';
478 1 View Code Duplication
            foreach ($Customers as $Customer) {
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...
479 1
                $data[] = array(
480 1
                    'id' => $Customer->getId(),
481 1
                    'name' => sprintf($formatName, $Customer->getName01(), $Customer->getName02(), $Customer->getKana01(),
482 1
                        $Customer->getKana02()),
483 1
                    'tel' => sprintf($formatTel, $Customer->getTel01(), $Customer->getTel02(), $Customer->getTel03()),
484 1
                    'email' => $Customer->getEmail(),
485
                );
486
            }
487
488 1
            $event = new EventArgs(
489
                array(
490 1
                    'data' => $data,
491 1
                    'Customers' => $pagination,
492
                ),
493
                $request
494
            );
495 1
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_CUSTOMER_COMPLETE, $event);
496 1
            $data = $event->getArgument('data');
497
498 1
            return $app->render('Order/search_customer.twig', array(
499 1
                'data' => $data,
500 1
                'pagination' => $pagination,
501
            ));
502
        }
503
    }
504
505
    /**
506
     * 顧客情報を検索する.
507
     *
508
     * @param Application $app
509
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
510
     * @return \Symfony\Component\HttpFoundation\JsonResponse
511
     */
512 3
    public function searchCustomerById(Application $app, Request $request)
513
    {
514 3
        if ($request->isXmlHttpRequest()) {
515 3
            $app['monolog']->addDebug('search customer by id start.');
516
517
            /** @var $Customer \Eccube\Entity\Customer */
518 3
            $Customer = $app['eccube.repository.customer']
519 3
                ->find($request->get('id'));
520
521 3
            $event = new EventArgs(
522
                array(
523 3
                    'Customer' => $Customer,
524
                ),
525
                $request
526
            );
527 3
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_CUSTOMER_BY_ID_INITIALIZE, $event);
528
529 3
            if (is_null($Customer)) {
530
                $app['monolog']->addDebug('search customer by id not found.');
531
532
                return $app->json(array(), 404);
533
            }
534
535 3
            $app['monolog']->addDebug('search customer by id found.');
536
537
            $data = array(
538 3
                'id' => $Customer->getId(),
539 3
                'name01' => $Customer->getName01(),
540 3
                'name02' => $Customer->getName02(),
541 3
                'kana01' => $Customer->getKana01(),
542 3
                'kana02' => $Customer->getKana02(),
543 3
                'zip01' => $Customer->getZip01(),
544 3
                'zip02' => $Customer->getZip02(),
545 3
                'pref' => is_null($Customer->getPref()) ? null : $Customer->getPref()->getId(),
546 3
                'addr01' => $Customer->getAddr01(),
547 3
                'addr02' => $Customer->getAddr02(),
548 3
                'email' => $Customer->getEmail(),
549 3
                'tel01' => $Customer->getTel01(),
550 3
                'tel02' => $Customer->getTel02(),
551 3
                'tel03' => $Customer->getTel03(),
552 3
                'fax01' => $Customer->getFax01(),
553 3
                'fax02' => $Customer->getFax02(),
554 3
                'fax03' => $Customer->getFax03(),
555 3
                'company_name' => $Customer->getCompanyName(),
556
            );
557
558 3
            $event = new EventArgs(
559
                array(
560 3
                    'data' => $data,
561 3
                    'Customer' => $Customer,
562
                ),
563
                $request
564
            );
565 3
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_CUSTOMER_BY_ID_COMPLETE, $event);
566 3
            $data = $event->getArgument('data');
567
568 3
            return $app->json($data);
569
        }
570
    }
571
572 3
    public function searchProduct(Application $app, Request $request, $page_no = null)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
573
    {
574 3
        if ($request->isXmlHttpRequest()) {
575 3
            $app['monolog']->addDebug('search product start.');
576 3
            $page_count = $app['config']['default_page_count'];
577 3
            $session = $app['session'];
578
579 3
            if ('POST' === $request->getMethod()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
580
581 3
                $page_no = 1;
582
583
                $searchData = array(
584 3
                    'id' => $request->get('id'),
585
                );
586
587 3
                if ($categoryId = $request->get('category_id')) {
588
                    $Category = $app['eccube.repository.category']->find($categoryId);
589
                    $searchData['category_id'] = $Category;
590
                }
591
592 3
                $session->set('eccube.admin.order.product.search', $searchData);
593 3
                $session->set('eccube.admin.order.product.search.page_no', $page_no);
594
            } else {
595
                $searchData = (array)$session->get('eccube.admin.order.product.search');
0 ignored issues
show
Coding Style introduced by
As per coding-style, a cast statement should be followed by a single space.
Loading history...
596
                if (is_null($page_no)) {
597
                    $page_no = intval($session->get('eccube.admin.order.product.search.page_no'));
598
                } else {
599
                    $session->set('eccube.admin.order.product.search.page_no', $page_no);
600
                }
601
            }
602
603 3
            $qb = $app['eccube.repository.product']
604 3
                ->getQueryBuilderBySearchDataForAdmin($searchData);
605
606 3
            $event = new EventArgs(
607
                array(
608 3
                    'qb' => $qb,
609 3
                    'searchData' => $searchData,
610
                ),
611
                $request
612
            );
613 3
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_PRODUCT_SEARCH, $event);
614
615
            /** @var \Knp\Component\Pager\Pagination\SlidingPagination $pagination */
616 3
            $pagination = $app['paginator']()->paginate(
617
                $qb,
618
                $page_no,
619
                $page_count,
620 3
                array('wrap-queries' => true)
621
            );
622
623
            /** @var $Products \Eccube\Entity\Product[] */
624 3
            $Products = $pagination->getItems();
625
626 3
            if (empty($Products)) {
627
                $app['monolog']->addDebug('search product not found.');
628
            }
629
630 3
            $forms = array();
631 3
            foreach ($Products as $Product) {
632
                /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
633 3
                $builder = $app['form.factory']->createNamedBuilder('', 'add_cart', null, array(
634 3
                    'product' => $Product,
635
                ));
636 3
                $addCartForm = $builder->getForm();
637 3
                $forms[$Product->getId()] = $addCartForm->createView();
638
            }
639
640 3
            $event = new EventArgs(
641
                array(
642 3
                    'forms' => $forms,
643 3
                    'Products' => $Products,
644 3
                    'pagination' => $pagination,
645
                ),
646
                $request
647
            );
648 3
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_PRODUCT_COMPLETE, $event);
649
650 3
            return $app->render('Order/search_product.twig', array(
651 3
                'forms' => $forms,
652 3
                'Products' => $Products,
653 3
                'pagination' => $pagination,
654
            ));
655
        }
656
    }
657
658 7
    protected function newOrder(Application $app)
659
    {
660 7
        $Order = new \Eccube\Entity\Order();
661 7
        $Shipping = new \Eccube\Entity\Shipping();
662 7
        $Shipping->setDelFlg(0);
663 7
        $Order->addShipping($Shipping);
664 7
        $Shipping->setOrder($Order);
665
666
        // device type
667 7
        $DeviceType = $app['eccube.repository.master.device_type']->find(DeviceType::DEVICE_TYPE_ADMIN);
668 7
        $Order->setDeviceType($DeviceType);
669
670 7
        return $Order;
671
    }
672
673
    /**
674
     * フォームからの入直内容に基づいて、受注情報の再計算を行う
675
     *
676
     * @param $app
677
     * @param $Order
678
     */
679 15
    protected function calculate($app, \Eccube\Entity\Order $Order)
680
    {
681 15
        $taxtotal = 0;
682 15
        $subtotal = 0;
683
684
        // 受注明細データの税・小計を再計算
685
        /** @var $OrderDetails \Eccube\Entity\OrderDetail[] */
686 15
        $OrderDetails = $Order->getOrderDetails();
687 15
        foreach ($OrderDetails as $OrderDetail) {
688
            // 税
689 15
            $tax = $app['eccube.service.tax_rule']
690 15
                ->calcTax($OrderDetail->getPrice(), $OrderDetail->getTaxRate(), $OrderDetail->getTaxRule());
691 15
            $OrderDetail->setPriceIncTax($OrderDetail->getPrice() + $tax);
692
693 15
            $taxtotal += $tax * $OrderDetail->getQuantity();
694
695
            // 小計
696 15
            $subtotal += $OrderDetail->getTotalPrice();
697
        }
698
699 15
        $shippings = $Order->getShippings();
700
        /** @var \Eccube\Entity\Shipping $Shipping */
701 15
        foreach ($shippings as $Shipping) {
702 15
            $Shipping->setDelFlg(Constant::DISABLED);
703
        }
704
705
        // 受注データの税・小計・合計を再計算
706 15
        $Order->setTax($taxtotal);
707 15
        $Order->setSubtotal($subtotal);
708 15
        $Order->setTotal($subtotal + $Order->getCharge() + $Order->getDeliveryFeeTotal() - $Order->getDiscount());
709
        // お支払い合計は、totalと同一金額(2系ではtotal - point)
710 15
        $Order->setPaymentTotal($Order->getTotal());
711
    }
712
713
    /**
714
     * 受注ステータスに応じて, 受注日/入金日/発送日を更新する,
715
     * 発送済ステータスが設定された場合は, お届け先情報の発送日も更新を行う.
716
     *
717
     * 編集の場合
718
     * - 受注ステータスが他のステータスから発送済へ変更された場合に発送日を更新
719
     * - 受注ステータスが他のステータスから入金済へ変更された場合に入金日を更新
720
     *
721
     * 新規登録の場合
722
     * - 受注日を更新
723
     * - 受注ステータスが発送済に設定された場合に発送日を更新
724
     * - 受注ステータスが入金済に設定された場合に入金日を更新
725
     *
726
     *
727
     * @param $app
728
     * @param $TargetOrder
729
     * @param $OriginOrder
730
     */
731 15
    protected function updateDate($app, $TargetOrder, $OriginOrder)
732
    {
733 15
        $dateTime = new \DateTime();
734
735
        // 編集
736 15
        if ($TargetOrder->getId()) {
737
            // 発送済
738 11
            if ($TargetOrder->getOrderStatus()->getId() == $app['config']['order_deliv']) {
739
                // 編集前と異なる場合のみ更新
740
                if ($TargetOrder->getOrderStatus()->getId() != $OriginOrder->getOrderStatus()->getId()) {
741
                    $TargetOrder->setCommitDate($dateTime);
742
                    // お届け先情報の発送日も更新する.
743
                    $Shippings = $TargetOrder->getShippings();
744
                    foreach ($Shippings as $Shipping) {
745
                        $Shipping->setShippingCommitDate($dateTime);
746
                    }
747
                }
748
                // 入金済
749 11
            } elseif ($TargetOrder->getOrderStatus()->getId() == $app['config']['order_pre_end']) {
750
                // 編集前と異なる場合のみ更新
751
                if ($TargetOrder->getOrderStatus()->getId() != $OriginOrder->getOrderStatus()->getId()) {
752 11
                    $TargetOrder->setPaymentDate($dateTime);
753
                }
754
            }
755
            // 新規
756
        } else {
757
            // 発送済
758 4
            if ($TargetOrder->getOrderStatus()->getId() == $app['config']['order_deliv']) {
759
                $TargetOrder->setCommitDate($dateTime);
760
                // お届け先情報の発送日も更新する.
761
                $Shippings = $TargetOrder->getShippings();
762
                foreach ($Shippings as $Shipping) {
763
                    $Shipping->setShippingCommitDate($dateTime);
764
                }
765
                // 入金済
766 4
            } elseif ($TargetOrder->getOrderStatus()->getId() == $app['config']['order_pre_end']) {
767
                $TargetOrder->setPaymentDate($dateTime);
768
            }
769
            // 受注日時
770 4
            $TargetOrder->setOrderDate($dateTime);
771
        }
772
    }
773
}
774