Completed
Pull Request — develop (#119)
by Boy
08:59 queued 04:21
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
final class SecondFactorMailService
34
{
35
    /**
36
     * @var Mailer
37
     */
38
    private $mailer;
39
40
    /**
41
     * @var Sender
42
     */
43
    private $sender;
44
45
    /**
46
     * @var TranslatorInterface
47
     */
48
    private $translator;
49
50
    /**
51
     * @var EngineInterface
52
     */
53
    private $templateEngine;
54
55
    /**
56
     * @var string
57
     */
58
    private $emailVerificationUrlTemplate;
59
60
    /**
61
     * @var \Surfnet\StepupMiddleware\CommandHandlingBundle\Configuration\Service\EmailTemplateService
62
     */
63
    private $emailTemplateService;
64
65
    /**
66
     * @var string
67
     */
68
    private $fallbackLocale;
69
70
    /**
71
     * @var LoggerInterface
72
     */
73
    private $logger;
74
75
    /**
76
     * @var bool
77
     */
78
    private $warnOnMissingTemplateConfiguration;
79
80
    /**
81
     * @param Mailer $mailer
82
     * @param Sender $sender
83
     * @param TranslatorInterface $translator
84
     * @param EngineInterface $templateEngine
85
     * @param string $emailVerificationUrlTemplate
86
     * @param EmailTemplateService $emailTemplateService
87
     * @param string $fallbackLocale
88
     * @param LoggerInterface $logger
89
     * @param bool $warnOnMissingTemplateConfiguration
90
     */
91
    public function __construct(
92
        Mailer $mailer,
93
        Sender $sender,
94
        TranslatorInterface $translator,
95
        EngineInterface $templateEngine,
96
        $emailVerificationUrlTemplate,
97
        EmailTemplateService $emailTemplateService,
98
        $fallbackLocale,
99
        LoggerInterface $logger,
100
        $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...
101
    ) {
102
        $this->mailer = $mailer;
103
        $this->sender = $sender;
104
        $this->translator = $translator;
105
        $this->templateEngine = $templateEngine;
106
        $this->emailVerificationUrlTemplate = $emailVerificationUrlTemplate;
107
        $this->emailTemplateService = $emailTemplateService;
108
        $this->fallbackLocale = $fallbackLocale;
109
        $this->logger = $logger;
110
        $this->warnOnMissingTemplateConfiguration = $warnOnMissingTemplateConfiguration;
111
    }
112
113
    /**
114
     * @param string $locale
115
     * @param string $commonName
116
     * @param string $email
117
     * @param string $verificationNonce
118
     */
119
    public function sendEmailVerificationEmail(
120
        $locale,
121
        $commonName,
122
        $email,
123
        $verificationNonce
124
    ) {
125
        $subject = $this->translator->trans(
126
            'ss.mail.email_verification_email.subject',
127
            ['%commonName%' => $commonName],
128
            null,
129
            $locale
130
        );
131
132
        $verificationUrl = str_replace(
133
            '{nonce}',
134
            urlencode($verificationNonce),
135
            $this->emailVerificationUrlTemplate
136
        );
137
138
        $emailTemplate = $this->findEmailTemplate('confirm_email', $locale, $this->fallbackLocale);
139
        if (!$emailTemplate) {
140
            return;
141
        }
142
143
        $parameters = [
144
            'templateString'   => $emailTemplate->htmlContent,
145
            'locale'           => $locale,
146
            'commonName'       => $commonName,
147
            'email'            => $email,
148
            'verificationUrl'  => $verificationUrl
149
        ];
150
151
        // Rendering file template instead of string
152
        // (https://github.com/symfony/symfony/issues/10865#issuecomment-42438248)
153
        $body = $this->templateEngine->render(
154
            'SurfnetStepupMiddlewareCommandHandlingBundle:SecondFactorMailService:email.html.twig',
155
            $parameters
156
        );
157
158
        /** @var Message $message */
159
        $message = $this->mailer->createMessage();
160
        $message
161
            ->setFrom($this->sender->getEmail(), $this->sender->getName())
162
            ->addTo($email, $commonName)
163
            ->setSubject($subject)
164
            ->setBody($body, 'text/html', 'utf-8');
165
166
        $this->mailer->send($message);
167
    }
168
169
    /**
170
     * @param string $locale
171
     * @param string $commonName
172
     * @param string $email
173
     * @param string $registrationCode
174
     * @param RegistrationAuthorityCredentials[] $ras
175
     */
176
    public function sendRegistrationEmail(
177
        $locale,
178
        $commonName,
179
        $email,
180
        $registrationCode,
181
        array $ras
182
    ) {
183
        $subject = $this->translator->trans(
184
            'ss.mail.registration_email.subject',
185
            ['%commonName%' => $commonName],
186
            null,
187
            $locale
188
        );
189
190
        $emailTemplate = $this->findEmailTemplate('registration_code', $locale, $this->fallbackLocale);
191
        if (!$emailTemplate) {
192
            return;
193
        }
194
195
        $parameters = [
196
            'templateString'   => $emailTemplate->htmlContent,
197
            'locale'           => $locale,
198
            'commonName'       => $commonName,
199
            'email'            => $email,
200
            'registrationCode' => $registrationCode,
201
            'ras'              => $ras,
202
        ];
203
204
        // Rendering file template instead of string
205
        // (https://github.com/symfony/symfony/issues/10865#issuecomment-42438248)
206
        $body = $this->templateEngine->render(
207
            'SurfnetStepupMiddlewareCommandHandlingBundle:SecondFactorMailService:email.html.twig',
208
            $parameters
209
        );
210
211
        /** @var Message $message */
212
        $message = $this->mailer->createMessage();
213
        $message
214
            ->setFrom($this->sender->getEmail(), $this->sender->getName())
215
            ->addTo($email, $commonName)
216
            ->setSubject($subject)
217
            ->setBody($body, 'text/html', 'utf-8');
218
219
        $this->mailer->send($message);
220
    }
221
222
    /**
223
     * @param Locale     $locale
224
     * @param CommonName $commonName
225
     * @param Email      $email
226
     */
227
    public function sendVettedEmail(
228
        Locale $locale,
229
        CommonName $commonName,
230
        Email $email
231
    ) {
232
        $subject = $this->translator->trans(
233
            'ss.mail.vetted_email.subject',
234
            ['%commonName%' => $commonName->getCommonName(), '%email%' => $email->getEmail()],
235
            null,
236
            $locale->getLocale()
237
        );
238
239
        $emailTemplate = $this->findEmailTemplate('vetted', $locale->getLocale(), $this->fallbackLocale);
240
        if (!$emailTemplate) {
241
            return;
242
        }
243
244
        $parameters = [
245
            'templateString'   => $emailTemplate->htmlContent,
246
            'locale'           => $locale->getLocale(),
247
            'commonName'       => $commonName->getCommonName(),
248
            'email'            => $email->getEmail(),
249
        ];
250
251
        // Rendering file template instead of string
252
        // (https://github.com/symfony/symfony/issues/10865#issuecomment-42438248)
253
        $body = $this->templateEngine->render(
254
            'SurfnetStepupMiddlewareCommandHandlingBundle:SecondFactorMailService:email.html.twig',
255
            $parameters
256
        );
257
258
        /** @var Message $message */
259
        $message = $this->mailer->createMessage();
260
        $message
261
            ->setFrom($this->sender->getEmail(), $this->sender->getName())
262
            ->addTo($email->getEmail(), $commonName->getCommonName())
263
            ->setSubject($subject)
264
            ->setBody($body, 'text/html', 'utf-8');
265
266
        $this->mailer->send($message);
267
    }
268
269
    /**
270
     * @param string $name
271
     * @param string $locale
272
     * @param string $fallbackLocale
273
     * @return null|\Surfnet\StepupMiddleware\CommandHandlingBundle\Configuration\Dto\EmailTemplate
274
     */
275
    private function findEmailTemplate($name, $locale, $fallbackLocale)
276
    {
277
        $emailTemplate = $this->emailTemplateService->findByName($name, $locale, $this->fallbackLocale);
278
279
        if ($emailTemplate) {
280
            return $emailTemplate;
281
        }
282
283
        if ($this->warnOnMissingTemplateConfiguration) {
284
            $this->logger->warning(
285
                'Skipping sending mail because template configuration is missing',
286
                ['name' => $name, 'locale' => $locale, 'fallbackLocale' => $fallbackLocale]
287
            );
288
        }
289
290
        return null;
291
    }
292
}
293