Failed Conditions
Push — experimental/3.1 ( 0c67c0...62371a )
by chihiro
51:52
created

EditController::edit()   D

Complexity

Conditions 16
Paths 145

Size

Total Lines 210
Code Lines 120

Duplication

Lines 19
Ratio 9.05 %

Importance

Changes 0
Metric Value
cc 16
eloc 120
nc 145
nop 3
dl 19
loc 210
rs 4.5663
c 0
b 0
f 0

How to fix   Long Method    Complexity   

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
namespace Eccube\Controller\Admin\Shipping;
4
5
use Doctrine\Common\Collections\ArrayCollection;
6
use Eccube\Application;
7
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
8
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
9
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
10
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
11
use Symfony\Component\HttpFoundation\Request;
12
13
use Eccube\Common\Constant;
14
use Eccube\Controller\AbstractController;
15
use Eccube\Entity\Shipping;
16
use Eccube\Entity\Master\CsvType;
17
use Eccube\Event\EccubeEvents;
18
use Eccube\Event\EventArgs;
19
use Eccube\Form\Type\AddCartType;
20
use Eccube\Form\Type\Admin\SearchOrderType;
21
use Eccube\Form\Type\Admin\ShippingType;
22
use Eccube\Form\Type\Admin\SearchCustomerType;
23
use Eccube\Form\Type\Admin\SearchProductType;
24
use Eccube\Form\Type\Admin\ShipmentItemType;
25
use Symfony\Component\HttpFoundation\StreamedResponse;
26
27
/**
28
 * // FIXME UrlGenerator で {_admin} を認識しない問題あり
29
 * @Route("/admin/shipping")
30
 */
