Completed
Pull Request — master (#4276)
by Craig
07:54 queued 02:40
created

ConfigController   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 121
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 58
c 2
b 0
f 0
dl 0
loc 121
rs 10
wmc 20

4 Methods

Rating   Name   Duplication   Size   Complexity  
A transportConfigChanged() 0 10 3
B testAction() 0 44 9
A getDataValues() 0 13 1
B configAction() 0 29 7
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Zikula package.
7
 *
8
 * Copyright Zikula - https://ziku.la/
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 Zikula\MailerModule\Controller;
15
16
use Psr\Log\LoggerInterface;
17
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
18
use Symfony\Component\HttpFoundation\Request;
19
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
20
use Symfony\Component\Mailer\MailerInterface;
21
use Symfony\Component\Mime\Address;
22
use Symfony\Component\Mime\Email;
23
use Symfony\Component\Routing\Annotation\Route;
24
use Zikula\Bundle\CoreBundle\Controller\AbstractController;
25
use Zikula\Bundle\CoreBundle\Site\SiteDefinitionInterface;
26
use Zikula\ExtensionsModule\Api\ApiInterface\VariableApiInterface;
27
use Zikula\MailerModule\Form\Type\MailTransportConfigType;
28
use Zikula\MailerModule\Form\Type\TestType;
29
use Zikula\MailerModule\Helper\MailTransportHelper;
30
use Zikula\PermissionsModule\Annotation\PermissionCheck;
31
use Zikula\ThemeModule\Engine\Annotation\Theme;
32
33
/**
34
 * Class ConfigController
35
 *
36
 * @Route("/config")
37
 * @PermissionCheck("admin")
38
 */
39
class ConfigController extends AbstractController
40
{
41
    /**
42
     * @Route("/config")
43
     * @Theme("admin")
44
     * @Template("@ZikulaMailerModule/Config/config.html.twig")
45
     */
46
    public function configAction(
47
        Request $request,
48
        MailTransportHelper $mailTransportHelper
49
    ): array {
50
        $form = $this->createForm(
51
            MailTransportConfigType::class,
52
            $this->getVars()
53
        );
54
        $form->handleRequest($request);
55
        if ($form->isSubmitted() && $form->isValid()) {
56
            if ($form->get('save')->isClicked()) {
0 ignored issues
show
Bug introduced by
The method isClicked() does not exist on Symfony\Component\Form\FormInterface. It seems like you code against a sub-type of Symfony\Component\Form\FormInterface such as Symfony\Component\Form\SubmitButton. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

56
            if ($form->get('save')->/** @scrutinizer ignore-call */ isClicked()) {
Loading history...
57
                $formData = $form->getData();
58
                if ($this->transportConfigChanged($formData)) {
59
                    if (true === $mailTransportHelper->handleFormData($formData)) {
60
                        $this->addFlash('status', 'Done! Mailer Transport Config updated.');
61
                    } else {
62
                        $this->addFlash('error', $this->trans('Cannot write to %file%.', ['%file%' => '\.env.local']));
63
                    }
64
                    unset($formData['mailer_key'], $formData['save'], $formData['cancel']);
65
                    $this->setVars($formData);
66
                }
67
                $this->setVar('enableLogging', $formData['enableLogging']);
68
            } elseif ($form->get('cancel')->isClicked()) {
69
                $this->addFlash('status', 'Operation cancelled.');
70
            }
71
        }
72
73
        return [
74
            'form' => $form->createView()
75
        ];
76
    }
77
78
    private function transportConfigChanged(array $formData): bool
79
    {
80
        $transportVars = ['transport', 'mailer_id', 'host', 'port', 'customParameters'];
81
        foreach ($transportVars as $transportVar) {
82
            if ($formData[$transportVar] !== $this->getVar($transportVar)) {
83
                return true;
84
            }
85
        }
86
87
        return false;
88
    }
89
90
    /**
91
     * @Route("/test")
92
     * @Theme("admin")
93
     * @Template("@ZikulaMailerModule/Config/test.html.twig")
94
     *
95
     * This function displays a form to send a test mail.
96
     */
97
    public function testAction(
98
        Request $request,
99
        VariableApiInterface $variableApi,
100
        MailerInterface $mailer,
101
        LoggerInterface $mailLogger, // $mailLogger var name auto-injects the mail channel handler
102
        SiteDefinitionInterface $site
103
    ): array {
104
        $form = $this->createForm(TestType::class, $this->getDataValues($variableApi, $site));
105
        $form->handleRequest($request);
106
        if ($form->isSubmitted() && $form->isValid()) {
107
            if ($form->get('test')->isClicked()) {
108
                $formData = $form->getData();
109
                $html = in_array($formData['messageType'], ['html', 'multipart']) ? true : false;
110
                try {
111
                    $email = (new Email())
112
                        ->from(new Address($formData['adminmail'], $formData['sitename']))
113
                        ->to(new Address($formData['toAddress'], $formData['toName']))
114
                        ->subject($formData['subject'])
115
                        ->text($formData['bodyText'])
116
                    ;
117
                    if ($html) {
118
                        $email->html($formData['bodyHtml']);
119
                    }
120
                    $mailer->send($email);
121
                    if ($variableApi->get('ZikulaMailerModule', 'enableLogging', false)) {
122
                        $mailLogger->info(sprintf('Email sent to %s', $formData['toAddress']), [
123
                            'in' => __METHOD__,
124
                        ]);
125
                    }
126
                    $this->addFlash('status', 'Done! Message sent.');
127
                } catch (TransportExceptionInterface $exception) {
128
                    $mailLogger->error($exception->getMessage(), [
129
                        'in' => __METHOD__,
130
                    ]);
131
                    $this->addFlash('error', $exception->getCode() . ': ' . $exception->getMessage());
132
                }
133
            }
134
            if ($form->get('cancel')->isClicked()) {
135
                $this->addFlash('status', 'Operation cancelled.');
136
            }
137
        }
138
139
        return [
140
            'form' => $form->createView(),
141
        ];
142
    }
143
144
    /**
145
     * Returns required data from module variables and mailer configuration.
146
     */
147
    private function getDataValues(
148
        VariableApiInterface $variableApi,
149
        SiteDefinitionInterface $site
150
    ): array {
151
        $modVars = $variableApi->getAll('ZikulaMailerModule');
152
153
        $modVars['sitename'] = $site->getName();
154
        $modVars['adminmail'] = $variableApi->getSystemVar('adminmail');
155
156
        $modVars['fromName'] = $modVars['sitename'];
157
        $modVars['fromAddress'] = $modVars['adminmail'];
158
159
        return $modVars;
160
    }
161
}
162