]> Raphaël G. Git Repositories - userbundle/blob - Controller/UserController.php
Remove final
[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($this->config['default']['admin'])) {
41 //Throw 403
42 throw $this->createAccessDeniedException($this->translator->trans('Unable to list users'));
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'));
52 }
53
54 //Get users
55 $this->context['users'] = $this->doctrine->getRepository($this->config['class']['user'])->findAllAsArray($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]));
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]));
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('Account do not exists'));
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'));
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]));
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'));
140 }
141
142 //Prevent access when not admin, user is not guest and not currently logged user
143 if (!$this->checker->isGranted($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'));
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 //Set method
158 'method' => 'POST'
159 ]+($this->checker->isGranted($this->config['default']['admin'])?$this->config['edit']['admin']:$this->config['edit']['field']));
160
161 //With admin role
162 if ($this->checker->isGranted($this->config['default']['admin'])) {
163 //Create the EditType form and give the proper parameters
164 $reset = $this->factory->create($this->config['edit']['view']['reset'], $user, [
165 //Set action to edit route name and context
166 'action' => $this->generateUrl($this->config['route']['edit']['name'], ['mail' => $smail, 'hash' => $this->slugger->hash($smail)]+$this->config['route']['edit']['context']),
167 //Set method
168 'method' => 'POST'
169 ]);
170
171 //With post method
172 if ($request->isMethod('POST')) {
173 //Refill the fields in case the form is not valid.
174 $reset->handleRequest($request);
175
176 //With reset submitted and valid
177 if ($reset->isSubmitted() && $reset->isValid()) {
178 //Set data
179 $data = $reset->getData();
180
181 //Set password
182 $data->setPassword($this->hasher->hashPassword($data, $data->getPassword()));
183
184 //Queue snippet save
185 $this->manager->persist($data);
186
187 //Flush to get the ids
188 $this->manager->flush();
189
190 //Add notice
191 $this->addFlash('notice', $this->translator->trans('Account password updated'));
192
193 //Redirect to cleanup the form
194 return $this->redirectToRoute($this->config['route']['edit']['name'], ['mail' => $smail = $this->slugger->short($mail), 'hash' => $this->slugger->hash($smail)]+$this->config['route']['edit']['context']);
195 }
196 }
197
198 //Add reset view
199 $this->config['edit']['view']['context']['reset'] = $reset->createView();
200 }
201
202 //With post method
203 if ($request->isMethod('POST')) {
204 //Refill the fields in case the form is not valid.
205 $edit->handleRequest($request);
206
207 //With edit submitted and valid
208 if ($edit->isSubmitted() && $edit->isValid()) {
209 //Set data
210 $data = $edit->getData();
211
212 //Queue snippet save
213 $this->manager->persist($data);
214
215 //Try saving in database
216 try {
217 //Flush to get the ids
218 $this->manager->flush();
219
220 //Add notice
221 $this->addFlash('notice', $this->translator->trans('Account updated'));
222
223 //Redirect to cleanup the form
224 return $this->redirectToRoute($this->config['route']['edit']['name'], ['mail' => $smail = $this->slugger->short($mail), 'hash' => $this->slugger->hash($smail)]+$this->config['route']['edit']['context']);
225 //Catch double slug or mail
226 } catch (UniqueConstraintViolationException $e) {
227 //Add error message mail already exists
228 $this->addFlash('error', $this->translator->trans('Account already exists'));
229 }
230 }
231 //Without admin role
232 //XXX: prefer a reset on login to force user unspam action
233 } elseif (!$this->checker->isGranted($this->config['default']['admin'])) {
234 //Add notice
235 $this->addFlash('notice', $this->translator->trans('To change your password login with your mail and any password then follow the procedure'));
236 }
237
238 //Render view
239 return $this->render(
240 //Template
241 $this->config['edit']['view']['name'],
242 //Context
243 ['edit' => $edit->createView(), 'sent' => $request->query->get('sent', 0)]+$this->config['edit']['view']['context']
244 );
245 }
246
247 /**
248 * Login
249 *
250 * @param Request $request The request
251 * @param AuthenticationUtils $authenticationUtils The authentication utils
252 * @param ?string $hash The hashed password
253 * @param ?string $mail The shorted mail address
254 * @return Response The response
255 */
256 public function login(Request $request, AuthenticationUtils $authenticationUtils, ?string $hash, ?string $mail): Response {
257 //Create the LoginType form and give the proper parameters
258 $login = $this->factory->create($this->config['login']['view']['form'], null, [
259 //Set action to login route name and context
260 'action' => $this->generateUrl($this->config['route']['login']['name'], $this->config['route']['login']['context']),
261 //Set method
262 'method' => 'POST'
263 ]);
264
265 //Init context
266 $context = [];
267
268 //With mail
269 if (!empty($mail) && !empty($hash)) {
270 //With invalid hash
271 if ($hash != $this->slugger->hash($mail)) {
272 //Throw bad request
273 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash]));
274 }
275
276 //Get mail
277 $mail = $this->slugger->unshort($smail = $mail);
278
279 //Without valid mail
280 if (filter_var($mail, FILTER_VALIDATE_EMAIL) === false) {
281 //Throw bad request
282 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'mail', '%value%' => $smail]));
283 }
284
285 //Prefilled mail
286 $login->get('mail')->setData($mail);
287 //Last username entered by the user
288 } elseif ($lastUsername = $authenticationUtils->getLastUsername()) {
289 $login->get('mail')->setData($lastUsername);
290 }
291
292 //Get the login error if there is one
293 if ($error = $authenticationUtils->getLastAuthenticationError()) {
294 //Get translated error
295 $error = $this->translator->trans($error->getMessageKey());
296
297 //Add error message to mail field
298 $login->get('mail')->addError(new FormError($error));
299
300 //Create the RecoverType form and give the proper parameters
301 $recover = $this->factory->create($this->config['recover']['view']['form'], null, [
302 //Set action to recover route name and context
303 'action' => $this->generateUrl($this->config['route']['recover']['name'], $this->config['route']['recover']['context']),
304 //Without password
305 'password' => false,
306 //Set method
307 'method' => 'POST'
308 ]);
309
310 //Get recover mail entity
311 $recover->get('mail')
312 //Set mail from login form
313 ->setData($login->get('mail')->getData())
314 //Add recover error
315 ->addError(new FormError($this->translator->trans('Use this form to recover your account')));
316
317 //Add recover form to context
318 $context['recover'] = $recover->createView();
319 } else {
320 //Add notice
321 $this->addFlash('notice', $this->translator->trans('To change your password login with your mail and any password then follow the procedure'));
322 }
323
324 //Render view
325 return $this->render(
326 //Template
327 $this->config['login']['view']['name'],
328 //Context
329 ['login' => $login->createView(), 'disabled' => $request->query->get('disabled', 0), 'sent' => $request->query->get('sent', 0)]+$context+$this->config['login']['view']['context']
330 );
331 }
332
333 /**
334 * Recover account
335 *
336 * @param Request $request The request
337 * @param ?string $hash The hashed password
338 * @param ?string $pass The shorted password
339 * @param ?string $mail The shorted mail address
340 * @return Response The response
341 */
342 public function recover(Request $request, ?string $hash, ?string $pass, ?string $mail): Response {
343 //Set user
344 $user = null;
345
346 //Set context
347 $context = [];
348
349 //With mail, pass and hash
350 if (!empty($mail) && !empty($pass) && !empty($hash)) {
351 //With invalid hash
352 if ($hash != $this->slugger->hash($mail.$pass)) {
353 //Throw bad request
354 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash]));
355 }
356
357 //Get mail
358 $mail = $this->slugger->unshort($smail = $mail);
359
360 //Without valid mail
361 if (filter_var($mail, FILTER_VALIDATE_EMAIL) === false) {
362 //Throw bad request
363 //XXX: prevent slugger reverse engineering by not displaying decoded mail
364 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'mail', '%value%' => $smail]));
365 }
366
367 //With existing subscriber
368 if (empty($user = $this->doctrine->getRepository($this->config['class']['user'])->findOneByMail($mail))) {
369 //Throw not found
370 //XXX: prevent slugger reverse engineering by not displaying decoded mail
371 throw $this->createNotFoundException($this->translator->trans('Unable to find account'));
372 }
373
374 //With unmatched pass
375 if ($pass != $this->slugger->hash($user->getPassword())) {
376 //Throw not found
377 //XXX: prevent use of outdated recover link
378 throw $this->createNotFoundException($this->translator->trans('Outdated recover link'));
379 }
380
381 //Set context
382 $context = ['mail' => $smail, 'pass' => $pass, 'hash' => $hash];
383 }
384
385 //Create the LoginType form and give the proper parameters
386 $form = $this->factory->create($this->config['recover']['view']['form'], $user, [
387 //Set action to recover route name and context
388 'action' => $this->generateUrl($this->config['route']['recover']['name'], $context+$this->config['route']['recover']['context']),
389 //With user disable mail
390 'mail' => ($user === null),
391 //With user enable password
392 'password' => ($user !== null),
393 //Set method
394 'method' => 'POST'
395 ]);
396
397 //With post method
398 if ($request->isMethod('POST')) {
399 //Refill the fields in case the form is not valid.
400 $form->handleRequest($request);
401
402 //With form submitted and valid
403 if ($form->isSubmitted() && $form->isValid()) {
404 //Set data
405 $data = $form->getData();
406
407 //With user
408 if ($user !== null) {
409 //Set hashed password
410 $hashed = $this->hasher->hashPassword($user, $user->getPassword());
411
412 //Update pass
413 $pass = $this->slugger->hash($hashed);
414
415 //Set user password
416 $user->setPassword($hashed);
417
418 //Persist user
419 $this->manager->persist($user);
420
421 //Send to database
422 $this->manager->flush();
423
424 //Add notice
425 $this->addFlash('notice', $this->translator->trans('Account password updated'));
426
427 //Redirect to user login
428 return $this->redirectToRoute($this->config['route']['login']['name'], ['mail' => $smail, 'hash' => $this->slugger->hash($smail)]+$this->config['route']['login']['context']);
429 //Find user by data mail
430 } elseif ($user = $this->doctrine->getRepository($this->config['class']['user'])->findOneByMail($data['mail'])) {
431 //Set context
432 $context = [
433 'recipient_mail' => $user->getMail(),
434 'recipient_name' => $user->getRecipientName()
435 ] + array_replace_recursive(
436 $this->config['context'],
437 $this->config['recover']['view']['context'],
438 $this->config['recover']['mail']['context']
439 );
440
441 //Generate each route route
442 foreach($this->config['recover']['route'] as $route => $tag) {
443 //Only process defined routes
444 if (!empty($this->config['route'][$route])) {
445 //Process for recover mail url
446 if ($route == 'recover') {
447 //Set the url in context
448 $context[$tag] = $this->router->generate(
449 $this->config['route'][$route]['name'],
450 //Prepend recover context with tag
451 [
452 'mail' => $smail = $this->slugger->short($context['recipient_mail']),
453 'pass' => $spass = $this->slugger->hash($pass = $user->getPassword()),
454 'hash' => $this->slugger->hash($smail.$spass)
455 ]+$this->config['route'][$route]['context'],
456 UrlGeneratorInterface::ABSOLUTE_URL
457 );
458 }
459 }
460 }
461
462 //Iterate on keys to translate
463 foreach($this->config['translate'] as $translate) {
464 //Extract keys
465 $keys = explode('.', $translate);
466
467 //Set current
468 $current =& $context;
469
470 //Iterate on each subkey
471 do {
472 //Skip unset translation keys
473 if (!isset($current[current($keys)])) {
474 continue(2);
475 }
476
477 //Set current to subkey
478 $current =& $current[current($keys)];
479 } while(next($keys));
480
481 //Set translation
482 $current = $this->translator->trans($current);
483
484 //Remove reference
485 unset($current);
486 }
487
488 //Translate subject
489 $context['subject'] = $subject = ucfirst(
490 $this->translator->trans(
491 $this->config['recover']['mail']['subject'],
492 $this->slugger->flatten($context, null, '.', '%', '%')
493 )
494 );
495
496 //Create message
497 $message = (new TemplatedEmail())
498 //Set sender
499 ->from(new Address($this->config['contact']['address'], $this->translator->trans($this->config['contact']['name'])))
500 //Set recipient
501 //XXX: remove the debug set in vendor/symfony/mime/Address.php +46
502 ->to(new Address($context['recipient_mail'], $context['recipient_name']))
503 //Set subject
504 ->subject($context['subject'])
505
506 //Set path to twig templates
507 ->htmlTemplate($this->config['recover']['mail']['html'])
508 ->textTemplate($this->config['recover']['mail']['text'])
509
510 //Set context
511 ->context($context);
512
513 //Try sending message
514 //XXX: mail delivery may silently fail
515 try {
516 //Send message
517 $this->mailer->send($message);
518
519 //Add notice
520 $this->addFlash('notice', $this->translator->trans('Your recovery mail has been sent, to retrieve your account follow the recuperate link inside'));
521
522 //Add junk warning
523 $this->addFlash('warning', $this->translator->trans('If you did not receive a recovery mail, check your Spam or Junk mail folder'));
524
525 //Redirect on the same route with sent=1 to cleanup form
526 return $this->redirectToRoute($request->get('_route'), ['sent' => 1]+$request->get('_route_params'), 302);
527 //Catch obvious transport exception
528 } catch(TransportExceptionInterface $e) {
529 //Add error message mail unreachable
530 $form->get('mail')->addError(new FormError($this->translator->trans('Unable to reach account')));
531 }
532 }
533 }
534 }
535
536 //Render view
537 return $this->render(
538 //Template
539 $this->config['recover']['view']['name'],
540 //Context
541 ['recover' => $form->createView(), 'sent' => $request->query->get('sent', 0)]+$this->config['recover']['view']['context']
542 );
543 }
544
545 /**
546 * Register an account
547 *
548 * @param Request $request The request
549 * @return Response The response
550 */
551 public function register(Request $request): Response {
552 //With mail
553 if (!empty($_POST['register']['mail'])) {
554 //Log new user infos
555 $this->logger->emergency(
556 $this->translator->trans(
557 'register: mail=%mail% locale=%locale% confirm=%confirm% ip=%ip%',
558 [
559 '%mail%' => $postMail = $_POST['register']['mail'],
560 '%locale%' => $request->getLocale(),
561 '%confirm%' => $this->router->generate(
562 $this->config['route']['confirm']['name'],
563 //Prepend subscribe context with tag
564 [
565 'mail' => $postSmail = $this->slugger->short($postMail),
566 'hash' => $this->slugger->hash($postSmail)
567 ]+$this->config['route']['confirm']['context'],
568 UrlGeneratorInterface::ABSOLUTE_URL
569 ),
570 '%ip%' => $request->getClientIp()
571 ]
572 )
573 );
574 }
575
576 //Init reflection
577 $reflection = new \ReflectionClass($this->config['class']['user']);
578
579 //Create new user
580 $user = $reflection->newInstance('', '');
581
582 //Create the RegisterType form and give the proper parameters
583 $form = $this->factory->create($this->config['register']['view']['form'], $user, [
584 //Set action to register route name and context
585 'action' => $this->generateUrl($this->config['route']['register']['name'], $this->config['route']['register']['context']),
586 //Set captcha
587 'captcha' => true,
588 //Set civility class
589 'civility_class' => $this->config['class']['civility'],
590 //Set civility default
591 'civility_default' => $this->doctrine->getRepository($this->config['class']['civility'])->findOneByTitle($this->config['default']['civility']),
592 //Set method
593 'method' => 'POST'
594 ]+($this->checker->isGranted($this->config['default']['admin'])?$this->config['register']['admin']:$this->config['register']['field']));
595
596 //With post method
597 if ($request->isMethod('POST')) {
598 //Refill the fields in case the form is not valid.
599 $form->handleRequest($request);
600
601 //With form submitted and valid
602 if ($form->isSubmitted() && $form->isValid()) {
603 //Set data
604 $data = $form->getData();
605
606 //Set password
607 $user->setPassword($this->hasher->hashPassword($user, $user->getPassword()));
608
609 //Persist user
610 $this->manager->persist($user);
611
612 //Iterate on default group
613 foreach($this->config['default']['group'] as $i => $groupTitle) {
614 //Fetch group
615 if (($group = $this->doctrine->getRepository($this->config['class']['group'])->findOneByTitle($groupTitle))) {
616 //Set default group
617 //XXX: see vendor/symfony/security-core/Role/Role.php
618 $user->addGroup($group);
619 //Group not found
620 } else {
621 //Throw exception
622 //XXX: consider missing group as fatal
623 throw new \Exception(sprintf('Group %s listed in %s.default.group[%d] not found by title', $groupTitle, RapsysUserBundle::getAlias(), $i));
624 }
625 }
626
627 //Set context
628 $context = [
629 'recipient_mail' => $user->getMail(),
630 'recipient_name' => $user->getRecipientName()
631 ] + array_replace_recursive(
632 $this->config['context'],
633 $this->config['register']['view']['context'],
634 $this->config['register']['mail']['context']
635 );
636
637 //Generate each route route
638 foreach($this->config['register']['route'] as $route => $tag) {
639 //Only process defined routes
640 if (!empty($this->config['route'][$route])) {
641 //Process for confirm mail url
642 if ($route == 'confirm') {
643 //Set the url in context
644 $context[$tag] = $this->router->generate(
645 $this->config['route'][$route]['name'],
646 //Prepend register context with tag
647 [
648 'mail' => $smail = $this->slugger->short($context['recipient_mail']),
649 'hash' => $this->slugger->hash($smail)
650 ]+$this->config['route'][$route]['context'],
651 UrlGeneratorInterface::ABSOLUTE_URL
652 );
653 }
654 }
655 }
656
657 //Iterate on keys to translate
658 foreach($this->config['translate'] as $translate) {
659 //Extract keys
660 $keys = explode('.', $translate);
661
662 //Set current
663 $current =& $context;
664
665 //Iterate on each subkey
666 do {
667 //Skip unset translation keys
668 if (!isset($current[current($keys)])) {
669 continue(2);
670 }
671
672 //Set current to subkey
673 $current =& $current[current($keys)];
674 } while(next($keys));
675
676 //Set translation
677 $current = $this->translator->trans($current);
678
679 //Remove reference
680 unset($current);
681 }
682
683 //Translate subject
684 $context['subject'] = $subject = ucfirst(
685 $this->translator->trans(
686 $this->config['register']['mail']['subject'],
687 $this->slugger->flatten($context, null, '.', '%', '%')
688 )
689 );
690
691 //Create message
692 $message = (new TemplatedEmail())
693 //Set sender
694 ->from(new Address($this->config['contact']['address'], $this->translator->trans($this->config['contact']['name'])))
695 //Set recipient
696 //XXX: remove the debug set in vendor/symfony/mime/Address.php +46
697 ->to(new Address($context['recipient_mail'], $context['recipient_name']))
698 //Set subject
699 ->subject($context['subject'])
700
701 //Set path to twig templates
702 ->htmlTemplate($this->config['register']['mail']['html'])
703 ->textTemplate($this->config['register']['mail']['text'])
704
705 //Set context
706 ->context($context);
707
708 //Try saving in database
709 try {
710 //Send to database
711 $this->manager->flush();
712
713 //Add error message mail already exists
714 $this->addFlash('notice', $this->translator->trans('Account created'));
715
716 //Try sending message
717 //XXX: mail delivery may silently fail
718 try {
719 //Send message
720 $this->mailer->send($message);
721
722 //Redirect on the same route with sent=1 to cleanup form
723 return $this->redirectToRoute($request->get('_route'), ['sent' => 1]+$request->get('_route_params'));
724 //Catch obvious transport exception
725 } catch(TransportExceptionInterface $e) {
726 //Add error message mail unreachable
727 $form->get('mail')->addError(new FormError($this->translator->trans('Unable to reach account')));
728 }
729 //Catch double subscription
730 } catch (UniqueConstraintViolationException $e) {
731 //Add error message mail already exists
732 $this->addFlash('error', $this->translator->trans('Account already exists'));
733 }
734 }
735 }
736
737 //Render view
738 return $this->render(
739 //Template
740 $this->config['register']['view']['name'],
741 //Context
742 ['register' => $form->createView(), 'sent' => $request->query->get('sent', 0)]+$this->config['register']['view']['context']
743 );
744 }
745 }