]> Raphaël G. Git Repositories - userbundle/blob - Controller/UserController.php
Add short syntax note
[userbundle] / Controller / UserController.php
1 <?php declare(strict_types=1);
2
3 /*
4 * This file is part of the Rapsys UserBundle package.
5 *
6 * (c) Raphaël Gertz <symfony@rapsys.eu>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Rapsys\UserBundle\Controller;
13
14 use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
15
16 use Rapsys\UserBundle\RapsysUserBundle;
17
18 use Symfony\Bridge\Twig\Mime\TemplatedEmail;
19 use Symfony\Component\Form\FormError;
20 use Symfony\Component\HttpFoundation\Request;
21 use Symfony\Component\HttpFoundation\Response;
22 use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
23 use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
24 use Symfony\Component\Mime\Address;
25 use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
26 use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
27
28 /**
29 * {@inheritdoc}
30 */
31 class UserController extends AbstractController {
32 /**
33 * User index
34 *
35 * @param Request $request The request
36 * @return Response The response
37 */
38 public function index(Request $request): Response {
39 //Without admin
40 if (!$this->checker->isGranted('ROLE_'.strtoupper($this->config['default']['admin']))) {
41 //Throw 403
42 throw $this->createAccessDeniedException($this->translator->trans('Unable to list users', [], $this->alias));
43 }
44
45 //Get count
46 $this->context['count'] = $this->doctrine->getRepository($this->config['class']['user'])->findCountAsInt();
47
48 //With not enough users
49 if ($this->context['count'] - $this->page * $this->limit < 0) {
50 //Throw 404
51 throw $this->createNotFoundException($this->translator->trans('Unable to find users', [], $this->alias));
52 }
53
54 //Get users by groups
55 $this->context['groups'] = $this->doctrine->getRepository($this->config['class']['user'])->findIndexByGroupId($this->page, $this->limit);
56
57 //Render view
58 return $this->render(
59 //Template
60 $this->config['index']['view']['name'],
61 //Context
62 $this->context+$this->config['index']['view']['context']
63 );
64 }
65
66 /**
67 * Confirm account from mail link
68 *
69 * @param Request $request The request
70 * @param string $hash The hashed password
71 * @param string $mail The shorted mail address
72 * @return Response The response
73 */
74 public function confirm(Request $request, string $hash, string $mail): Response {
75 //With invalid hash
76 if ($hash != $this->slugger->hash($mail)) {
77 //Throw bad request
78 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash], $this->alias));
79 }
80
81 //Get mail
82 $mail = $this->slugger->unshort($smail = $mail);
83
84 //Without valid mail
85 if (filter_var($mail, FILTER_VALIDATE_EMAIL) === false) {
86 //Throw bad request
87 //XXX: prevent slugger reverse engineering by not displaying decoded mail
88 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'mail', '%value%' => $smail], $this->alias));
89 }
90
91 //Without existing registrant
92 if (!($user = $this->doctrine->getRepository($this->config['class']['user'])->findOneByMail($mail))) {
93 //Add error message mail already exists
94 //XXX: prevent slugger reverse engineering by not displaying decoded mail
95 $this->addFlash('error', $this->translator->trans('The account do not exists', [], $this->alias));
96
97 //Redirect to register view
98 return $this->redirectToRoute($this->config['route']['register']['name'], $this->config['route']['register']['context']);
99 }
100
101 //Set active
102 $user->setActive(true);
103
104 //Persist user
105 $this->manager->persist($user);
106
107 //Send to database
108 $this->manager->flush();
109
110 //Add error message mail already exists
111 $this->addFlash('notice', $this->translator->trans('Your account has been activated', [], $this->alias));
112
113 //Redirect to user view
114 return $this->redirectToRoute($this->config['route']['edit']['name'], ['mail' => $smail, 'hash' => $this->slugger->hash($smail)]+$this->config['route']['edit']['context']);
115 }
116
117 /**
118 * Edit account by shorted mail
119 *
120 * @param Request $request The request
121 * @param string $hash The hashed password
122 * @param string $mail The shorted mail address
123 * @return Response The response
124 */
125 public function edit(Request $request, string $hash, string $mail): Response {
126 //With invalid hash
127 if ($hash != $this->slugger->hash($mail)) {
128 //Throw bad request
129 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash], $this->alias));
130 }
131
132 //Get mail
133 $mail = $this->slugger->unshort($smail = $mail);
134
135 //With existing subscriber
136 if (empty($user = $this->doctrine->getRepository($this->config['class']['user'])->findOneByMail($mail))) {
137 //Throw not found
138 //XXX: prevent slugger reverse engineering by not displaying decoded mail
139 throw $this->createNotFoundException($this->translator->trans('Unable to find account', [], $this->alias));
140 }
141
142 //Prevent access when not admin, user is not guest and not currently logged user
143 if (!$this->checker->isGranted('ROLE_'.strtoupper($this->config['default']['admin'])) && $user != $this->security->getUser() || !$this->checker->isGranted('IS_AUTHENTICATED_FULLY')) {
144 //Throw access denied
145 //XXX: prevent slugger reverse engineering by not displaying decoded mail
146 throw $this->createAccessDeniedException($this->translator->trans('Unable to access user', [], $this->alias));
147 }
148
149 //Create the EditType form and give the proper parameters
150 $edit = $this->factory->create($this->config['edit']['view']['edit'], $user, [
151 //Set action to edit route name and context
152 'action' => $this->generateUrl($this->config['route']['edit']['name'], ['mail' => $smail, 'hash' => $this->slugger->hash($smail)]+$this->config['route']['edit']['context']),
153 //Set civility class
154 'civility_class' => $this->config['class']['civility'],
155 //Set civility default
156 'civility_default' => $this->doctrine->getRepository($this->config['class']['civility'])->findOneByTitle($this->config['default']['civility']),
157 //Disable mail
158 'mail' => $this->checker->isGranted('ROLE_ADMIN'),
159 //Disable password
160 'password' => false,
161 //Set method
162 'method' => 'POST',
163 //Set domain
164 'translation_domain' => $this->alias
165 ]+($this->checker->isGranted('ROLE_'.strtoupper($this->config['default']['admin']))?$this->config['edit']['admin']:$this->config['edit']['field']));
166
167 //With admin role
168 if ($this->checker->isGranted('ROLE_'.strtoupper($this->config['default']['admin']))) {
169 //Create the EditType form and give the proper parameters
170 $reset = $this->factory->create($this->config['edit']['view']['reset'], $user, [
171 //Set action to edit route name and context
172 'action' => $this->generateUrl($this->config['route']['edit']['name'], ['mail' => $smail, 'hash' => $this->slugger->hash($smail)]+$this->config['route']['edit']['context']),
173 //Set method
174 'method' => 'POST',
175 //Set domain
176 'translation_domain' => $this->alias
177 ]);
178
179 //With post method
180 if ($request->isMethod('POST')) {
181 //Refill the fields in case the form is not valid.
182 $reset->handleRequest($request);
183
184 //With reset submitted and valid
185 if ($reset->isSubmitted() && $reset->isValid()) {
186 //Set data
187 $data = $reset->getData();
188
189 //Set password
190 $data->setPassword($this->hasher->hashPassword($data, $data->getPassword()));
191
192 //Queue snippet save
193 $this->manager->persist($data);
194
195 //Flush to get the ids
196 $this->manager->flush();
197
198 //Add notice
199 $this->addFlash('notice', $this->translator->trans('Account password updated', [], $this->alias));
200
201 //Redirect to cleanup the form
202 return $this->redirectToRoute($this->config['route']['edit']['name'], ['mail' => $smail = $this->slugger->short($mail), 'hash' => $this->slugger->hash($smail)]+$this->config['route']['edit']['context']);
203 }
204 }
205
206 //Add reset view
207 $this->config['edit']['view']['context']['reset'] = $reset->createView();
208 }
209
210 //With post method
211 if ($request->isMethod('POST')) {
212 //Refill the fields in case the form is not valid.
213 $edit->handleRequest($request);
214
215 //With edit submitted and valid
216 if ($edit->isSubmitted() && $edit->isValid()) {
217 //Set data
218 $data = $edit->getData();
219
220 //Queue snippet save
221 $this->manager->persist($data);
222
223 //Try saving in database
224 try {
225 //Flush to get the ids
226 $this->manager->flush();
227
228 //Add notice
229 $this->addFlash('notice', $this->translator->trans('Account updated', [], $this->alias));
230
231 //Redirect to cleanup the form
232 return $this->redirectToRoute($this->config['route']['edit']['name'], ['mail' => $smail = $this->slugger->short($mail), 'hash' => $this->slugger->hash($smail)]+$this->config['route']['edit']['context']);
233 //Catch double slug or mail
234 } catch (UniqueConstraintViolationException $e) {
235 //Add error message mail already exists
236 $this->addFlash('error', $this->translator->trans('The account already exists', [], $this->alias));
237 }
238 }
239 //Without admin role
240 //XXX: prefer a reset on login to force user unspam action
241 } elseif (!$this->checker->isGranted('ROLE_'.strtoupper($this->config['default']['admin']))) {
242 //Add notice
243 $this->addFlash('notice', $this->translator->trans('To change your password login with your mail and any password then follow the procedure', [], $this->alias));
244 }
245
246 //Render view
247 return $this->render(
248 //Template
249 $this->config['edit']['view']['name'],
250 //Context
251 ['register' => $edit->createView()]+$this->config['edit']['view']['context']
252 );
253 }
254
255 /**
256 * Login
257 *
258 * @param Request $request The request
259 * @param AuthenticationUtils $authenticationUtils The authentication utils
260 * @param ?string $hash The hashed password
261 * @param ?string $mail The shorted mail address
262 * @return Response The response
263 */
264 public function login(Request $request, AuthenticationUtils $authenticationUtils, ?string $hash, ?string $mail): Response {
265 //Create the LoginType form and give the proper parameters
266 $login = $this->factory->create($this->config['login']['view']['form'], null, [
267 //Set action to login route name and context
268 'action' => $this->generateUrl($this->config['route']['login']['name'], $this->config['route']['login']['context']),
269 //Set method
270 'method' => 'POST',
271 //Set domain
272 'translation_domain' => $this->alias
273 ]);
274
275 //Init context
276 $context = [];
277
278 //With mail
279 if (!empty($mail) && !empty($hash)) {
280 //With invalid hash
281 if ($hash != $this->slugger->hash($mail)) {
282 //Throw bad request
283 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash], $this->alias));
284 }
285
286 //Get mail
287 $mail = $this->slugger->unshort($smail = $mail);
288
289 //Without valid mail
290 if (filter_var($mail, FILTER_VALIDATE_EMAIL) === false) {
291 //Throw bad request
292 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'mail', '%value%' => $smail], $this->alias));
293 }
294
295 //Prefilled mail
296 $login->get('mail')->setData($mail);
297 //Last username entered by the user
298 } elseif ($lastUsername = $authenticationUtils->getLastUsername()) {
299 $login->get('mail')->setData($lastUsername);
300 }
301
302 //Get the login error if there is one
303 if ($error = $authenticationUtils->getLastAuthenticationError()) {
304 //Get translated error
305 $error = $this->translator->trans($error->getMessageKey(), [], $this->alias);
306
307 //Add error message to mail field
308 $login->get('mail')->addError(new FormError($error));
309
310 //Create the RecoverType form and give the proper parameters
311 $recover = $this->factory->create($this->config['recover']['view']['form'], null, [
312 //Set action to recover route name and context
313 'action' => $this->generateUrl($this->config['route']['recover']['name'], $this->config['route']['recover']['context']),
314 //Without password
315 'password' => false,
316 //Set method
317 'method' => 'POST',
318 //Set domain
319 'translation_domain' => $this->alias
320 ]);
321
322 //Get recover mail entity
323 $recover->get('mail')
324 //Set mail from login form
325 ->setData($login->get('mail')->getData())
326 //Add recover error
327 ->addError(new FormError($this->translator->trans('Use this form to recover your account', [], $this->alias)));
328
329 //Add recover form to context
330 $context['recover'] = $recover->createView();
331 } else {
332 //Add notice
333 $this->addFlash('notice', $this->translator->trans('To change your password login with your mail and any password then follow the procedure', [], $this->alias));
334 }
335
336 //Render view
337 return $this->render(
338 //Template
339 $this->config['login']['view']['name'],
340 //Context
341 ['login' => $login->createView(), 'disabled' => $request->query->get('disabled', 0)]+$context+$this->config['login']['view']['context']
342 );
343 }
344
345 /**
346 * Recover account
347 *
348 * @param Request $request The request
349 * @param ?string $hash The hashed password
350 * @param ?string $pass The shorted password
351 * @param ?string $mail The shorted mail address
352 * @return Response The response
353 */
354 public function recover(Request $request, ?string $hash, ?string $pass, ?string $mail): Response {
355 //Set user
356 $user = null;
357
358 //Set context
359 $context = [];
360
361 //With mail, pass and hash
362 if (!empty($mail) && !empty($pass) && !empty($hash)) {
363 //With invalid hash
364 if ($hash != $this->slugger->hash($mail.$pass)) {
365 //Throw bad request
366 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash], $this->alias));
367 }
368
369 //Get mail
370 $mail = $this->slugger->unshort($smail = $mail);
371
372 //Without valid mail
373 if (filter_var($mail, FILTER_VALIDATE_EMAIL) === false) {
374 //Throw bad request
375 //XXX: prevent slugger reverse engineering by not displaying decoded mail
376 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'mail', '%value%' => $smail], $this->alias));
377 }
378
379 //With existing subscriber
380 if (empty($user = $this->doctrine->getRepository($this->config['class']['user'])->findOneByMail($mail))) {
381 //Throw not found
382 //XXX: prevent slugger reverse engineering by not displaying decoded mail
383 throw $this->createNotFoundException($this->translator->trans('Unable to find account', [], $this->alias));
384 }
385
386 //With unmatched pass
387 if ($pass != $this->slugger->hash($user->getPassword())) {
388 //Throw not found
389 //XXX: prevent use of outdated recover link
390 throw $this->createNotFoundException($this->translator->trans('Outdated recover link', [], $this->alias));
391 }
392
393 //Set context
394 $context = ['mail' => $smail, 'pass' => $pass, 'hash' => $hash];
395 }
396
397 //Create the LoginType form and give the proper parameters
398 $form = $this->factory->create($this->config['recover']['view']['form'], $user, [
399 //Set action to recover route name and context
400 'action' => $this->generateUrl($this->config['route']['recover']['name'], $context+$this->config['route']['recover']['context']),
401 //With user disable mail
402 'mail' => ($user === null),
403 //With user enable password
404 'password' => ($user !== null),
405 //Set method
406 'method' => 'POST',
407 //Set domain
408 'translation_domain' => $this->alias
409 ]);
410
411 //With post method
412 if ($request->isMethod('POST')) {
413 //Refill the fields in case the form is not valid.
414 $form->handleRequest($request);
415
416 //With form submitted and valid
417 if ($form->isSubmitted() && $form->isValid()) {
418 //Set data
419 $data = $form->getData();
420
421 //With user
422 if ($user !== null) {
423 //Set hashed password
424 $hashed = $this->hasher->hashPassword($user, $user->getPassword());
425
426 //Update pass
427 $pass = $this->slugger->hash($hashed);
428
429 //Set user password
430 $user->setPassword($hashed);
431
432 //Persist user
433 $this->manager->persist($user);
434
435 //Send to database
436 $this->manager->flush();
437
438 //Add notice
439 $this->addFlash('notice', $this->translator->trans('Account password updated', [], $this->alias));
440
441 //Redirect to user login
442 return $this->redirectToRoute($this->config['route']['login']['name'], ['mail' => $smail, 'hash' => $this->slugger->hash($smail)]+$this->config['route']['login']['context']);
443 //Find user by data mail
444 } elseif ($user = $this->doctrine->getRepository($this->config['class']['user'])->findOneByMail($data['mail'])) {
445 //Set context
446 $context = [
447 'recipient_mail' => $user->getMail(),
448 'recipient_name' => $user->getRecipientName()
449 ] + array_replace_recursive(
450 $this->config['context'],
451 $this->config['recover']['view']['context'],
452 $this->config['recover']['mail']['context']
453 );
454
455 //Generate each route route
456 foreach($this->config['recover']['route'] as $route => $tag) {
457 //Only process defined routes
458 if (!empty($this->config['route'][$route])) {
459 //Process for recover mail url
460 if ($route == 'recover') {
461 //Set the url in context
462 $context[$tag] = $this->router->generate(
463 $this->config['route'][$route]['name'],
464 //Prepend recover context with tag
465 [
466 'mail' => $smail = $this->slugger->short($context['recipient_mail']),
467 'pass' => $spass = $this->slugger->hash($pass = $user->getPassword()),
468 'hash' => $this->slugger->hash($smail.$spass)
469 ]+$this->config['route'][$route]['context'],
470 UrlGeneratorInterface::ABSOLUTE_URL
471 );
472 }
473 }
474 }
475
476 //Translate subject
477 $context['subject'] = $subject = ucfirst(
478 $this->translator->trans(
479 $this->config['recover']['mail']['subject'],
480 $this->slugger->flatten($context, null, '.', '%', '%'),
481 $this->alias
482 )
483 );
484
485 //Create message
486 $message = (new TemplatedEmail())
487 //Set sender
488 ->from(new Address($this->config['contact']['address'], $this->translator->trans($this->config['contact']['name'], [], $this->alias)))
489 //Set recipient
490 //XXX: remove the debug set in vendor/symfony/mime/Address.php +46
491 ->to(new Address($context['recipient_mail'], $context['recipient_name']))
492 //Set subject
493 ->subject($context['subject'])
494
495 //Set path to twig templates
496 ->htmlTemplate($this->config['recover']['mail']['html'])
497 ->textTemplate($this->config['recover']['mail']['text'])
498
499 //Set context
500 ->context($context);
501
502 //Add created notice
503 $this->addFlash('notice', $this->translator->trans('Account recovered', [], $this->alias));
504
505 //Try sending message
506 //XXX: mail delivery may silently fail
507 try {
508 //Send message
509 $this->mailer->send($message);
510
511 //Add sent notice
512 $this->addFlash('notice', $this->translator->trans('Your recovery mail has been sent, to retrieve your account follow the recuperate link inside', [], $this->alias));
513
514 //Add junk warning
515 $this->addFlash('warning', $this->translator->trans('If you did not receive a recovery mail, check your Spam or Junk mail folder', [], $this->alias));
516
517 //Redirect on home route to cleanup form
518 return $this->redirectToRoute($this->config['route']['home']['name'], $this->config['route']['home']['context']);
519 //Catch obvious transport exception
520 } catch(TransportExceptionInterface $e) {
521 //Add error message mail unreachable
522 $form->get('mail')->addError(new FormError($this->translator->trans('Unable to reach account', [], $this->alias)));
523 }
524 }
525 }
526 }
527
528 //Render view
529 return $this->render(
530 //Template
531 $this->config['recover']['view']['name'],
532 //Context
533 ['recover' => $form->createView()]+$this->config['recover']['view']['context']
534 );
535 }
536
537 /**
538 * Register an account
539 *
540 * @param Request $request The request
541 * @return Response The response
542 */
543 public function register(Request $request): Response {
544 //With mail
545 if (!empty($_POST['register']['mail'])) {
546 //Log new user infos
547 $this->logger->emergency(
548 $this->translator->trans(
549 'register: mail=%mail% locale=%locale% confirm=%confirm% ip=%ip%',
550 [
551 '%mail%' => $postMail = $_POST['register']['mail'],
552 '%locale%' => $request->getLocale(),
553 '%confirm%' => $this->router->generate(
554 $this->config['route']['confirm']['name'],
555 //Prepend subscribe context with tag
556 [
557 'mail' => $postSmail = $this->slugger->short($postMail),
558 'hash' => $this->slugger->hash($postSmail)
559 ]+$this->config['route']['confirm']['context'],
560 UrlGeneratorInterface::ABSOLUTE_URL
561 ),
562 '%ip%' => $request->getClientIp()
563 ],
564 $this->alias
565 )
566 );
567 }
568
569 //Init reflection
570 $reflection = new \ReflectionClass($this->config['class']['user']);
571
572 //Create new user
573 $user = $reflection->newInstance('', '');
574
575 //Create the RegisterType form and give the proper parameters
576 $form = $this->factory->create($this->config['register']['view']['form'], $user, [
577 //Set action to register route name and context
578 'action' => $this->generateUrl($this->config['route']['register']['name'], $this->config['route']['register']['context']),
579 //Set captcha
580 'captcha' => true,
581 //Set civility class
582 'civility_class' => $this->config['class']['civility'],
583 //Set civility default
584 'civility_default' => $this->doctrine->getRepository($this->config['class']['civility'])->findOneByTitle($this->config['default']['civility']),
585 //Set method
586 'method' => 'POST',
587 //Set domain
588 'translation_domain' => $this->alias
589 ]+($this->checker->isGranted('ROLE_'.strtoupper($this->config['default']['admin']))?$this->config['register']['admin']:$this->config['register']['field']));
590
591 //With post method
592 if ($request->isMethod('POST')) {
593 //Refill the fields in case the form is not valid.
594 $form->handleRequest($request);
595
596 //With form submitted and valid
597 if ($form->isSubmitted() && $form->isValid()) {
598 //Set data
599 $data = $form->getData();
600
601 //Set password
602 $user->setPassword($this->hasher->hashPassword($user, $user->getPassword()));
603
604 //Persist user
605 $this->manager->persist($user);
606
607 //Iterate on default group
608 foreach($this->config['default']['group'] as $i => $groupTitle) {
609 //Fetch group
610 if (($group = $this->doctrine->getRepository($this->config['class']['group'])->findOneByTitle($groupTitle))) {
611 //Set default group
612 //XXX: see vendor/symfony/security-core/Role/Role.php
613 $user->addGroup($group);
614 //Group not found
615 } else {
616 //Throw exception
617 //XXX: consider missing group as fatal
618 throw new \Exception(sprintf('Group %s listed in %s.default.group[%d] not found by title', $groupTitle, $this->alias, $i));
619 }
620 }
621
622 //Set context
623 $context = [
624 'recipient_mail' => $user->getMail(),
625 'recipient_name' => $user->getRecipientName()
626 ] + array_replace_recursive(
627 $this->config['context'],
628 $this->config['register']['view']['context'],
629 $this->config['register']['mail']['context']
630 );
631
632 //Generate each route route
633 foreach($this->config['register']['route'] as $route => $tag) {
634 //Only process defined routes
635 if (!empty($this->config['route'][$route])) {
636 //Process for confirm mail url
637 if ($route == 'confirm') {
638 //Set the url in context
639 $context[$tag] = $this->router->generate(
640 $this->config['route'][$route]['name'],
641 //Prepend register context with tag
642 [
643 'mail' => $smail = $this->slugger->short($context['recipient_mail']),
644 'hash' => $this->slugger->hash($smail)
645 ]+$this->config['route'][$route]['context'],
646 UrlGeneratorInterface::ABSOLUTE_URL
647 );
648 }
649 }
650 }
651
652 //Translate subject
653 $context['subject'] = $subject = ucfirst(
654 $this->translator->trans(
655 $this->config['register']['mail']['subject'],
656 $this->slugger->flatten($context, null, '.', '%', '%'),
657 $this->alias
658 )
659 );
660
661 //Create message
662 $message = (new TemplatedEmail())
663 //Set sender
664 ->from(new Address($this->config['contact']['address'], $this->translator->trans($this->config['contact']['name'], [], $this->alias)))
665 //Set recipient
666 //XXX: remove the debug set in vendor/symfony/mime/Address.php +46
667 ->to(new Address($context['recipient_mail'], $context['recipient_name']))
668 //Set subject
669 ->subject($context['subject'])
670
671 //Set path to twig templates
672 ->htmlTemplate($this->config['register']['mail']['html'])
673 ->textTemplate($this->config['register']['mail']['text'])
674
675 //Set context
676 ->context($context);
677
678 //Try saving in database
679 try {
680 //Send to database
681 $this->manager->flush();
682
683 //Add created notice
684 $this->addFlash('notice', $this->translator->trans('Account created', [], $this->alias));
685
686 //Try sending message
687 //XXX: mail delivery may silently fail
688 try {
689 //Send message
690 $this->mailer->send($message);
691
692 //Add verification notice
693 $this->addFlash('notice', $this->translator->trans('Your verification mail has been sent, to activate your account you must follow the confirmation link inside', [], $this->alias));
694
695 //Add junk warning
696 $this->addFlash('warning', $this->translator->trans('If you did not receive a verification mail, check your Spam or Junk mail folders', [], $this->alias));
697
698 //Redirect on home route to cleanup form
699 return $this->redirectToRoute($this->config['route']['home']['name'], $this->config['route']['home']['context']);
700 //Catch obvious transport exception
701 } catch(TransportExceptionInterface $e) {
702 //Add error message mail unreachable
703 $form->get('mail')->addError(new FormError($this->translator->trans('Unable to reach account', [], $this->alias)));
704 }
705 //Catch double subscription
706 } catch (UniqueConstraintViolationException $e) {
707 //Add error message mail already exists
708 $this->addFlash('error', $this->translator->trans('The account already exists', [], $this->alias));
709 }
710 }
711 }
712
713 //Render view
714 return $this->render(
715 //Template
716 $this->config['register']['view']['name'],
717 //Context
718 ['register' => $form->createView()]+$this->config['register']['view']['context']
719 );
720 }
721 }