Failed Conditions
Branch experimental/sf (68db07)
by Kentaro
42:17 queued 33:39
created

ShippingMultipleController::shippingMultipleEdit()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 69

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 28
CRAP Score 7.7048

Importance

Changes 0
Metric Value
cc 7
nc 5
nop 1
dl 0
loc 69
rs 7.743
c 0
b 0
f 0
ccs 28
cts 37
cp 0.7568
crap 7.7048

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/*
4
 * This file is part of EC-CUBE
5
 *
6
 * Copyright(c) LOCKON CO.,LTD. All Rights Reserved.
7
 *
8
 * http://www.lockon.co.jp/
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Eccube\Controller;
15
16
use Eccube\Entity\Customer;
17
use Eccube\Entity\CustomerAddress;
18
use Eccube\Entity\Master\OrderItemType;
19
use Eccube\Entity\Master\OrderStatus;
20
use Eccube\Entity\OrderItem;
21
use Eccube\Entity\Shipping;
22
use Eccube\Event\EccubeEvents;
23
use Eccube\Event\EventArgs;
24
use Eccube\Form\Type\Front\ShoppingShippingType;
25
use Eccube\Form\Type\ShippingMultipleType;
26
use Eccube\Repository\Master\OrderItemTypeRepository;
27
use Eccube\Repository\Master\PrefRepository;
28
use Eccube\Repository\OrderRepository;
29
use Eccube\Service\PurchaseFlow\PurchaseContext;
30
use Eccube\Service\PurchaseFlow\PurchaseFlow;
31
use Eccube\Service\ShoppingService;
32
use Eccube\Service\CartService;
33
use Eccube\Service\OrderHelper;
34
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
35
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
36
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
37
use Symfony\Component\HttpFoundation\Request;
38
39
class ShippingMultipleController extends AbstractShoppingController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
40
{
41
    /**
42
     * @var PrefRepository
43
     */
44
    protected $prefRepository;
45
46
    /**
47
     * @var OrderItemTypeRepository
48
     */
49
    protected $orderItemTypeRepository;
50
51
    /**
52
     * @var ShoppingService
53
     */
54
    protected $shoppingService;
55
56
    /**
57
     * @var CartService
58
     */
59
    protected $cartService;
60
61
    /**
62
     * @var PurchaseFlow
63
     */
64
    protected $cartPurchaseFlow;
65
66
    /**
67
     * @var OrderRepository
68
     */
69
    protected $orderRepository;
70
71
    /**
72
     * @var OrderHelper
73
     */
74
    protected $orderHelper;
75
76
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$orderRepository" missing
Loading history...
introduced by
Doc comment for parameter "$cartService" missing
Loading history...
introduced by
Doc comment for parameter "$cartPurchaseFlow" missing
Loading history...
77
     * ShippingMultipleController constructor.
78
     *
79
     * @param PrefRepository $prefRepository
0 ignored issues
show
introduced by
Expected 10 spaces after parameter type; 1 found
Loading history...
80
     * @param OrderItemTypeRepository $orderItemTypeRepository
0 ignored issues
show
introduced by
Doc comment for parameter $orderItemTypeRepository does not match actual variable name $orderRepository
Loading history...
81
     * @param ShoppingService $shoppingService
0 ignored issues
show
introduced by
Expected 9 spaces after parameter type; 1 found
Loading history...
introduced by
Doc comment for parameter $shoppingService does not match actual variable name $orderItemTypeRepository
Loading history...
82
     * @param CartService $cartService,
0 ignored issues
show
Documentation introduced by
There is no parameter named $cartService,. Did you maybe mean $cartService?

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

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

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

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

Loading history...
introduced by
Expected 13 spaces after parameter type; 1 found
Loading history...
introduced by
Doc comment for parameter $cartService, does not match actual variable name $shoppingService
Loading history...
83
     * @param OrderHelper $orderHelper
0 ignored issues
show
introduced by
Expected 13 spaces after parameter type; 1 found
Loading history...
introduced by
Doc comment for parameter $orderHelper does not match actual variable name $cartService
Loading history...
84
     */
