Completed
Push — support-coverage ( 9b57a3...b5dae6 )
by Kentaro
41:38
created

MailController   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 274
Duplicated Lines 13.5 %

Coupling/Cohesion

Components 1
Dependencies 14

Test Coverage

Coverage 76.55%

Importance

Changes 0
Metric Value
dl 37
loc 274
ccs 98
cts 128
cp 0.7655
rs 10
c 0
b 0
f 0
wmc 17
lcom 1
cbo 14

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 1
B view() 0 26 3
A createBody() 0 8 1
B index() 18 89 5
C mailAll() 19 99 7

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
 * This file is part of EC-CUBE
4
 *
5
 * Copyright(c) 2000-2015 LOCKON CO.,LTD. All Rights Reserved.
6
 *
7
 * http://www.lockon.co.jp/
8
 *
9
 * This program is free software; you can redistribute it and/or
10
 * modify it under the terms of the GNU General Public License
11
 * as published by the Free Software Foundation; either version 2
12
 * of the License, or (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22
 */
23
24
namespace Eccube\Controller\Admin\Order;
25
26
use Eccube\Controller\AbstractController;
27
use Eccube\Entity\MailHistory;
28
use Eccube\Entity\Order;
29
use Eccube\Event\EccubeEvents;
30
use Eccube\Event\EventArgs;
31
use Eccube\Form\Type\Admin\MailType;
32
use Eccube\Repository\MailHistoryRepository;
33
use Eccube\Repository\OrderRepository;
34
use Eccube\Service\MailService;
35
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
36
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
37
use Symfony\Component\HttpFoundation\Request;
38
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
39
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
40
41
class MailController extends AbstractController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
42
{
43
    /**
44
     * @var MailService
45
     */
46
    protected $mailService;
47
48
    /**
49
     * @var MailHistoryRepository
50
     */
51
    protected $mailHistoryRepository;
52
53
    /**
54
     * @Inject(OrderRepository::class)
55
     *
56
     * @var OrderRepository
57
     */
58
    protected $orderRepository;
59
60
    /**
61
     * MailController constructor.
62
     *
63
     * @param MailService $mailService
0 ignored issues
show
introduced by
Expected 11 spaces after parameter type; 1 found
Loading history...
64
     * @param MailHistoryRepository $mailHistoryRepository
65
     * @param OrderRepository $orderRepository
0 ignored issues
show
introduced by
Expected 7 spaces after parameter type; 1 found
Loading history...
66
     */
67 5
    public function __construct(
68
        MailService $mailService,
69
        MailHistoryRepository $mailHistoryRepository,
70
        OrderRepository $orderRepository
71
    ) {
72 5
        $this->mailService = $mailService;
73 5
        $this->mailHistoryRepository = $mailHistoryRepository;
74 5
        $this->orderRepository = $orderRepository;
75
    }
76
77
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$Order" missing
Loading history...
78
     * @Route("/%eccube_admin_route%/order/{id}/mail", requirements={"id" = "\d+"}, name="admin_order_mail")
79
     * @Template("@admin/Order/mail.twig")
80
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
81 2
    public function index(Request $request, Order $Order)
82
    {
83 2
        $MailHistories = $this->mailHistoryRepository->findBy(['Order' => $Order]);
84
85 2
        $builder = $this->formFactory->createBuilder(MailType::class);
86
87 2
        $event = new EventArgs(
88
            [
89 2
                'builder' => $builder,
90 2
                'Order' => $Order,
91 2
                'MailHistories' => $MailHistories,
92
            ],
93 2
            $request
94
        );
95 2
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_MAIL_INDEX_INITIALIZE, $event);
96
97 2
        $form = $builder->getForm();
98
99 2
        if ('POST' === $request->getMethod()) {
100 1
            $form->handleRequest($request);
101
102 1
            $mode = $request->get('mode');
103
104
            // テンプレート変更の場合は. バリデーション前に内容差し替え.
105 1
            if ($mode == 'change') {
106 View Code Duplication
                if ($form->get('template')->isValid()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
107
                    /** @var $data \Eccube\Entity\MailTemplate */
108
                    $MailTemplate = $form->get('template')->getData();
109
                    $form = $builder->getForm();
110
                    $event = new EventArgs(
111
                        [
112
                            'form' => $form,
113
                            'Order' => $Order,
114
                            'MailTemplate' => $MailTemplate,
115
                        ],
116
                        $request
117
                    );
118
                    $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_MAIL_INDEX_CHANGE, $event);
119
                    $form->get('template')->setData($MailTemplate);
120
                    $form->get('mail_subject')->setData($MailTemplate->getMailSubject());
121
                    $form->get('mail_header')->setData($MailTemplate->getMailHeader());
122
                    $form->get('mail_footer')->setData($MailTemplate->getMailFooter());
123
                }
124
            } else {
125 1
                if ($form->isValid()) {
126 1
                    $data = $form->getData();
127 1
                    $body = $this->createBody($data['mail_header'], $data['mail_footer'], $Order);
128
129
                    // メール送信
130 1
                    $this->mailService->sendAdminOrderMail($Order, $data);
131
132
                    // 送信履歴を保存.
133 1
                    $MailTemplate = $form->get('template')->getData();
134 1
                    $MailHistory = new MailHistory();
135
                    $MailHistory
136 1
                        ->setMailSubject($data['mail_subject'])
137 1
                        ->setMailBody($body)
138 1
                        ->setSendDate(new \DateTime())
139 1
                        ->setOrder($Order);
140
141 1
                    $this->entityManager->persist($MailHistory);
142 1
                    $this->entityManager->flush($MailHistory);
0 ignored issues
show
Unused Code introduced by
The call to EntityManagerInterface::flush() has too many arguments starting with $MailHistory.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
143
144 1
                    $event = new EventArgs(
145
                        [
146 1
                            'form' => $form,
147 1
                            'Order' => $Order,
148 1
                            'MailTemplate' => $MailTemplate,
149 1
                            'MailHistory' => $MailHistory,
150
                        ],
151 1
                        $request
152
                    );
153 1
                    $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_MAIL_INDEX_COMPLETE, $event);
154
155 1
                    return $this->redirectToRoute('admin_order_page', ['page_no' => $this->session->get('eccube.admin.order.search.page_no', 1)]);
156
                }
157
            }
158
        }
