Failed Conditions
Pull Request — experimental/sf (#3241)
by k-yamamura
43:19 queued 23:09
created

MypageController   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 337
Duplicated Lines 17.8 %

Coupling/Cohesion

Components 1
Dependencies 20

Test Coverage

Coverage 87.79%

Importance

Changes 0
Metric Value
dl 60
loc 337
ccs 115
cts 131
cp 0.8779
rs 10
c 0
b 0
f 0
wmc 24
lcom 1
cbo 20

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 13 13 1
A login() 34 35 4
A index() 0 31 1
A history() 0 29 2
D order() 13 88 12
A favorite() 0 30 2
A delete() 0 27 2

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\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 View Code Duplication
    public function login(Request $request, AuthenticationUtils $utils)
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...
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
        if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
113
            $Customer = $this->getUser();
114
            if ($Customer instanceof Customer) {
115
                $builder->get('login_email')
116
                    ->setData($Customer->getEmail());
117
            }
118
        }
119
120 1
        $event = new EventArgs(
121
            [
122 1
                'builder' => $builder,
123
            ],
124 1
            $request
125
        );
126 1
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_MYPAGE_MYPAGE_LOGIN_INITIALIZE, $event);
127
128 1
        $form = $builder->getForm();
129
130
        return [
131 1
            'error' => $utils->getLastAuthenticationError(),
132 1
            'form' => $form->createView(),
133
        ];
134
    }
135
136
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$paginator" missing
Loading history...
137
     * マイページ.
138
     *
139
     * @Route("/mypage/", name="mypage")
140
     * @Template("Mypage/index.twig")
141
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
142 1
    public function index(Request $request, Paginator $paginator)
143
    {
144 1
        $Customer = $this->getUser();
145
146
        // 購入処理中/決済処理中ステータスの受注を非表示にする.
147 1
        $this->entityManager
148 1
            ->getFilters()
149 1
            ->enable('incomplete_order_status_hidden');
150
151
        // paginator
152 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...
153
154 1
        $event = new EventArgs(
155
            [
156 1
                'qb' => $qb,
157 1
                'Customer' => $Customer,
158
            ],
159 1
            $request
160
        );
161 1
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_MYPAGE_MYPAGE_INDEX_SEARCH, $event);
162
163 1
        $pagination = $paginator->paginate(
164 1
            $qb,
165 1
            $request->get('pageno', 1),
166 1
            $this->eccubeConfig['eccube_search_pmax']
167
        );
168
169
        return [
170 1
            'pagination' => $pagination,
171
        ];
172
    }
173
174
    /**
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...
175
     * 購入履歴詳細を表示する.
176
     *
177
     * @Route("/mypage/history/{order_no}", name="mypage_history")
178
     * @Template("Mypage/history.twig")
179
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
180 2
    public function history(Request $request, $order_no)
181
    {
182 2
        $this->entityManager->getFilters()
183 2
            ->enable('incomplete_order_status_hidden');
184 2
        $Order = $this->orderRepository->findOneBy(
185
            [
186 2
                'order_no' => $order_no,
187 2
                'Customer' => $this->getUser(),
188
            ]
189
        );
190
191 2
        $event = new EventArgs(
192
            [
193 2
                'Order' => $Order,
194
            ],
195 2
            $request
196
        );
197 2
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_MYPAGE_MYPAGE_HISTORY_INITIALIZE, $event);
198
199 2
        $Order = $event->getArgument('Order');
200
201 2
        if (!$Order) {
202 2
            throw new NotFoundHttpException();
203
        }
204
205
        return [
206
            'Order' => $Order,
207
        ];
208
    }
209
210
    /**
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...
211
     * 再購入を行う.
212
     *
213
     * @Route("/mypage/order/{order_no}", name="mypage_order")
214
     * @Method("PUT")
215
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
216 1
    public function order(Request $request, $order_no)
217
    {
218 1
        $this->isTokenValid();
219
220 1
        log_info('再注文開始', [$order_no]);
221
222 1
        $Customer = $this->getUser();
223
224
        /* @var $Order \Eccube\Entity\Order */
225 1
        $Order = $this->orderRepository->findOneBy(
226
            [
227 1
                'order_no' => $order_no,
228 1
                'Customer' => $Customer,
229
            ]
230
        );
231
232 1
        $event = new EventArgs(
233
            [
234 1
                'Order' => $Order,
235 1
                'Customer' => $Customer,
236
            ],
237 1
            $request
238
        );
239 1
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_MYPAGE_MYPAGE_ORDER_INITIALIZE, $event);
240
241 1
        if (!$Order) {
242
            log_info('対象の注文が見つかりません', [$order_no]);
243
            throw new NotFoundHttpException();
244
        }
245
246
        // エラーメッセージの配列
247 1
        $errorMessages = [];