85 26
    public function __construct(
86
        PrefRepository $prefRepository,
87
        OrderRepository $orderRepository,
88
        OrderItemTypeRepository $orderItemTypeRepository,
89
        ShoppingService $shoppingService,
90
        CartService $cartService,
91
        OrderHelper $orderHelper,
92
        PurchaseFlow $cartPurchaseFlow
93
    ) {
94 26
        $this->prefRepository = $prefRepository;
95 26
        $this->orderRepository = $orderRepository;
96 26
        $this->orderItemTypeRepository = $orderItemTypeRepository;
97 26
        $this->shoppingService = $shoppingService;
98 26
        $this->cartService = $cartService;
99 26
        $this->orderHelper = $orderHelper;
100 26
        $this->cartPurchaseFlow = $cartPurchaseFlow;
101
    }
102
103
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
104
     * 複数配送処理
105
     *
106
     * @Route("/shopping/shipping_multiple", name="shopping_shipping_multiple")
107
     * @Template("Shopping/shipping_multiple.twig")
108
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
109 26
    public function index(Request $request)
110
    {
111
        // カートチェック
112 26
        $response = $this->forwardToRoute('shopping_check_to_cart');
113 26
        if ($response->isRedirection() || $response->getContent()) {
114
            return $response;
115
        }
116
117
        /** @var \Eccube\Entity\Order $Order */
118 26
        $Order = $this->shoppingService->getOrder(OrderStatus::PROCESSING);
119 26
        if (!$Order) {
120
            log_info('購入処理中の受注情報がないため購入エラー');
121
            $this->addError('front.shopping.order.error');
122
123
            return $this->redirectToRoute('shopping_error');
124
        }
125
126
        // 処理しやすいようにすべてのShippingItemをまとめる
127 26
        $OrderItems = $Order->getProductOrderItems();
128
129
        // Orderに含まれる商品ごとの数量を求める
130 26
        $ItemQuantitiesByClassId = [];
131 26
        foreach ($OrderItems as $item) {
132 26
            $itemId = $item->getProductClass()->getId();
133 26
            $quantity = $item->getQuantity();
134 26
            if (array_key_exists($itemId, $ItemQuantitiesByClassId)) {
135
                $ItemQuantitiesByClassId[$itemId] += $quantity;
136
            } else {
137 26
                $ItemQuantitiesByClassId[$itemId] = $quantity;
138
            }
139
        }
140
141
        // FormBuilder用に商品ごとにShippingItemをまとめる
142 26
        $OrderItemsForFormBuilder = [];
143 26
        $tmpAddedClassIds = [];
144 26
        foreach ($OrderItems as $item) {
145 26
            $itemId = $item->getProductClass()->getId();
146 26
            if (!in_array($itemId, $tmpAddedClassIds)) {
147 26
                $OrderItemsForFormBuilder[] = $item;
148 26
                $tmpAddedClassIds[] = $itemId;
149
            }
150
        }
151
152
        // Form生成
153 26
        $builder = $this->formFactory->createBuilder();
154
        $builder
155 26
            ->add('shipping_multiple', CollectionType::class, [
156 26
                'entry_type' => ShippingMultipleType::class,
157 26
                'data' => $OrderItemsForFormBuilder,
158
                'allow_add' => true,
159
                'allow_delete' => true,
160
            ]);
161
        // Event
162 26
        $event = new EventArgs(
163
            [
164 26
                'builder' => $builder,
165 26
                'Order' => $Order,
166
            ],
167 26
            $request
168
        );
169 26
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_MULTIPLE_INITIALIZE, $event);
170
171 26
        $form = $builder->getForm();
172 26
        $form->handleRequest($request);
173
174 26
        $errors = [];
