Completed
Push — master ( 6f429a...4083cc )
by Alexis
06:02
created

EmailConfirmationListener   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 7
dl 0
loc 73
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A getSubscribedEvents() 0 6 1
A sendConfirmationEmail() 0 16 2
A generateToken() 0 4 1
1
<?php
2
3
namespace AWurth\SilexUser\EventListener;
4
5
use AWurth\SilexUser\Entity\UserInterface;
6
use AWurth\SilexUser\Event\Events;
7
use AWurth\SilexUser\Event\FormEvent;
8
use AWurth\SilexUser\Mailer\MailerInterface;
9
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
10
use Symfony\Component\HttpFoundation\RedirectResponse;
11
use Symfony\Component\HttpFoundation\Session\SessionInterface;
12
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
13
14
class EmailConfirmationListener implements EventSubscriberInterface
15
{
16
    /**
17
     * @var MailerInterface
18
     */
19
    protected $mailer;
20
21
    /**
22
     * @var UrlGeneratorInterface
23
     */
24
    protected $router;
25
26
    /**
27
     * @var SessionInterface
28
     */
29
    protected $session;
30
31
    /**
32
     * Constructor.
33
     *
34
     * @param MailerInterface       $mailer
35
     * @param UrlGeneratorInterface $router
36
     * @param SessionInterface      $session
37
     */
38
    public function __construct(MailerInterface $mailer, UrlGeneratorInterface $router, SessionInterface $session)
39
    {
40
        $this->mailer = $mailer;
41
        $this->router = $router;
42
        $this->session = $session;
43
    }
44
45
    /**
46
     * {@inheritdoc}
47
     */
48
    public static function getSubscribedEvents()
49
    {
50
        return [
51
            Events::REGISTRATION_SUCCESS => 'sendConfirmationEmail'
52
        ];
53
    }
54
55
    /**
56
     * Sends an email to the user to activate his account.
57
     *
58
     * @param FormEvent $event
59
     */
60
    public function sendConfirmationEmail(FormEvent $event)
61
    {
62
        /** @var UserInterface $user */
63
        $user = $event->getForm()->getData();
64
65
        $user->setEnabled(false);
66
        if (null === $user->getConfirmationToken()) {
67
            $user->setConfirmationToken($this->generateToken());
68
        }
69
70
        $this->mailer->sendConfirmationEmailMessage($user);
71
72
        $this->session->set('silex_user_confirmation_email', $user->getEmail());
73
74
        $event->setResponse(new RedirectResponse($this->router->generate('silex_user.registration_check_email')));
75
    }
76
77
    /**
78
     * Generates a new confirmation token.
79
     *
80
     * @return string
81
     */
82
    protected function generateToken()
83
    {
84
        return rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '=');
85
    }
86
}
87