Completed
Push — 4.0 ( 268f2c...88f012 )
by Hideki
05:48 queued 10s
created

Eccube/Controller/ShippingMultipleController.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
/*
4
 * This file is part of EC-CUBE
5
 *
6
 * Copyright(c) EC-CUBE CO.,LTD. All Rights Reserved.
7
 *
8
 * http://www.ec-cube.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\OrderItem;
20
use Eccube\Entity\Shipping;
21
use Eccube\Event\EccubeEvents;
22
use Eccube\Event\EventArgs;
23
use Eccube\Form\Type\Front\ShoppingShippingType;
24
use Eccube\Form\Type\ShippingMultipleType;
25
use Eccube\Repository\Master\OrderItemTypeRepository;
26
use Eccube\Repository\Master\PrefRepository;
27
use Eccube\Repository\OrderRepository;
28
use Eccube\Service\CartService;
29
use Eccube\Service\PurchaseFlow\PurchaseContext;
30
use Eccube\Service\PurchaseFlow\PurchaseFlow;
31
use Eccube\Service\OrderHelper;
32
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
33
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
34
use Symfony\Component\HttpFoundation\Request;
35
use Symfony\Component\Routing\Annotation\Route;
36
37
class ShippingMultipleController extends AbstractShoppingController
38
{
39
    /**
40
     * @var PrefRepository
41
     */
42
    protected $prefRepository;
43
44
    /**
45
     * @var OrderItemTypeRepository
46
     */
47
    protected $orderItemTypeRepository;
48
49
    /**
50
     * @var OrderHelper
51
     */
52
    protected $orderHelper;
53
54
    /**
55
     * @var CartService
56
     */
57
    protected $cartService;
58
59
    /**
60
     * @var PurchaseFlow
61
     */
62
    protected $cartPurchaseFlow;
63
64
    /**
65
     * @var OrderRepository
66
     */
67
    protected $orderRepository;
68
69
    /**
70
     * ShippingMultipleController constructor.
71
     *
72
     * @param PrefRepository $prefRepository
73
     * @param OrderRepository $orderRepository
74
     * @param OrderItemTypeRepository $orderItemTypeRepository
75
     * @param OrderHelper $orderHelper
76
     * @param CartService $cartService
77
     * @param PurchaseFlow $cartPurchaseFlow
78
     */
79
    public function __construct(
80
        PrefRepository $prefRepository,
81
        OrderRepository $orderRepository,
82
        OrderItemTypeRepository $orderItemTypeRepository,
83
        OrderHelper $orderHelper,
84
        CartService $cartService,
85 26
        PurchaseFlow $cartPurchaseFlow
86
    ) {
87
        $this->prefRepository = $prefRepository;
88
        $this->orderRepository = $orderRepository;
89
        $this->orderItemTypeRepository = $orderItemTypeRepository;
90
        $this->orderHelper = $orderHelper;
91
        $this->cartService = $cartService;
92
        $this->cartPurchaseFlow = $cartPurchaseFlow;
93
    }
94 26
95 26
    /**
96 26
     * 複数配送処理
97 26
     *
98 26
     * @Route("/shopping/shipping_multiple", name="shopping_shipping_multiple")
99 26
     * @Template("Shopping/shipping_multiple.twig")
100 26
     */
101
    public function index(Request $request)
102
    {
103
        // ログイン状態のチェック.
104
        if ($this->orderHelper->isLoginRequired()) {
105
            return $this->redirectToRoute('shopping_login');
106
        }
107
108
        // 受注の存在チェック
109 26
        $preOrderId = $this->cartService->getPreOrderId();
110
        $Order = $this->orderHelper->getPurchaseProcessingOrder($preOrderId);
111
        if (!$Order) {
112 26
            return $this->redirectToRoute('shopping_error');
113 26
        }
114
115
        // 処理しやすいようにすべてのShippingItemをまとめる
116
        $OrderItems = $Order->getProductOrderItems();
117
118 26
        // Orderに含まれる商品ごとの数量を求める
119 26
        $ItemQuantitiesByClassId = [];
120
        foreach ($OrderItems as $item) {
121
            $itemId = $item->getProductClass()->getId();
122
            $quantity = $item->getQuantity();
123
            if (array_key_exists($itemId, $ItemQuantitiesByClassId)) {
124
                $ItemQuantitiesByClassId[$itemId] += $quantity;
125
            } else {
126
                $ItemQuantitiesByClassId[$itemId] = $quantity;
127 26
            }
128
        }
129
130 26
        // FormBuilder用に商品ごとにShippingItemをまとめる
131 26
        $OrderItemsForFormBuilder = [];
132 26
        $tmpAddedClassIds = [];
133 26
        foreach ($OrderItems as $item) {
134 26
            $itemId = $item->getProductClass()->getId();
135
            if (!in_array($itemId, $tmpAddedClassIds)) {
136
                $OrderItemsForFormBuilder[] = $item;
137 26
                $tmpAddedClassIds[] = $itemId;
138
            }
139
        }
140
141
        // Form生成
142 26
        $builder = $this->formFactory->createBuilder();
143 26
        $builder
144 26
            ->add('shipping_multiple', CollectionType::class, [
145 26
                'entry_type' => ShippingMultipleType::class,
146 26
                'data' => $OrderItemsForFormBuilder,
147 26
                'allow_add' => true,
148 26
                'allow_delete' => true,
149
            ]);
150
        // Event
151
        $event = new EventArgs(
152
            [
153 26
                'builder' => $builder,
154
                'Order' => $Order,
155 26
            ],
156 26
            $request
157 26
        );
158
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_MULTIPLE_INITIALIZE, $event);
159
160
        $form = $builder->getForm();