175 26
        if ($form->isSubmitted() && $form->isValid()) {
176 25
            log_info('複数配送設定処理開始', [$Order->getId()]);
177
178 25
            $data = $form['shipping_multiple'];
179
180
            // フォームの入力から、送り先ごとに商品の数量を集計する
181 25
            $arrOrderItemTemp = [];
182 25
            foreach ($data as $mulitples) {
183 25
                $OrderItem = $mulitples->getData();
184 25
                foreach ($mulitples as $items) {
185 25
                    foreach ($items as $item) {
186 25
                        $CustomerAddress = $item['customer_address']->getData();
187 25
                        $customerAddressName = $CustomerAddress->getShippingMultipleDefaultName();
188
189 25
                        $itemId = $OrderItem->getProductClass()->getId();
190 25
                        $quantity = $item['quantity']->getData();
191
192 25
                        if (isset($arrOrderItemTemp[$customerAddressName]) && array_key_exists($itemId, $arrOrderItemTemp[$customerAddressName])) {
193 7
                            $arrOrderItemTemp[$customerAddressName][$itemId] = $arrOrderItemTemp[$customerAddressName][$itemId] + $quantity;
194
                        } else {
195 25
                            $arrOrderItemTemp[$customerAddressName][$itemId] = $quantity;
196
                        }
197
                    }
198
                }
199
            }
200
201
            // フォームの入力から、商品ごとの数量を集計する
202 25
            $itemQuantities = [];
203 25
            foreach ($arrOrderItemTemp as $FormItemByAddress) {
204 25
                foreach ($FormItemByAddress as $itemId => $quantity) {
205 25
                    if (array_key_exists($itemId, $itemQuantities)) {
206 14
                        $itemQuantities[$itemId] = $itemQuantities[$itemId] + $quantity;
207
                    } else {
208 25
                        $itemQuantities[$itemId] = $quantity;
209
                    }
210
                }
211
            }
212
213
            // -- ここから先がお届け先を再生成する処理 --
214
215
            // お届け先情報をすべて削除
216
            /** @var Shipping $Shipping */
217 25
            foreach ($Order->getShippings() as $Shipping) {
218 25
                foreach ($Shipping->getOrderItems() as $OrderItem) {
219 25
                    $Shipping->removeOrderItem($OrderItem);
220 25
                    $Order->removeOrderItem($OrderItem);
221 25
                    $this->entityManager->remove($OrderItem);
222
                }
223 25
                $this->entityManager->remove($Shipping);
224
            }
225
226
            // お届け先のリストを作成する
227 25
            $ShippingList = [];
228 25
            foreach ($data as $mulitples) {
229 25
                $OrderItem = $mulitples->getData();
230 25
                $ProductClass = $OrderItem->getProductClass();
231 25
                $Delivery = $OrderItem->getShipping()->getDelivery();
232 25
                $saleTypeId = $ProductClass->getSaleType()->getId();
233
234 25
                foreach ($mulitples as $items) {
235 25
                    foreach ($items as $item) {
236 25
                        $CustomerAddress = $item['customer_address']->getData();
237 25
                        $customerAddressName = $CustomerAddress->getShippingMultipleDefaultName();
238
239 25
                        $Shipping = new Shipping();
240
                        $Shipping
241 25
                            ->setFromCustomerAddress($CustomerAddress)
242 25
                            ->setDelivery($Delivery);
243
244 25
                        $ShippingList[$customerAddressName][$saleTypeId] = $Shipping;
245
                    }
246
                }
247
            }
248
            // お届け先のリストを保存
249 25
            foreach ($ShippingList as $ShippingListByAddress) {
250 25
                foreach ($ShippingListByAddress as $Shipping) {
251 25
                    $this->entityManager->persist($Shipping);
252
                }
253
            }
254
255 25
            $ProductOrderType = $this->orderItemTypeRepository->find(OrderItemType::PRODUCT);
256
257
            // お届け先に、配送商品の情報(OrderItem)を関連付ける
258 25
            foreach ($data as $mulitples) {
259
                /** @var OrderItem $OrderItem */
260 25
                $OrderItem = $mulitples->getData();
261 25
                $ProductClass = $OrderItem->getProductClass();
262 25
                $Product = $OrderItem->getProduct();
263 25
                $saleTypeId = $ProductClass->getSaleType()->getId();
264 25
                $productClassId = $ProductClass->getId();
265
266 25
                foreach ($mulitples as $items) {
267 25
                    foreach ($items as $item) {
268 25
                        $CustomerAddress = $item['customer_address']->getData();
269 25
                        $customerAddressName = $CustomerAddress->getShippingMultipleDefaultName();
270
271
                        // お届け先から商品の数量を取得
272 25
                        $quantity = 0;
0 ignored issues
show
Unused Code introduced by
$quantity 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...
273 25
                        if (isset($arrOrderItemTemp[$customerAddressName]) && array_key_exists($productClassId, $arrOrderItemTemp[$customerAddressName])) {
274 25
                            $quantity = $arrOrderItemTemp[$customerAddressName][$productClassId];
275 25
                            unset($arrOrderItemTemp[$customerAddressName][$productClassId]);
276
                        } else {
277
                            // この配送先には送る商品がないのでスキップ(通常ありえない)
278 7
                            continue;
279
                        }
280
281
                        // 関連付けるお届け先のインスタンスを取得
282 25
                        $Shipping = $ShippingList[$customerAddressName][$saleTypeId];
283
284
                        // インスタンスを生成して保存
285 25
                        $OrderItem = new OrderItem();
286 25
                        $OrderItem->setShipping($Shipping)
287 25
                            ->setOrder($Order)
288 25
                            ->setProductClass($ProductClass)
289 25
                            ->setProduct($Product)
290 25
                            ->setProductName($Product->getName())
291 25
                            ->setProductCode($ProductClass->getCode())
292 25
                            ->setPrice($ProductClass->getPrice02())
293 25
                            ->setQuantity($quantity)
294 25
                            ->setOrderItemType($ProductOrderType);
295
296 25
                        $ClassCategory1 = $ProductClass->getClassCategory1();
297 25
                        if (!is_null($ClassCategory1)) {
298 25
                            $OrderItem->setClasscategoryName1($ClassCategory1->getName());
299 25
                            $OrderItem->setClassName1($ClassCategory1->getClassName()->getName());
300
                        }
301 25
                        $ClassCategory2 = $ProductClass->getClassCategory2();
302 25
                        if (!is_null($ClassCategory2)) {
303 23
                            $OrderItem->setClasscategoryName2($ClassCategory2->getName());
304 23
                            $OrderItem->setClassName2($ClassCategory2->getClassName()->getName());
305
                        }
306 25
                        $Shipping->addOrderItem($OrderItem);
307 25
                        $Order->addOrderItem($OrderItem);
308 25
                        $this->entityManager->persist($OrderItem);
309
                    }
310
                }
311
            }
312
313
            // 合計金額の再計算
314 25
            $flowResult = $this->executePurchaseFlow($Order);
315 25
            if ($flowResult->hasWarning()) {
316
                return [
317
                    'form' => $form->createView(),
318
                    'OrderItems' => $OrderItemsForFormBuilder,
319
                    'compItemQuantities' => $ItemQuantitiesByClassId,
320
                    'errors' => $errors,
321
                ];
322
            }
323 25
            if ($flowResult->hasError()) {
324
                return $this->redirectToRoute('cart');
325
            }
326
327 25
            $this->entityManager->flush();
328
329 25
            $event = new EventArgs(
330
                [
331 25
                    'form' => $form,
332 25
                    'Order' => $Order,
333
                ],
334 25
                $request
335
            );
336 25
            $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_MULTIPLE_COMPLETE, $event);
