Completed
Pull Request — develop (#119)
by Boy
09:26 queued 05:09
created

SecondFactorMailService::findEmailTemplate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 17
rs 9.4285
cc 3
eloc 9
nc 3
nop 3
1
<?php
2
3
/**
4
 * Copyright 2014 SURFnet bv
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 *     http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
19
namespace Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Service;
20
21
use Psr\Log\LoggerInterface;
22
use Surfnet\Stepup\Identity\Value\CommonName;
23
use Surfnet\Stepup\Identity\Value\Email;
24
use Surfnet\Stepup\Identity\Value\Locale;
25
use Surfnet\StepupMiddleware\ApiBundle\Identity\Value\RegistrationAuthorityCredentials;
26
use Surfnet\StepupMiddleware\CommandHandlingBundle\Configuration\Service\EmailTemplateService;
27
use Surfnet\StepupMiddleware\CommandHandlingBundle\Value\Sender;
28
use Swift_Mailer as Mailer;
29
use Swift_Message as Message;
30
use Symfony\Component\Templating\EngineInterface;
31
use Symfony\Component\Translation\TranslatorInterface;
32
33
/**
34
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
35
 */
36
final class SecondFactorMailService
37
{
38
    /**
39
     * @var Mailer
40
     */
41
    private $mailer;
42
43
    /**
44
     * @var Sender
45
     */
46
    private $sender;
47
48
    /**
49
     * @var TranslatorInterface
50
     */
51
    private $translator;
52
53
    /**
54
     * @var EngineInterface
55
     */
56
    private $templateEngine;
57
58
    /**
59
     * @var string
60
     */
61
    private $emailVerificationUrlTemplate;
62
63
    /**
64
     * @var \Surfnet\StepupMiddleware\CommandHandlingBundle\Configuration\Service\EmailTemplateService
65
     */
66
    private $emailTemplateService;
67
68
    /**
69
     * @var string
70
     */
71
    private $fallbackLocale;
72
73
    /**
74
     * @var LoggerInterface
75
     */
76
    private $logger;
77
78
    /**
79
     * @var bool
80
     */
81
    private $warnOnMissingTemplateConfiguration;
82
83
    /**
84
     * @param Mailer $mailer
85
     * @param Sender $sender
86
     * @param TranslatorInterface $translator
87
     * @param EngineInterface $templateEngine
88
     * @param string $emailVerificationUrlTemplate
89
     * @param EmailTemplateService $emailTemplateService
90
     * @param string $fallbackLocale
91
     * @param LoggerInterface $logger
92
     * @param bool $warnOnMissingTemplateConfiguration
93
     */
94
    public function __construct(
95
        Mailer $mailer,
96
        Sender $sender,
97
        TranslatorInterface $translator,
98
        EngineInterface $templateEngine,
99
        $emailVerificationUrlTemplate,
100
        EmailTemplateService $emailTemplateService,
101
        $fallbackLocale,
102
        LoggerInterface $logger,
103
        $warnOnMissingTemplateConfiguration = TRUE
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $warnOnMissingTemplateConfiguration exceeds the maximum configured length of 30.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
104
    ) {
105
        $this->mailer = $mailer;
106
        $this->sender = $sender;
107
        $this->translator = $translator;
108
        $this->templateEngine = $templateEngine;
109
        $this->emailVerificationUrlTemplate = $emailVerificationUrlTemplate;
110
        $this->emailTemplateService = $emailTemplateService;
111
        $this->fallbackLocale = $fallbackLocale;
112
        $this->logger = $logger;
113
        $this->warnOnMissingTemplateConfiguration = $warnOnMissingTemplateConfiguration;
114
    }
115
116
    /**
117
     * @param string $locale
118
     * @param string $commonName
119
     * @param string $email
120
     * @param string $verificationNonce
121
     */
122
    public function sendEmailVerificationEmail(
123
        $locale,
124
        $commonName,
125
        $email,
126
        $verificationNonce
127
    ) {
128
        $subject = $this->translator->trans(
129
            'ss.mail.email_verification_email.subject',
130
            ['%commonName%' => $commonName],
131
            null,
132
            $locale
133
        );
134
135
        $verificationUrl = str_replace(
136
            '{nonce}',
137
            urlencode($verificationNonce),
138
            $this->emailVerificationUrlTemplate
139
        );
140
141
        $emailTemplate = $this->findEmailTemplate('confirm_email', $locale, $this->fallbackLocale);
142
        if (!$emailTemplate) {
143
            return;
144
        }
145
146
        $parameters = [
147
            'templateString'   => $emailTemplate->htmlContent,
148
            'locale'           => $locale,
149
            'commonName'       => $commonName,
150
            'email'            => $email,
151
            'verificationUrl'  => $verificationUrl
152
        ];
153
154
        // Rendering file template instead of string
155
        // (https://github.com/symfony/symfony/issues/10865#issuecomment-42438248)
156
        $body = $this->templateEngine->render(
157
            'SurfnetStepupMiddlewareCommandHandlingBundle:SecondFactorMailService:email.html.twig',
158
            $parameters
159
        );
160
161
        /** @var Message $message */
162
        $message = $this->mailer->createMessage();
163
        $message
164
            ->setFrom($this->sender->getEmail(), $this->sender->getName())
165
            ->addTo($email, $commonName)
166
            ->setSubject($subject)
167
            ->setBody($body, 'text/html', 'utf-8');
168
169
        $this->mailer->send($message);
170
    }
171
172
    /**
173
     * @param string $locale
174
     * @param string $commonName
175
     * @param string $email
176
     * @param string $registrationCode
177
     * @param RegistrationAuthorityCredentials[] $ras
178
     */
179
    public function sendRegistrationEmail(
180
        $locale,
181
        $commonName,
182
        $email,
183
        $registrationCode,
184
        array $ras
185
    ) {
186
        $subject = $this->translator->trans(
187
            'ss.mail.registration_email.subject',
188
            ['%commonName%' => $commonName],
189
            null,
190
            $locale
191
        );
192
193
        $emailTemplate = $this->findEmailTemplate('registration_code', $locale, $this->fallbackLocale);
194
        if (!$emailTemplate) {
195
            return;
196
        }
197
198
        $parameters = [
199
            'templateString'   => $emailTemplate->htmlContent,
200
            'locale'           => $locale,
201
            'commonName'       => $commonName,
202
            'email'            => $email,
203
            'registrationCode' => $registrationCode,
204
            'ras'              => $ras,
205
        ];
206
207
        // Rendering file template instead of string
208
        // (https://github.com/symfony/symfony/issues/10865#issuecomment-42438248)
209
        $body = $this->templateEngine->render(
210
            'SurfnetStepupMiddlewareCommandHandlingBundle:SecondFactorMailService:email.html.twig',
211
            $parameters
212
        );
213
214
        /** @var Message $message */
215
        $message = $this->mailer->createMessage();
216
        $message
217
            ->setFrom($this->sender->getEmail(), $this->sender->getName())
218
            ->addTo($email, $commonName)
219
            ->setSubject($subject)
220
            ->setBody($body, 'text/html', 'utf-8');
221
222
        $this->mailer->send($message);
223
    }
224
225
    /**
226
     * @param Locale     $locale
227
     * @param CommonName $commonName
228
     * @param Email      $email
229
     */
230
    public function sendVettedEmail(
231
        Locale $locale,
232
        CommonName $commonName,
233
        Email $email
234
    ) {
235
        $subject = $this->translator->trans(
236
            'ss.mail.vetted_email.subject',
237
            ['%commonName%' => $commonName->getCommonName(), '%email%' => $email->getEmail()],
238
            null,
239
            $locale->getLocale()
240
        );
241
242
        $emailTemplate = $this->findEmailTemplate('vetted', $locale->getLocale(), $this->fallbackLocale);
243
        if (!$emailTemplate) {
244
            return;
245
        }
246
247
        $parameters = [
248
            'templateString'   => $emailTemplate->htmlContent,
249
            'locale'           => $locale->getLocale(),
250
            'commonName'       => $commonName->getCommonName(),
251
            'email'            => $email->getEmail(),
252
        ];
253
254
        // Rendering file template instead of string
255
        // (https://github.com/symfony/symfony/issues/10865#issuecomment-42438248)
256
        $body = $this->templateEngine->render(
257
            'SurfnetStepupMiddlewareCommandHandlingBundle:SecondFactorMailService:email.html.twig',
258
            $parameters
259
        );
260
261
        /** @var Message $message */
262
        $message = $this->mailer->createMessage();
263
        $message
264
            ->setFrom($this->sender->getEmail(), $this->sender->getName())
265
            ->addTo($email->getEmail(), $commonName->getCommonName())
266
            ->setSubject($subject)
267
            ->setBody($body, 'text/html', 'utf-8');
268
269
        $this->mailer->send($message);
270
    }
271
272
    /**
273
     * @param string $name
274
     * @param string $locale
275
     * @param string $fallbackLocale
276
     * @return null|\Surfnet\StepupMiddleware\CommandHandlingBundle\Configuration\Dto\EmailTemplate
277
     */
278
    private function findEmailTemplate($name, $locale, $fallbackLocale)
279
    {
280
        $emailTemplate = $this->emailTemplateService->findByName($name, $locale, $this->fallbackLocale);
281
282
        if ($emailTemplate) {
283
            return $emailTemplate;
284
        }
285
286
        if ($this->warnOnMissingTemplateConfiguration) {
287
            $this->logger->warning(
288
                'Skipping sending mail because template configuration is missing',
289
                ['name' => $name, 'locale' => $locale, 'fallbackLocale' => $fallbackLocale]
290
            );
291
        }
292
293
        return null;
294
    }
295
}
296