Failed Conditions
Push — experimental/sf ( 49de0c...430492 )
by chihiro
27s
created

ShippingController   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 245
Duplicated Lines 2.45 %

Coupling/Cohesion

Components 1
Dependencies 13

Test Coverage

Coverage 82.95%

Importance

Changes 0
Metric Value
dl 6
loc 245
rs 10
c 0
b 0
f 0
ccs 73
cts 88
cp 0.8295
wmc 22
lcom 1
cbo 13

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 19 1
F index() 6 124 19
A previewShippingNotifyMail() 0 4 1
A notifyMail() 0 15 1

How to fix   Duplicated Code   

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:

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 Eccube\Controller\AbstractController;
18
use Eccube\Entity\Order;
19
use Eccube\Entity\OrderItem;
20
use Eccube\Entity\Shipping;
21
use Eccube\Form\Type\Admin\SearchProductType;
22
use Eccube\Form\Type\Admin\ShippingType;
23
use Eccube\Repository\CategoryRepository;
24
use Eccube\Repository\DeliveryRepository;
25
use Eccube\Repository\OrderItemRepository;
26
use Eccube\Repository\ShippingRepository;
27
use Eccube\Service\OrderStateMachine;
28
use Eccube\Service\TaxRuleService;
29
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
30
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
31
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
32
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
33
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
34
use Symfony\Component\Form\FormEvent;
35
use Symfony\Component\Form\FormEvents;
36
use Symfony\Component\HttpFoundation\JsonResponse;
37
use Symfony\Component\HttpFoundation\Request;
38
use Symfony\Component\HttpFoundation\Response;
39
use Symfony\Component\Serializer\SerializerInterface;
40
use Eccube\Service\MailService;
41
42
class ShippingController extends AbstractController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
43
{
44
    /**
45
     * @var OrderItemRepository
46
     */
47
    protected $orderItemRepository;
48
49
    /**
50
     * @var CategoryRepository
51
     */
52
    protected $categoryRepository;
53
54
    /**
55
     * @var DeliveryRepository
56
     */
57
    protected $deliveryRepository;
58
59
    /**
60
     * @var TaxRuleService
61
     */
62
    protected $taxRuleService;
63
64
    /**
65
     * @var ShippingRepository
66
     */
67
    protected $shippingRepository;
68
69
    /**
70
     * @var SerializerInterface
71
     */
72
    protected $serializer;
73
74
    /**
75
     * @var \Eccube\Service\MailService
76
     */
77
    protected $mailService;
78
79
    /**
80
     * @var OrderStateMachine
81
     */
82
    private $orderStateMachine;
83
84
    /**
85
     * EditController constructor.
86
     *
87
     * @param MailService $mailService
0 ignored issues
show
introduced by
Expected 9 spaces after parameter type; 1 found
Loading history...
88
     * @param OrderItemRepository $orderItemRepository
89
     * @param CategoryRepository $categoryRepository
0 ignored issues
show
introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
90
     * @param DeliveryRepository $deliveryRepository
0 ignored issues
show
introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
91
     * @param TaxRuleService $taxRuleService
0 ignored issues
show
introduced by
Expected 6 spaces after parameter type; 1 found
Loading history...
92
     * @param ShippingRepository $shippingRepository
0 ignored issues
show
introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
93
     * @param SerializerInterface $serializer
94
     * @param OrderStateMachine $orderStateMachine
0 ignored issues
show
introduced by
Expected 3 spaces after parameter type; 1 found
Loading history...
95
     */
96 5
    public function __construct(
97
        MailService $mailService,
98
        OrderItemRepository $orderItemRepository,
99
        CategoryRepository $categoryRepository,
100
        DeliveryRepository $deliveryRepository,
101
        TaxRuleService $taxRuleService,
102
        ShippingRepository $shippingRepository,
103
        SerializerInterface $serializer,
104
        OrderStateMachine $orderStateMachine
105
    ) {
106 5
        $this->mailService = $mailService;
107 5
        $this->orderItemRepository = $orderItemRepository;
108 5
        $this->categoryRepository = $categoryRepository;
109 5
        $this->deliveryRepository = $deliveryRepository;
110 5
        $this->taxRuleService = $taxRuleService;
111 5
        $this->shippingRepository = $shippingRepository;
112 5
        $this->serializer = $serializer;
113 5
        $this->orderStateMachine = $orderStateMachine;
114
    }
115
116
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$Order" missing
Loading history...
117
     * 出荷登録/編集画面.
118
     *
119
     * @Route("/%eccube_admin_route%/shipping/{id}/edit", requirements={"id" = "\d+"}, name="admin_shipping_edit")
120
     * @Template("@admin/Order/shipping.twig")
121
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
122 2
    public function index(Request $request, Order $Order)
123
    {
124 2
        $TargetShippings = $Order->getShippings();
125 2
        $OriginShippings = [];
126 2
        $OriginOrderItems = [];
127
128
        // 編集前の受注情報を保持
129 2
        foreach ($TargetShippings as $key => $TargetShipping) {
130 2
            $OriginShippings[$key] = clone $TargetShipping;
131
132
            // 編集前のお届け先のアイテム情報を保持
133 2
            $OriginOrderItems[$key] = new ArrayCollection();
134
135 2
            foreach ($TargetShipping->getOrderItems() as $OrderItem) {
136 2
                $OriginOrderItems[$key]->add($OrderItem);
137
            }
138
        }
139
140 2
        $builder = $this->formFactory->createBuilder();
141
        $builder
142 2
            ->add('shippings', CollectionType::class, [
143 2
                'entry_type' => ShippingType::class,
144 2
                'data' => $TargetShippings,
145
                'allow_add' => true,
146
                'allow_delete' => true,
147
                'prototype' => true,
148
            ]);
149
150
        // 配送先の追加フラグ
151
        $builder
152 2
            ->add('add_shipping', HiddenType::class, [
153 2
                'mapped' => false,
154
            ]);
155
156
        // 配送先の追加フラグが立っている場合は新しいお届け先を追加
157 2
        $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
158 2
            $data = $event->getData();
159 2
            if ($data['add_shipping']) {
160
                $Shippings = $data['shippings'];
161
                $newShipping = ['Delivery' => ''];
162
                $Shippings[] = $newShipping;
163
                $data['shippings'] = $Shippings;
164
                $data['add_shipping'] = '';
165
                $event->setData($data);
166
            }
167 2
        });
