Completed
Push — sf/composer-install-update ( a1e834 )
by Kiyotaka
10:44
created

MailController::index()   C

Complexity

Conditions 12
Paths 16

Size

Total Lines 133

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
nc 16
nop 2
dl 0
loc 133
rs 5.5733
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\Admin\Order;
15
16
use Eccube\Controller\AbstractController;
17
use Eccube\Entity\MailHistory;
18
use Eccube\Entity\Order;
19
use Eccube\Event\EccubeEvents;
20
use Eccube\Event\EventArgs;
21
use Eccube\Form\Type\Admin\MailType;
22
use Eccube\Repository\MailHistoryRepository;
23
use Eccube\Repository\OrderRepository;
24
use Eccube\Service\MailService;
25
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
26
use Symfony\Component\HttpFoundation\Request;
27
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
28
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
29
use Symfony\Component\Routing\Annotation\Route;
30
use Twig\Environment;
31
32
class MailController extends AbstractController
33
{
34
    /**
35
     * @var MailService
36
     */
37
    protected $mailService;
38
39
    /**
40
     * @var MailHistoryRepository
41
     */
42
    protected $mailHistoryRepository;
43
44
    /**
45
     * @var OrderRepository
46
     */
47
    protected $orderRepository;
48
    /**
49
     * @var Environment
50
     */
51
    protected $twig;
52
53
    /**
54
     * MailController constructor.
55
     *
56
     * @param MailService $mailService
57
     * @param MailHistoryRepository $mailHistoryRepository
58
     * @param OrderRepository $orderRepository
59
     * @param twig $twig
60
     */
61
    public function __construct(
62
        MailService $mailService,
63
        MailHistoryRepository $mailHistoryRepository,
64
        OrderRepository $orderRepository,
65
        Environment $twig
66
    ) {
67
        $this->mailService = $mailService;
68
        $this->mailHistoryRepository = $mailHistoryRepository;
69
        $this->orderRepository = $orderRepository;
70
        $this->twig = $twig;
71
    }
72
73
    /**
74
     * @Route("/%eccube_admin_route%/order/{id}/mail", requirements={"id" = "\d+"}, name="admin_order_mail")
75
     * @Template("@admin/Order/mail.twig")
76
     */
77
    public function index(Request $request, Order $Order)
78
    {
79
        $MailHistories = $this->mailHistoryRepository->findBy(['Order' => $Order]);
80
81
        $builder = $this->formFactory->createBuilder(MailType::class);
82
83
        $event = new EventArgs(
84
            [
85
                'builder' => $builder,
86
                'Order' => $Order,
87
                'MailHistories' => $MailHistories,
88
            ],
89
            $request
90
        );
91
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_MAIL_INDEX_INITIALIZE, $event);
92
93
        $form = $builder->getForm();
94
95
        if ('POST' === $request->getMethod()) {
96
            $form->handleRequest($request);
97
98
            $mode = $request->get('mode');
99
100
            // テンプレート変更の場合は. バリデーション前に内容差し替え.
101
            switch ($mode) {
102
                case 'change':
103
                    if ($form->get('template')->isValid()) {
104
                        /** @var $data \Eccube\Entity\MailTemplate */
105
                        $MailTemplate = $form->get('template')->getData();
106
                        $data = $form->getData();
0 ignored issues
show
Unused Code introduced by
$data 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...
107
108
                        $twig = $MailTemplate->getFileName();
109
                        if (!$twig) {
110
                            $twig = 'Mail/order.twig';
111
                        }
112
113
                        // 本文確認用
114
                        $body = $this->createBody($Order, $twig);
115
                        // HTMLテンプレート
116
                        $htmlBody = null;
117
                        $targetTwig = explode('.', $twig);
118
                        $suffix = '.html';
119
                        $htmlTwig = $targetTwig[0].$suffix.'.'.$targetTwig[1];
120
                        if ($this->twig->getLoader()->exists($htmlTwig)) {
121
                            $htmlBody = $this->createBody($Order, $htmlTwig);
122
                        }
123
124
                        $form = $builder->getForm();
125
                        $event = new EventArgs(
126
                            [
127
                                'form' => $form,
128
                                'Order' => $Order,
129
                                'MailTemplate' => $MailTemplate,
130
                            ],
131
                            $request
132
                        );
133
                        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_MAIL_INDEX_CHANGE, $event);
134
                        $form->get('template')->setData($MailTemplate);
135
                        $form->get('mail_subject')->setData($MailTemplate->getMailSubject());
136
                        $form->get('tpl_data')->setData($body);
137
                        if (!is_null($htmlBody)) {
138
                            $form->get('html_tpl_data')->setData($htmlBody);
139
                        }
140
                    }
141
                    break;
142
                case 'confirm':
143
                    if ($form->isValid()) {
144
                        $builder->setAttribute('freeze', true);
145
                        $builder->setAttribute('freeze_display_text', false);
146
                        $form = $builder->getForm();
147
                        $form->handleRequest($request);
148
149
                        return $this->render('@admin/Order/mail_confirm.twig', [
150
                            'form' => $form->createView(),
151
                            'Order' => $Order,
152
                            'MailHistories' => $MailHistories,
153
                        ]);
154
                    }
155
                    break;
156
                case 'complete':
157
                    if ($form->isValid()) {
158
                        $data = $form->getData();
159
                        $data['tpl_data'] = $form->get('tpl_data')->getData();
160
                        $data['html_tpl_data'] = $form->get('html_tpl_data')->getData();
161
162
                        // メール送信
163
                        $message = $this->mailService->sendAdminOrderMail($Order, $data);
164
165
                        // 送信履歴を保存.
166
                        $MailTemplate = $form->get('template')->getData();
167
                        $MailHistory = new MailHistory();
168
                        $MailHistory
169
                            ->setMailSubject($message->getSubject())
170
                            ->setMailBody($message->getBody())
171
                            ->setSendDate(new \DateTime())
172
                            ->setOrder($Order);
173
174
                        // HTML用メールの設定
175
                        if (!is_null($data['html_tpl_data'])) {
176
                            $multipart = $message->getChildren();
177
                            $MailHistory->setMailHtmlBody($multipart[0]->getBody());
178
                        }
179
180
                        $this->entityManager->persist($MailHistory);
181
                        $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...
182
183
                        $event = new EventArgs(
184
                            [
185
                                'form' => $form,
186
                                'Order' => $Order,
187
                                'MailTemplate' => $MailTemplate,
188
                                'MailHistory' => $MailHistory,
189
                            ],
190
                            $request
191
                        );
192
                        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_MAIL_INDEX_COMPLETE, $event);
193
194
                        $this->addSuccess('admin.order.mail_complete.364', 'admin');
195
196
                        return $this->redirectToRoute('admin_order_page', ['page_no' => $this->session->get('eccube.admin.order.search.page_no', 1)]);
197
                    }
198
                    break;
199
                default:
200
                    break;
201
            }