161
        $form->handleRequest($request);
162 26
163
        $errors = [];
164 26
        if ($form->isSubmitted() && $form->isValid()) {
165 26
            log_info('複数配送設定処理開始', [$Order->getId()]);
166
167 26
            $data = $form['shipping_multiple'];
168
169 26
            // フォームの入力から、送り先ごとに商品の数量を集計する
170
            $arrOrderItemTemp = [];
171 26
            foreach ($data as $multiples) {
172 26
                $OrderItem = $multiples->getData();
173
                foreach ($multiples as $items) {
174 26
                    foreach ($items as $item) {
175 26
                        $CustomerAddress = $item['customer_address']->getData();
176 25
                        $customerAddressName = $CustomerAddress->getShippingMultipleDefaultName();
177
178 25
                        $itemId = $OrderItem->getProductClass()->getId();
179
                        $quantity = $item['quantity']->getData();
180
181 25
                        if (isset($arrOrderItemTemp[$customerAddressName]) && array_key_exists($itemId, $arrOrderItemTemp[$customerAddressName])) {
182 25
                            $arrOrderItemTemp[$customerAddressName][$itemId] = $arrOrderItemTemp[$customerAddressName][$itemId] + $quantity;
183 25
                        } else {
184 25
                            $arrOrderItemTemp[$customerAddressName][$itemId] = $quantity;
185 25
                        }
186 25
                    }
187 25
                }
188
            }
189 25
190 25
            // フォームの入力から、商品ごとの数量を集計する
191
            $itemQuantities = [];
192 25
            foreach ($arrOrderItemTemp as $FormItemByAddress) {
193 7
                foreach ($FormItemByAddress as $itemId => $quantity) {
194
                    if (array_key_exists($itemId, $itemQuantities)) {
195 25
                        $itemQuantities[$itemId] = $itemQuantities[$itemId] + $quantity;
196
                    } else {
197
                        $itemQuantities[$itemId] = $quantity;
198
                    }
199
                }
200
            }
201
202 25
            // -- ここから先がお届け先を再生成する処理 --
203 25
204 25
            // お届け先情報をすべて削除
205 25
            /** @var Shipping $Shipping */
206 14
            foreach ($Order->getShippings() as $Shipping) {
207
                foreach ($Shipping->getOrderItems() as $OrderItem) {
208 25
                    $Shipping->removeOrderItem($OrderItem);
209
                    $Order->removeOrderItem($OrderItem);
210
                    $this->entityManager->remove($OrderItem);
211
                }
212
                $Order->removeShipping($Shipping);
213
                $this->entityManager->remove($Shipping);
214
            }
215
216
            // お届け先のリストを作成する
217 25
            $ShippingList = [];
218 25
            foreach ($data as $multiples) {
219 25
                $OrderItem = $multiples->getData();
220 25
                $ProductClass = $OrderItem->getProductClass();
221 25
                $Delivery = $OrderItem->getShipping()->getDelivery();
222
                $saleTypeId = $ProductClass->getSaleType()->getId();
223 25
224 25
                foreach ($multiples as $items) {
225
                    foreach ($items as $item) {
226
                        $CustomerAddress = $item['customer_address']->getData();
227
                        $customerAddressName = $CustomerAddress->getShippingMultipleDefaultName();
228 25
229 25
                        if (isset($ShippingList[$customerAddressName][$saleTypeId])) {
230 25
                            continue;
231 25
                        }
232 25
                        $Shipping = new Shipping();
233 25
                        $Shipping
234
                            ->setOrder($Order)
235 25
                            ->setFromCustomerAddress($CustomerAddress)
236 25
                            ->setDelivery($Delivery);
237 25
                        $Order->addShipping($Shipping);
238 25
                        $ShippingList[$customerAddressName][$saleTypeId] = $Shipping;
239
                    }
240 25
                }
241 18
            }
242
            // お届け先のリストを保存
243 25
            foreach ($ShippingList as $ShippingListByAddress) {
244
                foreach ($ShippingListByAddress as $Shipping) {
245 25
                    $this->entityManager->persist($Shipping);
246 25
                }
247 25
            }
248 25
249 25
            $ProductOrderType = $this->orderItemTypeRepository->find(OrderItemType::PRODUCT);
250
251
            // お届け先に、配送商品の情報(OrderItem)を関連付ける
252
            foreach ($data as $multiples) {
253
                /** @var OrderItem $OrderItem */
254 25
                $OrderItem = $multiples->getData();
255 25
                $ProductClass = $OrderItem->getProductClass();
256 25
                $Product = $OrderItem->getProduct();
257
                $saleTypeId = $ProductClass->getSaleType()->getId();
258
                $productClassId = $ProductClass->getId();
259
260 25
                foreach ($multiples as $items) {
261
                    foreach ($items as $item) {
262
                        $CustomerAddress = $item['customer_address']->getData();
263 25
                        $customerAddressName = $CustomerAddress->getShippingMultipleDefaultName();
264
265 25
                        // お届け先から商品の数量を取得
266 25
                        $quantity = 0;
0 ignored issues
show
$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...
267 25
                        if (isset($arrOrderItemTemp[$customerAddressName]) && array_key_exists($productClassId, $arrOrderItemTemp[$customerAddressName])) {
268 25
                            $quantity = $arrOrderItemTemp[$customerAddressName][$productClassId];
269 25
                            unset($arrOrderItemTemp[$customerAddressName][$productClassId]);
270
                        } else {
271 25
                            // この配送先には送る商品がないのでスキップ(通常ありえない)
272 25
                            continue;
273 25
                        }
274 25
275
                        // 関連付けるお届け先のインスタンスを取得
276
                        $Shipping = $ShippingList[$customerAddressName][$saleTypeId];
277 25
278 25
                        // インスタンスを生成して保存
279 25
                        $OrderItem = new OrderItem();
280 25
                        $OrderItem->setShipping($Shipping)
281
                            ->setOrder($Order)
282
                            ->setProductClass($ProductClass)
283 7
                            ->setProduct($Product)
284
                            ->setProductName($Product->getName())
285
                            ->setProductCode($ProductClass->getCode())
286
                            ->setPrice($ProductClass->getPrice02())
287 25
                            ->setQuantity($quantity)
288
                            ->setOrderItemType($ProductOrderType);
289
290 25
                        $ClassCategory1 = $ProductClass->getClassCategory1();
291 25
                        if (!is_null($ClassCategory1)) {
292 25
                            $OrderItem->setClasscategoryName1($ClassCategory1->getName());
293 25
                            $OrderItem->setClassName1($ClassCategory1->getClassName()->getName());
294 25
                        }
295 25
                        $ClassCategory2 = $ProductClass->getClassCategory2();
296 25
                        if (!is_null($ClassCategory2)) {
297 25
                            $OrderItem->setClasscategoryName2($ClassCategory2->getName());
298 25
                            $OrderItem->setClassName2($ClassCategory2->getClassName()->getName());
299 25
                        }
300
                        $Shipping->addOrderItem($OrderItem);
301 25
                        $Order->addOrderItem($OrderItem);
302 25
                        $this->entityManager->persist($OrderItem);
303 25
                    }
304 25
                }
305
            }
306 25
307 25
            // 合計金額の再計算
308 20
            $flowResult = $this->executePurchaseFlow($Order, false);
309 20
            if ($flowResult->hasError()) {
310
                return $this->redirectToRoute('shopping_error');
311 25
            }
312 25
313 25
            $this->entityManager->flush();
314
315
            $event = new EventArgs(
316
                [
317
                    'form' => $form,
318
                    'Order' => $Order,
319 25
                ],
320 25
                $request
321
            );
322
            $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_MULTIPLE_COMPLETE, $event);