168
169 2
        $form = $builder->getForm();
170
171 2
        $form->handleRequest($request);
172
173 2
        if ($form->isSubmitted() && $form->isValid() && $request->get('mode') == 'register') {
174 2
            log_info('出荷登録開始', [$TargetShipping->getId()]);
0 ignored issues
show
Bug introduced by
The variable $TargetShipping seems to be defined by a foreach iteration on line 129. Are you sure the iterator is never empty, otherwise this variable is not defined?

It seems like you are relying on a variable being defined by an iteration:

foreach ($a as $b) {
}

// $b is defined here only if $a has elements, for example if $a is array()
// then $b would not be defined here. To avoid that, we recommend to set a
// default value for $b.


// Better
$b = 0; // or whatever default makes sense in your context
foreach ($a as $b) {
}

// $b is now guaranteed to be defined here.
Loading history...
175
176
            // 削除された項目の削除
177
            /** @var Shipping $OriginShipping */
178 2
            foreach ($OriginShippings as $key => $OriginShipping) {
179
                // 削除された明細の削除
180
                /** @var OrderItem $OriginOrderItem */
181 2
                foreach ($OriginOrderItems[$key] as $OriginOrderItem) {
182 2
                    if (false === $TargetShippings[$key]->getOrderItems()->contains($OriginOrderItem)) {
183
                        $TargetShippings[$key]->removeOrderItem($OriginOrderItem); // 不要かも
184
                        $OriginOrderItem->setShipping(null);
185
                        $Order->removeOrderItem($OriginOrderItem);
186 2
                        $OriginOrderItem->setOrder(null);
187
                    }
188
                }
189
            }
190
191
            // 追加された項目の追加
192 2
            foreach ($TargetShippings as $key => $TargetShipping) {
193 2
                foreach ($TargetShipping->getOrderItems() as $OrderItem) {
194 2
                    $TargetShipping->addOrderItem($OrderItem); // 不要かも
195 2
                    $OrderItem->setShipping($TargetShipping);
196 2
                    $Order->addOrderItem($OrderItem);
197 2
                    $OrderItem->setOrder($Order);
198
                }
199
200 2
                $TargetShipping->setOrder($Order);
201
            }
202
203
            try {
204 2
                foreach ($TargetShippings as $TargetShipping) {
205 2
                    $this->entityManager->persist($TargetShipping);
206
                }
207 2
                $this->entityManager->flush();
208
209 2
                $this->addSuccess('admin.shipping.edit.save.complete', 'admin');
210 2
                $this->addInfo('admin.shipping.edit.save.info', 'admin');
211 2
                log_info('出荷登録完了', [$Order->getId()]);
212
213 2
                return $this->redirectToRoute('admin_shipping_edit', ['id' => $Order->getId()]);
214
            } catch (\Exception $e) {
215
                log_error('出荷登録エラー', [$Order->getId(), $e]);
216
                $this->addError('admin.flash.register_failed', 'admin');
217
            }
218 2
        } elseif ($form->isSubmitted() && $request->get('mode') == 'register' && $form->getErrors(true)) {
219
            $this->addError('admin.flash.register_failed', 'admin');
220
        }
