Failed Conditions
Pull Request — experimental/sf (#3241)
by Kiyotaka
276:13 queued 265:05
created

MypageController::order()   D

Complexity

Conditions 12
Paths 257

Size

Total Lines 88

Duplication

Lines 13
Ratio 14.77 %

Code Coverage

Tests 37
CRAP Score 13.0792

Importance

Changes 0
Metric Value
cc 12
nc 257
nop 2
dl 13
loc 88
ccs 37
cts 46
cp 0.8043
crap 13.0792
rs 4.5984
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
/*
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\Mypage;
15
16
use Eccube\Controller\AbstractController;
17
use Eccube\Entity\BaseInfo;
18
use Eccube\Entity\Customer;
19
use Eccube\Entity\CustomerFavoriteProduct;
20
use Eccube\Event\EccubeEvents;
21
use Eccube\Event\EventArgs;
22
use Eccube\Exception\CartException;
23
use Eccube\Form\Type\Front\CustomerLoginType;
24
use Eccube\Repository\CustomerFavoriteProductRepository;
25
use Eccube\Repository\OrderRepository;
26
use Eccube\Repository\ProductRepository;
27
use Eccube\Service\CartService;
28
use Eccube\Service\PurchaseFlow\PurchaseContext;
29
use Eccube\Service\PurchaseFlow\PurchaseFlow;
30
use Knp\Component\Pager\Paginator;
31
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
32
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
33
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
34
use Symfony\Component\HttpFoundation\Request;
35
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
36
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
37
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
38
39
class MypageController extends AbstractController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
40
{
41
    /**
42
     * @var ProductRepository
43
     */
44
    protected $productRepository;
45
46
    /**
47
     * @var CustomerFavoriteProductRepository
48
     */
49
    protected $customerFavoriteProductRepository;
50
51
    /**
52
     * @var BaseInfo
53
     */
54
    protected $BaseInfo;
55
56
    /**
57
     * @var CartService
58
     */
59
    protected $cartService;
60
61
    /**
62
     * @var OrderRepository
63
     */
64
    protected $orderRepository;
65
66
    /**
67
     * @var PurchaseFlow
68
     */
69
    protected $purchaseFlow;
70
71
    /**
72
     * MypageController constructor.
73
     *
74
     * @param OrderRepository $orderRepository
0 ignored issues
show
introduced by
Expected 19 spaces after parameter type; 1 found
Loading history...
75
     * @param CustomerFavoriteProductRepository $customerFavoriteProductRepository
76
     * @param CartService $cartService
0 ignored issues
show
introduced by
Expected 23 spaces after parameter type; 1 found
Loading history...
77
     * @param BaseInfo $baseInfo
0 ignored issues
show
introduced by
Expected 26 spaces after parameter type; 1 found
Loading history...
78
     * @param PurchaseFlow $purchaseFlow
0 ignored issues
show
introduced by
Expected 22 spaces after parameter type; 1 found
Loading history...
79
     */
80 9 View Code Duplication
    public function __construct(
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
81
        OrderRepository $orderRepository,
82
        CustomerFavoriteProductRepository $customerFavoriteProductRepository,
83
        CartService $cartService,
84
        BaseInfo $baseInfo,
85
        PurchaseFlow $purchaseFlow
86
    ) {
87 9
        $this->orderRepository = $orderRepository;
88 9
        $this->customerFavoriteProductRepository = $customerFavoriteProductRepository;
89 9
        $this->BaseInfo = $baseInfo;
90 9
        $this->cartService = $cartService;
91 9
        $this->purchaseFlow = $purchaseFlow;
92
    }
93
94
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$utils" missing
Loading history...
95
     * ログイン画面.
96
     *
97
     * @Route("/mypage/login", name="mypage_login")
98
     * @Template("Mypage/login.twig")
99
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
100 2
    public function login(Request $request, AuthenticationUtils $utils)
101
    {
102 2
        if ($this->isGranted('IS_AUTHENTICATED_FULLY')) {
103 1
            log_info('認証済のためログイン処理をスキップ');
104
105 1
            return $this->redirectToRoute('mypage');
106
        }
107
108
        /* @var $form \Symfony\Component\Form\FormInterface */
109 1
        $builder = $this->formFactory
110 1
            ->createNamedBuilder('', CustomerLoginType::class);
111
112 1
        $builder->get('login_memory')->setData((bool) $request->getSession()->get('_security.login_memory'));
113
114 1
        if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
115
            $Customer = $this->getUser();
116
            if ($Customer instanceof Customer) {
117
                $builder->get('login_email')
118
                    ->setData($Customer->getEmail());
119
            }
120
        }
121
122 1
        $event = new EventArgs(
123
            [
124 1
                'builder' => $builder,
125
            ],
126 1
            $request
127
        );
128 1
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_MYPAGE_MYPAGE_LOGIN_INITIALIZE, $event);
129
130 1
        $form = $builder->getForm();