337
338 25
            log_info('複数配送設定処理完了', [$Order->getId()]);
339
340 25
            $this->entityManager->refresh($Order);
341
342 25
            $quantityByProductClass = [];
343 25
            foreach ($Order->getProductOrderItems() as $Item) {
344 25
                $id = $Item->getProductClass()->getId();
345 25
                if (isset($quantityByProductClass[$id])) {
346 14
                    $quantityByProductClass[$id] += $Item->getQuantity();
347
                } else {
348 25
                    $quantityByProductClass[$id] = $Item->getQuantity();
349
                }
350
            }
351 25
            $Cart = $this->cartService->getCart();
352 25
            foreach ($Cart->getCartItems() as $CartItem) {
353 25
                $id = $CartItem->getProductClass()->getId();
354 25
                if (isset($quantityByProductClass[$id])) {
355 25
                    $CartItem->setQuantity($quantityByProductClass[$id]);
356
                }
357
            }
358
359 25
            $this->cartPurchaseFlow->calculate($Cart, new PurchaseContext());
360 25
            $this->cartService->save();
361
362 25
            return $this->redirectToRoute('shopping');
363
        }
364
365
        return [
366 4
            'form' => $form->createView(),
367 4
            'OrderItems' => $OrderItemsForFormBuilder,
368 4
            'compItemQuantities' => $ItemQuantitiesByClassId,
369 4
            'errors' => $errors,
370
        ];