221
222
        // 商品検索フォーム
223 2
        $builder = $this->formFactory
224 2
            ->createBuilder(SearchProductType::class);
225
226 2
        $searchProductModalForm = $builder->getForm();
227
228
        // 配送業者のお届け時間
229 2
        $times = [];
230 2
        $deliveries = $this->deliveryRepository->findAll();
231 2 View Code Duplication
        foreach ($deliveries as $Delivery) {
232 2
            $deliveryTiems = $Delivery->getDeliveryTimes();
233 2
            foreach ($deliveryTiems as $DeliveryTime) {
234 2
                $times[$Delivery->getId()][$DeliveryTime->getId()] = $DeliveryTime->getDeliveryTime();
235
            }
236
        }
237
238
        return [
239 2
            'form' => $form->createView(),
240 2
            'searchProductModalForm' => $searchProductModalForm->createView(),
241 2
            'Order' => $Order,
242 2
            'Shippings' => $TargetShippings,
243 2
            'shippingDeliveryTimes' => $this->serializer->serialize($times, 'json'),
244
        ];
245
    }
246
247
    /**
248
     * @Route("/%eccube_admin_route%/shipping/preview_notify_mail/{id}", requirements={"id" = "\d+"}, name="admin_shipping_preview_notify_mail")
249
     *
250
     * @param Shipping $Shipping
251
     *
252
     * @return Response
253
     *
254
     * @throws \Twig_Error
255
     */
256
    public function previewShippingNotifyMail(Shipping $Shipping)
257
    {
258
        return new Response($this->mailService->getShippingNotifyMailBody($Shipping, $Shipping->getOrder()));
259
    }
260
261
    /**
262
     * @Method("PUT")
263
     * @Route("/%eccube_admin_route%/shipping/notify_mail/{id}", requirements={"id" = "\d+"}, name="admin_shipping_notify_mail")
264
     *
265
     * @param Shipping $Shipping
266
     *
267
     * @return JsonResponse
268
     *
269
     * @throws \Twig_Error
270
     */
271 2
    public function notifyMail(Shipping $Shipping)
272
    {
273 2
        $this->isTokenValid();
274
275 2
        $this->mailService->sendShippingNotifyMail($Shipping);
276
277 2
        $Shipping->setMailSendDate(new \DateTime());
278 2
        $this->shippingRepository->save($Shipping);
279 2
        $this->entityManager->flush();
280
281 2
        return $this->json([
282 2
            'mail' => true,
283
            'shipped' => false,
284
        ]);
285
    }
286
}
287