31
class EditController
32
{
33
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$id" missing
Loading history...
34
     * 出荷登録/編集画面.
35
     *
36
     * @Route("/edit", name="admin/shipping/new")
37
     * @Route("/{id}/edit", requirements={"id" = "\d+"}, name="admin/shipping/edit")
38
     * @Template("shipping/edit.twig")
39
     *
40
     * TODO templateアノテーションを利用するかどうか検討.http://symfony.com/doc/current/best_practices/controllers.html
41
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
42
    public function edit(Application $app, Request $request, $id = null)
43
    {
44
        /* @var $softDeleteFilter \Eccube\Doctrine\Filter\SoftDeleteFilter */
45
        $softDeleteFilter = $app['orm.em']->getFilters()->getFilter('soft_delete');
46
        $softDeleteFilter->setExcludes(array(
47
            'Eccube\Entity\ProductClass',
48
            'Eccube\Entity\Product',
49
        ));
50
51
        $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
        $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
54
        if (is_null($id)) {
55
            // 空のエンティティを作成.
56
            $TargetOrder = new Shipping();
57
        } else {
58
            $TargetOrder = $app['eccube.repository.shipping']->find($id);
59
            if (is_null($TargetOrder)) {
60
                throw new NotFoundHttpException();
61
            }
62
        }
63
64
        // 編集前の受注情報を保持
65
        $OriginOrder = clone $TargetOrder;
66
        $OriginalOrderDetails = new ArrayCollection();
67
        // 編集前のお届け先情報を保持
68
        $OriginalShippings = new ArrayCollection();
0 ignored issues
show
Unused Code introduced by
$OriginalShippings 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...
69
        // 編集前のお届け先のアイテム情報を保持
70
        $OriginalShipmentItems = new ArrayCollection();
0 ignored issues
show
Unused Code introduced by
$OriginalShipmentItems 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...
71
72
        foreach ($TargetOrder->getShipmentItems() as $OrderDetail) {
73
            $OriginalOrderDetails->add($OrderDetail);
74
        }
75
76
        // // 編集前の情報を保持
77
        // foreach ($TargetOrder->getShippings() as $tmpOriginalShippings) {
78
        //     foreach ($tmpOriginalShippings->getShipmentItems() as $tmpOriginalShipmentItem) {
79
        //         // アイテム情報
80
        //         $OriginalShipmentItems->add($tmpOriginalShipmentItem);
81
        //     }
82
        //     // お届け先情報
83
        //     $OriginalShippings->add($tmpOriginalShippings);
84
        // }
85
86
        $builder = $app['form.factory']
87
            ->createBuilder(ShippingType::class, $TargetOrder);
88
89
        $event = new EventArgs(
90
            array(
91
                'builder' => $builder,
92
                'OriginOrder' => $OriginOrder,
93
                'TargetOrder' => $TargetOrder,
94
                'OriginOrderDetails' => $OriginalOrderDetails,
95
            ),
96
            $request
97
        );
98
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_INDEX_INITIALIZE, $event);
99
100
        $form = $builder->getForm();
101
        $form->handleRequest($request);
102
103
        if ($form->isSubmitted()) {
104
            $event = new EventArgs(
105
                array(
106
                    'builder' => $builder,
107
                    'OriginOrder' => $OriginOrder,
108
                    'TargetOrder' => $TargetOrder,
109
                    'OriginOrderDetails' => $OriginalOrderDetails,
110
                ),
111
                $request
112
            );
113
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_INDEX_PROGRESS, $event);
114
115
            // FIXME 税額計算は CalculateService で処理する. ここはテストを通すための暫定処理
116
            // see EditControllerTest::testOrderProcessingWithTax
117
            $OrderDetails = $TargetOrder->getShipmentItems();
118
            $taxtotal = 0;
119
            foreach ($OrderDetails as $OrderDetail) {
120
                $tax = $app['eccube.service.tax_rule']
121
                    ->calcTax($OrderDetail->getPrice(), $OrderDetail->getTaxRate(), $OrderDetail->getTaxRule());
122
                $OrderDetail->setPriceIncTax($OrderDetail->getPrice() + $tax);
123
124
                $taxtotal += $tax * $OrderDetail->getQuantity();
125
            }
126
127
            // 登録ボタン押下
128
            switch ($request->get('mode')) {
129
                case 'register_and_commit':
130
                    if ($form->isValid()) {
131
                        $TargetOrder->setCommitDate(new \DateTime());
132
                    }
133
                    // no break
134
                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...
135
136
                    log_info('出荷登録開始', array($TargetOrder->getId()));
137
                    // TODO 在庫の有無や販売制限数のチェックなども行う必要があるため、完了処理もcaluclatorのように抽象化できないか検討する.
138
                    if ($form->isValid()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
139
140
                        $BaseInfo = $app['eccube.repository.base_info']->get();
0 ignored issues
show
Unused Code introduced by
$BaseInfo 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...
141
142
                        // TODO 後続にある会員情報の更新のように、完了処理もcaluclatorのように抽象化できないか検討する.
143
144
                        // 画面上で削除された明細をremove
145
                        foreach ($OriginalOrderDetails as $OrderDetail) {
146
                            if (false === $TargetOrder->getShipmentItems()->contains($OrderDetail)) {
147
                                $OrderDetail->setShipping(null);
148
                            }
149
                        }
150
151
                        foreach ($TargetOrder->getShipmentItems() as $ShipmentItem) {
152
                            $ShipmentItem->setShipping($TargetOrder);
153
                        }
154
                        $app['orm.em']->persist($TargetOrder);
155
                        $app['orm.em']->flush();
156
157
                        $event = new EventArgs(
158
                            array(
159
                                'form' => $form,
160
                                'OriginOrder' => $OriginOrder,
161
                                'TargetOrder' => $TargetOrder,
162
                                'OriginOrderDetails' => $OriginalOrderDetails,
163
                                //'Customer' => $Customer,
164
                            ),
165
                            $request
166
                        );
167
                        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_INDEX_COMPLETE, $event);
168
169
                        $app->addSuccess('admin.order.save.complete', 'admin');
170
171
                        log_info('受注登録完了', array($TargetOrder->getId()));
172
173
                        return $app->redirect($app->url('admin/shipping/edit', array('id' => $TargetOrder->getId())));
174
                    }
175
176
                    break;
177
178 View Code Duplication
                case 'add_delivery':
179
                    // お届け先情報の新規追加
180
181
                    $form = $builder->getForm();
182
183
                    $Shipping = new \Eccube\Entity\Shipping();
184
                    $TargetOrder->addShipping($Shipping);
185
186
                    $Shipping->setOrder($TargetOrder);
187
188
                    $form->setData($TargetOrder);
189
190
                    break;
191
192
                default:
193
                    break;
194
            }
195
        }
196
197
        // 会員検索フォーム
198
        $builder = $app['form.factory']
199
            ->createBuilder(SearchCustomerType::class);
200
201
        $event = new EventArgs(
202
            array(
203
                'builder' => $builder,
204
                'OriginOrder' => $OriginOrder,
205
                'TargetOrder' => $TargetOrder,
206
                'OriginOrderDetails' => $OriginalOrderDetails,
207
            ),
208
            $request
209
        );
210
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_CUSTOMER_INITIALIZE, $event);
211
212
        $searchCustomerModalForm = $builder->getForm();
213
214
        // 商品検索フォーム
215
        $builder = $app['form.factory']
216
            ->createBuilder(SearchProductType::class);