159
160
        // 本文確認用
161 1
        $body = $this->createBody('', '', $Order);
162
163
        return [
164 1
            'form' => $form->createView(),
165 1
            'Order' => $Order,
166 1
            'MailHistories' => $MailHistories,
167 1
            'body' => $body,
168
        ];
169
    }
170
171
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
172
     * @Route("/%eccube_admin_route%/order/mail/view", name="admin_order_mail_view")
173
     * @Template("@admin/Order/mail_view.twig")
174
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
175 1
    public function view(Request $request)
176
    {
177 1
        if (!$request->isXmlHttpRequest()) {
178
            throw new BadRequestHttpException();
179
        }
180
181 1
        $id = $request->get('id');
182 1
        $MailHistory = $this->mailHistoryRepository->find($id);
183
184 1
        if (null === $MailHistory) {
185
            throw new NotFoundHttpException('history not found.');
186
        }
187
188 1
        $event = new EventArgs(
189
            [
190 1
                'MailHistory' => $MailHistory,
191
            ],
192 1
            $request
193
        );
194 1
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_MAIL_VIEW_COMPLETE, $event);
195
196
        return [
197 1
            'mail_subject' => $MailHistory->getMailSubject(),
198 1
            'body' => $MailHistory->getMailBody(),
199
        ];
200
    }
201
202
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
203
     * @Route("/%eccube_admin_route%/order/mail/mail_all", name="admin_order_mail_all")
204
     * @Template("@admin/Order/mail_all.twig")
205
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
206 2
    public function mailAll(Request $request)