371
    }
372
373
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
374
     * 複数配送設定時の新規お届け先の設定
375
     *
376
     * @Route("/shopping/shipping_multiple_edit", name="shopping_shipping_multiple_edit")
377
     * @Template("Shopping/shipping_multiple_edit.twig")
378
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
379 8
    public function shippingMultipleEdit(Request $request)
380
    {
381
        // カートチェック
382 8
        $response = $this->forwardToRoute('shopping_check_to_cart');
383 8
        if ($response->isRedirection() || $response->getContent()) {
384
            return $response;
385
        }
386
387
        /** @var Customer $Customer */
388 8
        $Customer = $this->getUser();
389 8
        $CustomerAddress = new CustomerAddress();
390 8
        $builder = $this->formFactory->createBuilder(ShoppingShippingType::class, $CustomerAddress);
391
392 8
        $event = new EventArgs(
393
            [
394 8
                'builder' => $builder,
395 8
                'Customer' => $Customer,
396
            ],
397 8
            $request
398
        );
399 8
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_MULTIPLE_EDIT_INITIALIZE, $event);
400
401 8
        $form = $builder->getForm();
402
403 8
        $form->handleRequest($request);
404
405 8
        if ($form->isSubmitted() && $form->isValid()) {
406 8
            log_info('複数配送のお届け先追加処理開始');
407
408 8
            if ($this->isGranted('ROLE_USER')) {
409
                $CustomerAddresses = $Customer->getCustomerAddresses();
410
411
                $count = count($CustomerAddresses);
412
                if ($count >= $this->eccubeConfig['eccube_deliv_addr_max']) {
413
                    return [
414
                        'error' => trans('delivery.text.error.max_delivery_address'),
415
                        'form' => $form->createView(),
416
                    ];
417
                }
418
419
                $CustomerAddress->setCustomer($Customer);
420
                $this->entityManager->persist($CustomerAddress);
421
                $this->entityManager->flush($CustomerAddress);
0 ignored issues
show
Unused Code introduced by
The call to EntityManagerInterface::flush() has too many arguments starting with $CustomerAddress.

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...
422
            } else {
423
                // 非会員用のセッションに追加
424 8
                $CustomerAddresses = $this->session->get($this->sessionCustomerAddressKey);
425 8
                $CustomerAddresses = unserialize($CustomerAddresses);
426 8
                $CustomerAddresses[] = $CustomerAddress;
427 8
                $this->session->set($this->sessionCustomerAddressKey, serialize($CustomerAddresses));
428
            }
429
430 8
            $event = new EventArgs(
431
                [
432 8
                    'form' => $form,
433 8
                    'CustomerAddresses' => $CustomerAddresses,
434
                ],
435 8
                $request
436
            );
437 8
            $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_MULTIPLE_EDIT_COMPLETE, $event);
438
439 8
            log_info('複数配送のお届け先追加処理完了');
440
441 8
            return $this->redirectToRoute('shopping_shipping_multiple');
442
        }
443
444
        return [
445 1
            'form' => $form->createView(),
446
        ];
447
    }
448
}
449