131
132
        return [
133 1
            'error' => $utils->getLastAuthenticationError(),
134 1
            'form' => $form->createView(),
135
        ];
136
    }
137
138
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$paginator" missing
Loading history...
139
     * マイページ.
140
     *
141
     * @Route("/mypage/", name="mypage")
142
     * @Template("Mypage/index.twig")
143
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
144 1
    public function index(Request $request, Paginator $paginator)
145
    {
146 1
        $Customer = $this->getUser();
147
148
        // 購入処理中/決済処理中ステータスの受注を非表示にする.
149 1
        $this->entityManager
150 1
            ->getFilters()
151 1
            ->enable('incomplete_order_status_hidden');
152
153
        // paginator
154 1
        $qb = $this->orderRepository->getQueryBuilderByCustomer($Customer);
0 ignored issues
show
Documentation introduced by
$Customer is of type null|object, but the function expects a object<Eccube\Entity\Customer>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
155
156 1
        $event = new EventArgs(
157
            [
158 1
                'qb' => $qb,
159 1
                'Customer' => $Customer,
160
            ],
161 1
            $request
162
        );
163 1
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_MYPAGE_MYPAGE_INDEX_SEARCH, $event);
164
165 1
        $pagination = $paginator->paginate(
166 1
            $qb,
167 1
            $request->get('pageno', 1),
168 1
            $this->eccubeConfig['eccube_search_pmax']
169
        );
170
171
        return [
172 1
            'pagination' => $pagination,
173
        ];
174
    }
175
176
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$order_no" missing
Loading history...
177
     * 購入履歴詳細を表示する.
178
     *
179
     * @Route("/mypage/history/{order_no}", name="mypage_history")
180
     * @Template("Mypage/history.twig")
181
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
182 2
    public function history(Request $request, $order_no)
183
    {
184 2
        $this->entityManager->getFilters()
185 2
            ->enable('incomplete_order_status_hidden');
186 2
        $Order = $this->orderRepository->findOneBy(
187
            [
188 2
                'order_no' => $order_no,
189 2
                'Customer' => $this->getUser(),
190
            ]
191
        );
192
193 2
        $event = new EventArgs(
194
            [
195 2
                'Order' => $Order,
196
            ],
197 2
            $request
198
        );
199 2
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_MYPAGE_MYPAGE_HISTORY_INITIALIZE, $event);
200
201 2
        $Order = $event->getArgument('Order');
202
203 2
        if (!$Order) {
204 2
            throw new NotFoundHttpException();
205
        }
206
207
        return [
208
            'Order' => $Order,
209
        ];
210
    }
211
212
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$order_no" missing
Loading history...
213
     * 再購入を行う.
214
     *
215
     * @Route("/mypage/order/{order_no}", name="mypage_order")
216
     * @Method("PUT")
217
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
218 1
    public function order(Request $request, $order_no)
219
    {
220 1
        $this->isTokenValid();
221
222 1
        log_info('再注文開始', [$order_no]);
223
224 1
        $Customer = $this->getUser();
225
226
        /* @var $Order \Eccube\Entity\Order */
227 1
        $Order = $this->orderRepository->findOneBy(
228
            [
229 1
                'order_no' => $order_no,
230 1
                'Customer' => $Customer,
231
            ]
232
        );
233
234 1
        $event = new EventArgs(
235
            [
236 1
                'Order' => $Order,
237 1
                'Customer' => $Customer,
238
            ],
239 1
            $request
240
        );
241 1
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_MYPAGE_MYPAGE_ORDER_INITIALIZE, $event);
242
243 1
        if (!$Order) {
244
            log_info('対象の注文が見つかりません', [$order_no]);
245
            throw new NotFoundHttpException();
246
        }
247
248
        // エラーメッセージの配列
249 1
        $errorMessages = [];