202
        }
203
204
        return [
205
            'form' => $form->createView(),
206
            'Order' => $Order,
207
            'MailHistories' => $MailHistories,
208
        ];
209
    }
210
211
    /**
212
     * @Route("/%eccube_admin_route%/order/mail/view", name="admin_order_mail_view")
213
     * @Template("@admin/Order/mail_view.twig")
214
     */
215
    public function view(Request $request)
216
    {
217
        if (!$request->isXmlHttpRequest()) {
218
            throw new BadRequestHttpException();
219
        }
220
221
        $id = $request->get('id');
222
        $MailHistory = $this->mailHistoryRepository->find($id);
223
224
        if (null === $MailHistory) {
225
            throw new NotFoundHttpException();
226
        }
227
228
        $event = new EventArgs(
229
            [
230
                'MailHistory' => $MailHistory,
231
            ],
232
            $request
233
        );
234
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_MAIL_VIEW_COMPLETE, $event);
235
236
        return [
237
            'mail_subject' => $MailHistory->getMailSubject(),
238
            'body' => $MailHistory->getMailBody(),
239
            'html_body' => $MailHistory->getMailHtmlBody(),
240
        ];
241
    }
242
243
    /**
244
     * @Route("/%eccube_admin_route%/order/mail/mail_all", name="admin_order_mail_all")
245
     * @Template("@admin/Order/mail_all.twig")
246
     */
