ToolController   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 98
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 50
dl 0
loc 98
rs 10
c 0
b 0
f 0
wmc 13

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getDataValues() 0 10 1
A __construct() 0 5 1
A phpinfo() 0 14 1
B test() 0 49 10
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\ThemeBundle\Controller;
15
16
use Psr\Log\LoggerInterface;
17
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
18
use Symfony\Component\DependencyInjection\Attribute\Autowire;
19
use Symfony\Component\HttpFoundation\Request;
20
use Symfony\Component\HttpFoundation\Response;
21
use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException;
22
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
23
use Symfony\Component\Mailer\MailerInterface;
24
use Symfony\Component\Mime\Address;
25
use Symfony\Component\Mime\Email;
26
use Symfony\Component\RateLimiter\RateLimiterFactory;
27
use Symfony\Component\Routing\Attribute\Route;
28
use Symfony\Component\Security\Http\Attribute\IsGranted;
29
use Zikula\CoreBundle\Site\SiteDefinitionInterface;
30
use Zikula\ThemeBundle\Form\Type\MailTestType;
31
32
#[Route('/admin/tool')]
33
#[IsGranted('ROLE_ADMIN')]
34
class ToolController extends AbstractController
35
{
36
    public function __construct(
37
        private readonly SiteDefinitionInterface $site,
38
        #[Autowire(param: 'enable_mail_logging')]
39
        private readonly bool $mailLoggingEnabled
40
    ) {
41
    }
42
43
    /**
44
     * This function displays a form to send a test mail.
45
     */
46
    #[Route('/testmail', name: 'zikulathemebundle_tool_testmail')]
47
    public function test(
48
        Request $request,
49
        MailerInterface $mailer,
50
        RateLimiterFactory $testMailsLimiter,
51
        LoggerInterface $mailLogger // $mailLogger var name auto-injects the mail channel handler
52
    ): Response {
53
        $form = $this->createForm(MailTestType::class, $this->getDataValues());
54
        $form->handleRequest($request);
55
        if ($form->isSubmitted() && $form->isValid()) {
56
            if ($form->get('test')->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('test')->/** @scrutinizer ignore-call */ isClicked()) {
Loading history...
57
                $limiter = $testMailsLimiter->create($request->getClientIp());
58
                if (false === $limiter->consume(1)->isAccepted()) {
59
                    throw new TooManyRequestsHttpException();
60
                }
61
62
                $formData = $form->getData();
63
                $html = in_array($formData['messageType'], ['html', 'multipart']) ? true : false;
64
                try {
65
                    $email = (new Email())
66
                        ->from(new Address($formData['adminmail'], $formData['sitename']))
67
                        ->to(new Address($formData['toAddress'], $formData['toName']))
68
                        ->subject($formData['subject'])
69
                        ->text($formData['bodyText'])
70
                    ;
71
                    if ($html) {
72
                        $email->html($formData['bodyHtml']);
73
                    }
74
                    $mailer->send($email);
75
                    if ($this->mailLoggingEnabled) {
76
                        $mailLogger->info(sprintf('Email sent to %s', $formData['toAddress']), [
77
                            'in' => __METHOD__,
78
                        ]);
79
                    }
80
                    $this->addFlash('status', 'Done! Message sent.');
81
                } catch (TransportExceptionInterface $exception) {
82
                    $mailLogger->error($exception->getMessage(), [
83
                        'in' => __METHOD__,
84
                    ]);
85
                    $this->addFlash('error', $exception->getCode() . ': ' . $exception->getMessage());
86
                }
87
            }
88
            if ($form->get('cancel')->isClicked()) {
89
                $this->addFlash('status', 'Operation cancelled.');
90
            }
91
        }
92
93
        return $this->render('@ZikulaTheme/Tool/testmail.html.twig', [
94
            'form' => $form,
95
        ]);
96
    }
97
98
    /**
99
     * Returns required data from configuration.
100
     */
101
    private function getDataValues(): array
102
    {
103
        $parameters = [];
104
        $parameters['sitename'] = $this->site->getName();
105
        $parameters['adminmail'] = $this->site->getAdminMail();
106
107
        $parameters['fromName'] = $parameters['sitename'];
108
        $parameters['fromAddress'] = $parameters['adminmail'];
109
110
        return $parameters;
111
    }
112
113
    /**
114
     * Displays the content of {@see phpinfo()}.
115
     */
116
    #[Route('/phpinfo', name: 'zikulathemebundle_tool_phpinfo', methods: ['GET'])]
117
    public function phpinfo(): Response
118
    {
119
        ob_start();
120
        phpinfo();
121
        $phpinfo = ob_get_clean();
122
        $phpinfo = str_replace(
123
            'bundle_Zend Optimizer',
124
            'bundle_Zend_Optimizer',
125
            preg_replace('%^.*<body>(.*)</body>.*$%ms', '$1', $phpinfo)
126
        );
127
128
        return $this->render('@ZikulaTheme/Tool/phpinfo.html.twig', [
129
            'phpinfo' => $phpinfo,
130
        ]);
131
    }
132
}
133