217
218
        $event = new EventArgs(
219
            array(
220
                'builder' => $builder,
221
                'OriginOrder' => $OriginOrder,
222
                'TargetOrder' => $TargetOrder,
223
                'OriginOrderDetails' => $OriginalOrderDetails,
224
            ),
225
            $request
226
        );
227
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_PRODUCT_INITIALIZE, $event);
228
229
        $searchProductModalForm = $builder->getForm();
230
231
        // 配送業者のお届け時間
232
        $times = array();
233
        $deliveries = $app['eccube.repository.delivery']->findAll();
234 View Code Duplication
        foreach ($deliveries as $Delivery) {
235
            $deliveryTiems = $Delivery->getDeliveryTimes();
236
            foreach ($deliveryTiems as $DeliveryTime) {
237
                $times[$Delivery->getId()][$DeliveryTime->getId()] = $DeliveryTime->getDeliveryTime();
238
            }
239
        }
240
241
        return [
242
            'form' => $form->createView(),
243
            'shippingForm' => $form->createView(),
244
            'searchCustomerModalForm' => $searchCustomerModalForm->createView(),
245
            'searchProductModalForm' => $searchProductModalForm->createView(),
246
            'Order' => $TargetOrder, // Deprecated
247
            'Shipping' => $TargetOrder,
248
            'id' => $id,
249
            'shippingDeliveryTimes' => $app['serializer']->serialize($times, 'json'),
250
        ];
251
    }
252
253
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$page_no" missing
Loading history...
254
     * @Route("/search/product", name="admin_shipping_search_product")
255
     * @Security("has_role('ROLE_ADMIN')")
256
     * @Template("shipping/search_product.twig")
257
     *
258
     * @param Application $app
259
     * @return \Symfony\Component\HttpFoundation\Response
260
     */
261
    public function searchProduct(Application $app, Request $request, $page_no = null)
262
    {
263
        if ($request->isXmlHttpRequest()) {
264
            $app['monolog']->addDebug('search product start.');
265
            $page_count = $app['config']['default_page_count'];
266
            $session = $app['session'];
267
268 View Code Duplication
            if ('POST' === $request->getMethod()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
269
270
                $page_no = 1;
271
272
                $searchData = array(
273
                    'id' => $request->get('id'),
274
                );
275
276
                if ($categoryId = $request->get('category_id')) {
277
                    $Category = $app['eccube.repository.category']->find($categoryId);
278
                    $searchData['category_id'] = $Category;
279
                }
280
281
                $session->set('eccube.admin.order.product.search', $searchData);
282
                $session->set('eccube.admin.order.product.search.page_no', $page_no);
283
            } else {
284
                $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...
285
                if (is_null($page_no)) {
286
                    $page_no = intval($session->get('eccube.admin.order.product.search.page_no'));
287
                } else {
288
                    $session->set('eccube.admin.order.product.search.page_no', $page_no);
289
                }
290
            }
291
            // TODO ShipmentItemRepository に移動
292
            $qb = $app['eccube.repository.shipment_item']->createQueryBuilder('s')
293
                ->where('s.Shipping is null AND s.Order is not null')
294
                ->andWhere('s.OrderItemType in (1, 2)');
295
296
            $event = new EventArgs(
297
                array(
298
                    'qb' => $qb,
299
                    'searchData' => $searchData,
300
                ),
301
                $request
302
            );
303
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_PRODUCT_SEARCH, $event);
304
305
            /** @var \Knp\Component\Pager\Pagination\SlidingPagination $pagination */
306
            $pagination = $app['paginator']()->paginate(
307
                $qb,
308
                $page_no,
309
                $page_count,
310
                array('wrap-queries' => true)
311
            );
312
313
            $ShipmentItems = $pagination->getItems();
314
315
            if (empty($ShipmentItems)) {
316
                $app['monolog']->addDebug('search product not found.');
317
            }
318
319
            $forms = array();
320 View Code Duplication
            foreach ($ShipmentItems as $ShipmentItem) {
321
                /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
322
                $builder = $app['form.factory']->createNamedBuilder('', ShipmentItemType::class, $ShipmentItem);
323
                $addCartForm = $builder->getForm();
324
                $forms[$ShipmentItem->getId()] = $addCartForm->createView();
325
            }
326
327
            $event = new EventArgs(
328
                array(
329
                    'forms' => $forms,
330
                    'ShipmentItems' => $ShipmentItems,
331
                    'pagination' => $pagination,
332
                ),
333
                $request
334
            );
335
            $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_PRODUCT_COMPLETE, $event);
336
337
            return [
338
                'forms' => $forms,
339
                'ShipmentItems' => $ShipmentItems,
340
                'pagination' => $pagination,
341
            ];
342
        }
343
    }
344
}
345