Completed
Pull Request — master (#4187)
by Craig
04:32
created

ConfigController   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 116
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 63
dl 0
loc 116
rs 10
c 0
b 0
f 0
wmc 15

3 Methods

Rating   Name   Duplication   Size   Complexity  
B testAction() 0 38 8
A getDataValues() 0 12 1
B configAction() 0 43 6
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Zikula package.
7
 *
8
 * Copyright Zikula Foundation - 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 Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
17
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
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\Helper\LocalDotEnvHelper;
26
use Zikula\Bundle\CoreBundle\HttpKernel\ZikulaHttpKernelInterface;
27
use Zikula\ExtensionsModule\Api\ApiInterface\VariableApiInterface;
28
use Zikula\MailerModule\Form\Type\ConfigType;
29
use Zikula\MailerModule\Form\Type\TestType;
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
        ZikulaHttpKernelInterface $kernel
49
    ): array {
50
        $form = $this->createForm(
51
            ConfigType::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
                $this->setVars($formData);
59
                $transportStrings = [
60
                    'smtp' => 'smtp://$MAILER_ID:[email protected]',
61
                    'sendmail' => 'sendmail+smtp://default',
62
                    'amazon' => 'ses://$MAILER_ID:$MAILER_KEY@default',
63
                    'gmail' => 'gmail://$MAILER_ID:$MAILER_KEY@default',
64
                    'mailchimp' => 'mandrill://$MAILER_ID:$MAILER_KEY@default',
65
                    'mailgun' => 'mailgun://$MAILER_ID:$MAILER_KEY@default',
66
                    'postmark' => 'postmark://$MAILER_ID:$MAILER_KEY@default',
67
                    'sendgrid' => 'sendgrid://apikey:$MAILER_KEY@default', // unclear if 'apikey' is supposed to be literal, or replaced
68
                    'test' => 'null://null',
69
                ];
70
                try {
71
                    $vars = [
72
                        'MAILER_ID' => $formData['mailer_id'],
73
                        'MAILER_KEY' => $formData['mailer_key'],
74
                        'MAILER_DSN' => '!' . $transportStrings[$formData['transport']]
75
                    ];
76
                    $helper = new LocalDotEnvHelper($kernel->getProjectDir());
77
                    $helper->writeLocalEnvVars($vars);
78
                    $this->addFlash('status', 'Done! Configuration updated.');
79
                } catch (IOExceptionInterface $exception) {
80
                    $this->addFlash('error', $this->trans('Cannot write to %file%.' . ' ' . $exception->getMessage(), ['%file%' => $kernel->getProjectDir() . '\.env.local']));
81
                }
82
            } elseif ($form->get('cancel')->isClicked()) {
83
                $this->addFlash('status', 'Operation cancelled.');
84
            }
85
        }
86
87
        return [
88
            'form' => $form->createView()
89
        ];
90
    }
91
92
    /**
93
     * @Route("/test")
94
     * @Theme("admin")
95
     * @Template("@ZikulaMailerModule/Config/test.html.twig")
96
     *
97
     * This function displays a form to send a test mail.
98
     */
99
    public function testAction(
100
        Request $request,
101
        VariableApiInterface $variableApi,
102
        MailerInterface $mailer
103
    ): array {
104
105
        $form = $this->createForm(TestType::class, $this->getDataValues($variableApi));
106
        $form->handleRequest($request);
107
        if ($form->isSubmitted() && $form->isValid()) {
108
            if ($form->get('test')->isClicked()) {
109
                $formData = $form->getData();
110
                $html = in_array($formData['messageType'], ['html', 'multipart']) ? true : false;
111
                try {
112
                    $siteName = $variableApi->getSystemVar('sitename', $variableApi->getSystemVar('sitename_en'));
113
                    $adminMail = $variableApi->getSystemVar('adminmail');
114
115
                    $email = (new Email())
116
                        ->from(new Address($adminMail, $siteName))
117
                        ->to(new Address($formData['toAddress'], $formData['toName']))
118
                        ->subject($formData['subject'])
119
                        ->text($formData['bodyText'])
120
                    ;
121
                    if ($html) {
122
                        $email->html($formData['bodyHtml']);
123
                    }
124
                    $mailer->send($email);
125
                    $this->addFlash('status', 'Done! Message sent.');
126
                } catch (TransportExceptionInterface $exception) {
127
                    $this->addFlash('error', $exception->getMessage());
128
                }
129
            }
130
            if ($form->get('cancel')->isClicked()) {
131
                $this->addFlash('status', 'Operation cancelled.');
132
            }
133
        }
134
135
        return [
136
            'form' => $form->createView(),
137
        ];
138
    }
139
140
    /**
141
     * Returns required data from module variables and mailer configuration.
142
     */
143
    private function getDataValues(
144
        VariableApiInterface $variableApi
145
    ): array {
146
        $modVars = $variableApi->getAll('ZikulaMailerModule');
147
148
        $modVars['sitename'] = $variableApi->getSystemVar('sitename', $variableApi->getSystemVar('sitename_en'));
149
        $modVars['adminmail'] = $variableApi->getSystemVar('adminmail');
150
151
        $modVars['fromName'] = $modVars['sitename'];
152
        $modVars['fromAddress'] = $modVars['adminmail'];
153
154
        return $modVars;
155
    }
156
}
157