207
    {
208 2
        $builder = $this->formFactory->createBuilder(MailType::class);
209
210 2
        $event = new EventArgs(
211
            [
212 2
                'builder' => $builder,
213
            ],
214 2
            $request
215
        );
216 2
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_MAIL_MAIL_ALL_INITIALIZE, $event);
217
218 2
        $form = $builder->getForm();
219
220 2
        $ids = '';
0 ignored issues
show
Unused Code introduced by
$ids 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...
221 2
        if ('POST' === $request->getMethod()) {
222 1
            $form->handleRequest($request);
223
224 1
            $mode = $request->get('mode');
225
226 1
            $ids = $request->get('ids');
227
228
            // テンプレート変更の場合は. バリデーション前に内容差し替え.
229 1
            if ($mode == 'change') {
230 View Code Duplication
                if ($form->get('template')->isValid()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
231
                    /** @var $data \Eccube\Entity\MailTemplate */
232
                    $MailTemplate = $form->get('template')->getData();
233
                    $form = $builder->getForm();
234
235
                    $event = new EventArgs(
236
                        [
237
                            'form' => $form,
238
                            'MailTemplate' => $MailTemplate,
239
                        ],
240
                        $request
241
                    );
242
                    $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_MAIL_MAIL_ALL_CHANGE, $event);
243
244
                    $form->get('template')->setData($MailTemplate);
245
                    $form->get('mail_subject')->setData($MailTemplate->getMailSubject());
246
                    $form->get('mail_header')->setData($MailTemplate->getMailHeader());
247
                    $form->get('mail_footer')->setData($MailTemplate->getMailFooter());
248
                }
249
            } else {
250 1
                if ($form->isValid()) {
251 1
                    $data = $form->getData();
252
253 1
                    $ids = explode(',', $ids);
254
255 1
                    foreach ($ids as $value) {
256 1
                        $Order = $this->orderRepository->find($value);
257
258 1
                        $body = $this->createBody($data['mail_header'], $data['mail_footer'], $Order);
259
260
                        // メール送信
261 1
                        $this->mailService->sendAdminOrderMail($Order, $data);
0 ignored issues
show
Documentation introduced by
$Order is of type object|null, but the function expects a object<Eccube\Entity\Order>.

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...
262
263
                        // 送信履歴を保存.
264 1
                        $MailHistory = new MailHistory();
265
                        $MailHistory
266 1
                            ->setMailSubject($data['mail_subject'])
267 1
                            ->setMailBody($body)
268 1
                            ->setSendDate(new \DateTime())
269 1
                            ->setOrder($Order);
270 1
                        $this->entityManager->persist($MailHistory);
271
                    }
272
273 1
                    $this->entityManager->flush($MailHistory);
0 ignored issues
show
Bug introduced by
The variable $MailHistory does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Unused Code introduced by
The call to EntityManagerInterface::flush() has too many arguments starting with $MailHistory.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
274
275 1
                    $event = new EventArgs(
276
                        [
277 1
                            'form' => $form,
278 1
                            'MailHistory' => $MailHistory,
279
                        ],
280 1
                        $request
281
                    );
282 1
                    $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_MAIL_MAIL_ALL_COMPLETE, $event);
283
284 1
                    return $this->redirectToRoute('admin_order_page', ['page_no' => $this->session->get('eccube.admin.order.search.page_no', 1)]);
285
                }
286
            }
287
        } else {
288 1
            $ids = implode(',', (array) $request->get('ids'));
289
        }
290
291
        // 本文確認用
292 1
        $body = '';
293 1
        if ($ids != '') {
294
            $idArray = explode(',', $ids);
295
            $Order = $this->orderRepository->find($idArray[0]);
296
            $body = $this->createBody('', '', $Order);
297
        }
298
299
        return [
300 1
            'form' => $form->createView(),
301 1
            'ids' => $ids,
302 1
            'body' => $body,
303
        ];
304
    }
305
306 3
    private function createBody($header, $footer, $Order)
307
    {
308 3
        return $this->renderView('@admin/Mail/order.twig', [
309 3
            'header' => $header,
310 3
            'footer' => $footer,
311 3
            'Order' => $Order,
312
        ]);
313
    }
314
}
315