323
324
            log_info('複数配送設定処理完了', [$Order->getId()]);
325
326
            $this->entityManager->refresh($Order);
327
328 25
            $quantityByProductClass = [];
329
            foreach ($Order->getProductOrderItems() as $Item) {
330
                $id = $Item->getProductClass()->getId();
331
                if (isset($quantityByProductClass[$id])) {
332 25
                    $quantityByProductClass[$id] += $Item->getQuantity();
333
                } else {
334 25
                    $quantityByProductClass[$id] = $Item->getQuantity();
335
                }
336 25
            }
337 25
            $Cart = $this->cartService->getCart();
338
            if ($Cart) {
339 25
                foreach ($Cart->getCartItems() as $CartItem) {
340
                    $id = $CartItem->getProductClass()->getId();
341 25
                    if (isset($quantityByProductClass[$id])) {
342
                        $CartItem->setQuantity($quantityByProductClass[$id]);
343 25
                    }
344
                }
345 25
346
                $this->cartPurchaseFlow->validate($Cart, new PurchaseContext());
347 25
                $this->cartService->save();
348 25
            }
349 25
350 25
            return $this->redirectToRoute('shopping');
351 14
        }
352
353 25
        return [
354
            'form' => $form->createView(),
355
            'OrderItems' => $OrderItemsForFormBuilder,
356 25
            'compItemQuantities' => $ItemQuantitiesByClassId,
357 25
            'errors' => $errors,
358 25
        ];
