]> Raphaël G. Git Repositories - userbundle/blob - Controller/UserController.php
Cleanup
[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 civility class
587 'civility_class' => $this->config['class']['civility'],
588 //Set civility default
589 'civility_default' => $this->doctrine->getRepository($this->config['class']['civility'])->findOneByTitle($this->config['default']['civility']),
590 //Set method
591 'method' => 'POST'
592 ]+($this->checker->isGranted($this->config['default']['admin'])?$this->config['register']['admin']:$this->config['register']['field']));
593
594 //With post method
595 if ($request->isMethod('POST')) {
596 //Refill the fields in case the form is not valid.
597 $form->handleRequest($request);
598
599 //With form submitted and valid
600 if ($form->isSubmitted() && $form->isValid()) {
601 //Set data
602 $data = $form->getData();
603
604 //Set password
605 $user->setPassword($this->hasher->hashPassword($user, $user->getPassword()));
606
607 //Persist user
608 $this->manager->persist($user);
609
610 //Iterate on default group
611 foreach($this->config['default']['group'] as $i => $groupTitle) {
612 //Fetch group
613 if (($group = $this->doctrine->getRepository($this->config['class']['group'])->findOneByTitle($groupTitle))) {
614 //Set default group
615 //XXX: see vendor/symfony/security-core/Role/Role.php
616 $user->addGroup($group);
617 //Group not found
618 } else {
619 //Throw exception
620 //XXX: consider missing group as fatal
621 throw new \Exception(sprintf('Group %s listed in %s.default.group[%d] not found by title', $groupTitle, RapsysUserBundle::getAlias(), $i));
622 }
623 }
624
625 //Set context
626 $context = [
627 'recipient_mail' => $user->getMail(),
628 'recipient_name' => $user->getRecipientName()
629 ] + array_replace_recursive(
630 $this->config['context'],
631 $this->config['register']['view']['context'],
632 $this->config['register']['mail']['context']
633 );
634
635 //Generate each route route
636 foreach($this->config['register']['route'] as $route => $tag) {
637 //Only process defined routes
638 if (!empty($this->config['route'][$route])) {
639 //Process for confirm mail url
640 if ($route == 'confirm') {
641 //Set the url in context
642 $context[$tag] = $this->router->generate(
643 $this->config['route'][$route]['name'],
644 //Prepend register context with tag
645 [
646 'mail' => $smail = $this->slugger->short($context['recipient_mail']),
647 'hash' => $this->slugger->hash($smail)
648 ]+$this->config['route'][$route]['context'],
649 UrlGeneratorInterface::ABSOLUTE_URL
650 );
651 }
652 }
653 }
654
655 //Iterate on keys to translate
656 foreach($this->config['translate'] as $translate) {
657 //Extract keys
658 $keys = explode('.', $translate);
659
660 //Set current
661 $current =& $context;
662
663 //Iterate on each subkey
664 do {
665 //Skip unset translation keys
666 if (!isset($current[current($keys)])) {
667 continue(2);
668 }
669
670 //Set current to subkey
671 $current =& $current[current($keys)];
672 } while(next($keys));
673
674 //Set translation
675 $current = $this->translator->trans($current);
676
677 //Remove reference
678 unset($current);
679 }
680
681 //Translate subject
682 $context['subject'] = $subject = ucfirst(
683 $this->translator->trans(
684 $this->config['register']['mail']['subject'],
685 $this->slugger->flatten($context, null, '.', '%', '%')
686 )
687 );
688
689 //Create message
690 $message = (new TemplatedEmail())
691 //Set sender
692 ->from(new Address($this->config['contact']['address'], $this->translator->trans($this->config['contact']['name'])))
693 //Set recipient
694 //XXX: remove the debug set in vendor/symfony/mime/Address.php +46
695 ->to(new Address($context['recipient_mail'], $context['recipient_name']))
696 //Set subject
697 ->subject($context['subject'])
698
699 //Set path to twig templates
700 ->htmlTemplate($this->config['register']['mail']['html'])
701 ->textTemplate($this->config['register']['mail']['text'])
702
703 //Set context
704 ->context($context);
705
706 //Try saving in database
707 try {
708 //Send to database
709 $this->manager->flush();
710
711 //Add error message mail already exists
712 $this->addFlash('notice', $this->translator->trans('Account created'));
713
714 //Try sending message
715 //XXX: mail delivery may silently fail
716 try {
717 //Send message
718 $this->mailer->send($message);
719
720 //Redirect on the same route with sent=1 to cleanup form
721 return $this->redirectToRoute($request->get('_route'), ['sent' => 1]+$request->get('_route_params'));
722 //Catch obvious transport exception
723 } catch(TransportExceptionInterface $e) {
724 //Add error message mail unreachable
725 $form->get('mail')->addError(new FormError($this->translator->trans('Unable to reach account')));
726 }
727 //Catch double subscription
728 } catch (UniqueConstraintViolationException $e) {
729 //Add error message mail already exists
730 $this->addFlash('error', $this->translator->trans('Account already exists'));
731 }
732 }
733 }
734
735 //Render view
736 return $this->render(
737 //Template
738 $this->config['register']['view']['name'],
739 //Context
740 ['register' => $form->createView(), 'sent' => $request->query->get('sent', 0)]+$this->config['register']['view']['context']
741 );
742 }
743 }