250
251 1
        foreach ($Order->getOrderItems() as $OrderItem) {
252
            try {
253 1
                if ($OrderItem->getProduct() &&
254 1
                    $OrderItem->getProductClass()
255
                ) {
256 1
                    $this->cartService->addProduct($OrderItem->getProductClass(), $OrderItem->getQuantity());
257
258
                    // 明細の正規化
259 1
                    $Carts = $this->cartService->getCarts();
260 1 View Code Duplication
                    foreach ($Carts as $Cart) {
261 1
                        $result = $this->purchaseFlow->calculate($Cart, new PurchaseContext($Cart, $this->getUser()));
262
                        // 復旧不可のエラーが発生した場合は追加した明細を削除.
263 1
                        if ($result->hasError()) {
264
                            $this->cartService->removeProduct($OrderItem->getProductClass());
265
                            foreach ($result->getErrors() as $error) {
266
                                $errorMessages[] = $error->getMessage();
267
                            }
268
                        }
269 1
                        foreach ($result->getWarning() as $warning) {
270 1
                            $errorMessages[] = $warning->getMessage();
271
                        }
272
                    }
273
274 1
                    $this->cartService->save();
275
                } else {
276 1
                    log_info(trans('cart.product.delete'), [$order_no]);
277 1
                    $this->addRequestError('cart.product.delete');
278
                }
279
            } catch (CartException $e) {
280
                log_info($e->getMessage(), [$order_no]);
281 1
                $this->addRequestError($e->getMessage());
282
            }
283
        }
284
285 1
        foreach ($errorMessages as $errorMessage) {
286
            $this->addRequestError($errorMessage);
287
        }
288
289 1
        $event = new EventArgs(
290
            [
291 1
                'Order' => $Order,
292 1
                'Customer' => $Customer,
293
            ],
294 1
            $request
295
        );
296 1
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_MYPAGE_MYPAGE_ORDER_COMPLETE, $event);
297
298 1
        if ($event->getResponse() !== null) {
299
            return $event->getResponse();
300
        }
301
302 1
        log_info('再注文完了', [$order_no]);
303
304 1
        return $this->redirect($this->generateUrl('cart'));
305
    }
306
307
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$paginator" missing
Loading history...
308
     * お気に入り商品を表示する.
309
     *
310
     * @Route("/mypage/favorite", name="mypage_favorite")
311
     * @Template("Mypage/favorite.twig")
312
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
313 2
    public function favorite(Request $request, Paginator $paginator)
314
    {
315 2
        if (!$this->BaseInfo->isOptionFavoriteProduct()) {
316
            throw new NotFoundHttpException();
317
        }
318 2
        $Customer = $this->getUser();
319
320
        // paginator
321 2
        $qb = $this->customerFavoriteProductRepository->getQueryBuilderByCustomer($Customer);
0 ignored issues
show
Documentation introduced by
$Customer is of type null|object, but the function expects a object<Eccube\Entity\Customer>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
322
323 2
        $event = new EventArgs(
324
            [
325 2
                'qb' => $qb,
326 2
                'Customer' => $Customer,
327
            ],
328 2
            $request
329
        );
330 2
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_MYPAGE_MYPAGE_FAVORITE_SEARCH, $event);
331
332 2
        $pagination = $paginator->paginate(
333 2
            $qb,
334 2
            $request->get('pageno', 1),
335 2
            $this->eccubeConfig['eccube_search_pmax'],
336 2
            ['wrap-queries' => true]
337
        );
338
339
        return [
340 2
            'pagination' => $pagination,
341
        ];
342
    }
343
344
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$CustomerFavoriteProduct" missing
Loading history...
345
     * お気に入り商品を削除する.
346
     *
347
     * @Method("DELETE")
348
     * @Route("/mypage/favorite/{id}/delete", name="mypage_favorite_delete", requirements={"id" = "\d+"})
349
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
350 1
    public function delete(Request $request, CustomerFavoriteProduct $CustomerFavoriteProduct)
351
    {
352 1
        $this->isTokenValid();
353
354 1
        $Customer = $this->getUser();
355
356 1
        log_info('お気に入り商品削除開始', [$Customer->getId(), $CustomerFavoriteProduct->getId()]);
357
358 1
        if ($Customer->getId() !== $CustomerFavoriteProduct->getCustomer()
359 1
                ->getId()) {
360
            throw new BadRequestHttpException();
361
        }
362
363 1
        $this->customerFavoriteProductRepository->delete($CustomerFavoriteProduct);
364
365 1
        $event = new EventArgs(
366
            [
367 1
                'Customer' => $Customer,
368 1
                'CustomerFavoriteProduct' => $CustomerFavoriteProduct,
369 1
            ], $request
370
        );
371 1
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_MYPAGE_MYPAGE_DELETE_COMPLETE, $event);
372
373 1
        log_info('お気に入り商品削除完了', [$Customer->getId(), $CustomerFavoriteProduct->getId()]);
374
375 1
        return $this->redirect($this->generateUrl('mypage_favorite'));
376
    }
377
}
378