359 25
    }
360 25
361
    /**
362
     * 複数配送設定時の新規お届け先の設定
363
     *
364 25
     * 会員ログイン時は会員のお届け先に追加する
365 25
     * 非会員時はセッションに追加する
366
     *
367 25
     * @Route("/shopping/shipping_multiple_edit", name="shopping_shipping_multiple_edit")
368
     * @Template("Shopping/shipping_multiple_edit.twig")
369
     */
370
    public function shippingMultipleEdit(Request $request)
371 4
    {
372 4
        // ログイン状態のチェック.
373 4
        if ($this->orderHelper->isLoginRequired()) {
374 4
            return $this->redirectToRoute('shopping_login');
375
        }
376
377
        // 受注の存在チェック
378
        $preOrderId = $this->cartService->getPreOrderId();
379
        $Order = $this->orderHelper->getPurchaseProcessingOrder($preOrderId);
380
        if (!$Order) {
381
            return $this->redirectToRoute('shopping_error');
382
        }
383
384 8
        /** @var Customer $Customer */
385
        $Customer = $this->getUser();
386
        $CustomerAddress = new CustomerAddress();
387 8
        $builder = $this->formFactory->createBuilder(ShoppingShippingType::class, $CustomerAddress);
388 8
389
        $event = new EventArgs(
390
            [
391
                'builder' => $builder,
392
                'Customer' => $Customer,
393 8
            ],
394 8
            $request
395 8
        );
396
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_MULTIPLE_EDIT_INITIALIZE, $event);
397 8
398
        $form = $builder->getForm();
399 8
400 8
        $form->handleRequest($request);
401
402 8
        if ($form->isSubmitted() && $form->isValid()) {
403
            log_info('複数配送のお届け先追加処理開始');
404 8
405
            if ($this->isGranted('ROLE_USER')) {
406 8
                $CustomerAddresses = $Customer->getCustomerAddresses();
407
408 8
                $count = count($CustomerAddresses);
409
                if ($count >= $this->eccubeConfig['eccube_deliv_addr_max']) {
410 8
                    return [
411 8
                        'error' => trans('common.customer_address_count_is_over', [
412
                            '%eccube_deliv_addr_max%' => $this->eccubeConfig->get('eccube_deliv_addr_max'),
413 8
                        ]),
414
                        'form' => $form->createView(),
415
                    ];
416
                }
417
418
                $CustomerAddress->setCustomer($Customer);
419
                $this->entityManager->persist($CustomerAddress);
420
                $this->entityManager->flush($CustomerAddress);
421
            } else {
422
                // 非会員用のセッションに追加
423
                $CustomerAddresses = $this->session->get(OrderHelper::SESSION_NON_MEMBER_ADDRESSES);
424
                $CustomerAddresses = unserialize($CustomerAddresses);
425
                $CustomerAddresses[] = $CustomerAddress;
426
                $this->session->set(OrderHelper::SESSION_NON_MEMBER_ADDRESSES, serialize($CustomerAddresses));
427
            }
428
429 8
            $event = new EventArgs(
430 8
                [
431 8
                    'form' => $form,
432 8
                    'CustomerAddresses' => $CustomerAddresses,
433
                ],
434
                $request
435 8
            );
436
            $this->eventDispatcher->dispatch(EccubeEvents::FRONT_SHOPPING_SHIPPING_MULTIPLE_EDIT_COMPLETE, $event);
437 8
438 8
            log_info('複数配送のお届け先追加処理完了');
439
440 8
            return $this->redirectToRoute('shopping_shipping_multiple');
441
        }
442 8
443
        return [
444 8
            'form' => $form->createView(),
445
        ];
446 8
    }
447
}
448