248
249 1
        foreach ($Order->getOrderItems() as $OrderItem) {
250
            try {
251 1
                if ($OrderItem->getProduct() &&
252 1
                    $OrderItem->getProductClass()
253
                ) {
254 1
                    $this->cartService->addProduct($OrderItem->getProductClass(), $OrderItem->getQuantity());
255
256
                    // 明細の正規化
257 1
                    $Carts = $this->cartService->getCarts();
258 1 View Code Duplication
                    foreach ($Carts as $Cart) {
259 1
                        $result = $this->purchaseFlow->calculate($Cart, new PurchaseContext($Cart, $this->getUser()));
260
                        // 復旧不可のエラーが発生した場合は追加した明細を削除.
261 1
                        if ($result->hasError()) {
262
                            $this->cartService->removeProduct($OrderItem->getProductClass());
263
                            foreach ($result->getErrors() as $error) {
264
                                $errorMessages[] = $error->getMessage();
265
                            }
266
                        }
267 1
                        foreach ($result->getWarning() as $warning) {
268 1
                            $errorMessages[] = $warning->getMessage();
269
                        }
270
                    }
271
272 1
                    $this->cartService->save();
273
                } else {
274 1
                    log_info(trans('cart.product.delete'), [$order_no]);
275 1
                    $this->addRequestError('cart.product.delete');
276
                }
277
            } catch (CartException $e) {
278
                log_info($e->getMessage(), [$order_no]);
279 1
                $this->addRequestError($e->getMessage());
280
            }
281
        }
282
283 1
        foreach ($errorMessages as $errorMessage) {
284
            $this->addRequestError($errorMessage);
285
        }
286
287 1
        $event = new EventArgs(
288
            [
289 1
                'Order' => $Order,
290 1
                'Customer' => $Customer,
291
            ],
292 1
            $request
293
        );
294 1
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_MYPAGE_MYPAGE_ORDER_COMPLETE, $event);
295
296 1
        if ($event->getResponse() !== null) {
297
            return $event->getResponse();
298
        }
299
300 1
        log_info('再注文完了', [$order_no]);
301
302 1
        return $this->redirect($this->generateUrl('cart'));
303
    }
304
305
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$paginator" missing
Loading history...
306
     * お気に入り商品を表示する.
307
     *
308
     * @Route("/mypage/favorite", name="mypage_favorite")
309
     * @Template("Mypage/favorite.twig")
310
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
311 2
    public function favorite(Request $request, Paginator $paginator)
312
    {
313 2
        if (!$this->BaseInfo->isOptionFavoriteProduct()) {
314
            throw new NotFoundHttpException();
315
        }
316 2
        $Customer = $this->getUser();
317
318
        // paginator
319 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...
320
321 2
        $event = new EventArgs(
322
            [
323 2
                'qb' => $qb,
324 2
                'Customer' => $Customer,
325
            ],
326 2
            $request
327
        );
328 2
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_MYPAGE_MYPAGE_FAVORITE_SEARCH, $event);
329
330 2
        $pagination = $paginator->paginate(
331 2
            $qb,
332 2
            $request->get('pageno', 1),
333 2
            $this->eccubeConfig['eccube_search_pmax'],
334 2
            ['wrap-queries' => true]
335
        );
336
337
        return [
338 2
            'pagination' => $pagination,
339
        ];
340
    }
341
342
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$CustomerFavoriteProduct" missing
Loading history...
343
     * お気に入り商品を削除する.
344
     *
345
     * @Method("DELETE")
346
     * @Route("/mypage/favorite/{id}/delete", name="mypage_favorite_delete", requirements={"id" = "\d+"})
347
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
348 1
    public function delete(Request $request, CustomerFavoriteProduct $CustomerFavoriteProduct)
349
    {
350 1
        $this->isTokenValid();
351
352 1
        $Customer = $this->getUser();
353
354 1
        log_info('お気に入り商品削除開始', [$Customer->getId(), $CustomerFavoriteProduct->getId()]);
355
356 1
        if ($Customer->getId() !== $CustomerFavoriteProduct->getCustomer()
357 1
                ->getId()) {
358
            throw new BadRequestHttpException();
359
        }
360
361 1
        $this->customerFavoriteProductRepository->delete($CustomerFavoriteProduct);
362
363 1
        $event = new EventArgs(
364
            [
365 1
                'Customer' => $Customer,
366 1
                'CustomerFavoriteProduct' => $CustomerFavoriteProduct,
367 1
            ], $request
368
        );
369 1
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_MYPAGE_MYPAGE_DELETE_COMPLETE, $event);
370
371 1
        log_info('お気に入り商品削除完了', [$Customer->getId(), $CustomerFavoriteProduct->getId()]);
372
373 1
        return $this->redirect($this->generateUrl('mypage_favorite'));
374
    }
375
}
376