247
    public function mailAll(Request $request)
248
    {
249
        $builder = $this->formFactory->createBuilder(MailType::class);
250
251
        $event = new EventArgs(
252
            [
253
                'builder' => $builder,
254
            ],
255
            $request
256
        );
257
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_MAIL_MAIL_ALL_INITIALIZE, $event);
258
259
        $form = $builder->getForm();
260
261
        $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...
262
        if ('POST' === $request->getMethod()) {
263
            $form->handleRequest($request);
264
265
            $mode = $request->get('mode');
266
267
            $ids = $request->get('ids');
268
269
            // テンプレート変更の場合は. バリデーション前に内容差し替え.
270
            if ($mode == 'change') {
271
                if ($form->get('template')->isValid()) {
272
                    /** @var $data \Eccube\Entity\MailTemplate */
273
                    $MailTemplate = $form->get('template')->getData();
274
                    $form = $builder->getForm();
275
276
                    $event = new EventArgs(
277
                        [
278
                            'form' => $form,
279
                            'MailTemplate' => $MailTemplate,
280
                        ],
281
                        $request
282
                    );
283
                    $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_MAIL_MAIL_ALL_CHANGE, $event);
284
285
                    $form->get('template')->setData($MailTemplate);
286
                    $form->get('mail_subject')->setData($MailTemplate->getMailSubject());
287
                }
288
            } else {
289
                if ($form->isValid()) {
290
                    $data = $form->getData();
291
292
                    $ids = explode(',', $ids);
293
294
                    foreach ($ids as $value) {
295
                        $MailTemplate = $form->get('template')->getData();
296
                        $Order = $this->orderRepository->find($value);
297
                        // 本文確認用
298
                        $body = $this->createBody($Order, $MailTemplate->getFileName());
299
                        $data['tpl_data'] = $body;
300
                        $data['html_tpl_data'] = null;
301
302
                        // メール送信
303
                        $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...
304
305
                        // 送信履歴を保存.
306
                        $MailHistory = new MailHistory();
307
                        $MailHistory
308
                            ->setMailSubject($data['mail_subject'])
309
                            ->setMailBody($body)
310
                            ->setSendDate(new \DateTime())
311
                            ->setOrder($Order);
0 ignored issues
show
Bug introduced by
It seems like $Order defined by $this->orderRepository->find($value) on line 296 can also be of type object; however, Eccube\Entity\MailHistory::setOrder() does only seem to accept null|object<Eccube\Entity\Order>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
312
                        $this->entityManager->persist($MailHistory);
313
                    }
314
315
                    $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...
316
317
                    $event = new EventArgs(
318
                        [
319
                            'form' => $form,
320
                            'MailHistory' => $MailHistory,
321
                        ],
322
                        $request
323
                    );
324
                    $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_ORDER_MAIL_MAIL_ALL_COMPLETE, $event);
325
326
                    return $this->redirectToRoute('admin_order_page', ['page_no' => $this->session->get('eccube.admin.order.search.page_no', 1)]);
327
                }
328
            }
329
        } else {
330
            $ids = implode(',', (array) $request->get('ids'));
331
        }
332
333
        // 本文確認用
334
        $body = '';
335
        if ($ids != '') {
336
            $idArray = explode(',', $ids);
337
            $Order = $this->orderRepository->find($idArray[0]);
338
            $body = $this->createBody($Order);
339
        }
340
341
        return [
342
            'form' => $form->createView(),
343
            'ids' => $ids,
344
            'body' => $body,
345
        ];
346
    }
347
348
    private function createBody($Order, $twig = 'Mail/order.twig')
349
    {
350
        return $this->renderView($twig, [
351
            'Order' => $Order,
352
        ]);
353
    }
354
}
355