Passed
Pull Request — master (#101)
by Łukasz
03:05
created

PrepareUserListener   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 44
rs 10
c 0
b 0
f 0
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A prepareAndDispatchUserCreated() 0 20 3
A getSubscribedEvents() 0 5 1
A __construct() 0 3 1
1
<?php
2
3
/**
4
 * (c) FSi sp. z o.o. <[email protected]>
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
namespace FSi\Bundle\AdminSecurityBundle\EventListener;
11
12
use FSi\Bundle\AdminBundle\Event\FormEvent;
13
use FSi\Bundle\AdminBundle\Event\FormEvents;
14
use FSi\Bundle\AdminSecurityBundle\Event\UserEvent;
15
use FSi\Bundle\AdminSecurityBundle\Security\User\UserInterface;
16
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
17
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
18
use FSi\Bundle\AdminSecurityBundle\Event\AdminSecurityEvents;
19
20
class PrepareUserListener implements EventSubscriberInterface
21
{
22
    /**
23
     * @var EventDispatcherInterface
24
     */
25
    private $eventDispatcher;
26
27
    public function __construct(EventDispatcherInterface $eventDispatcher)
28
    {
29
        $this->eventDispatcher = $eventDispatcher;
30
    }
31
32
    /**
33
     * {@inheritdoc}
34
     */
35
    public static function getSubscribedEvents()
36
    {
37
        return [
38
            FormEvents::FORM_DATA_PRE_SAVE => [
39
                'prepareAndDispatchUserCreated',
40
            ]
41
        ];
42
    }
43
44
    public function prepareAndDispatchUserCreated(FormEvent $event)
45
    {
46
        $entity = $event->getForm()->getData();
47
48
        if (!$entity instanceof UserInterface) {
49
            return;
50
        }
51
52
        // do not dispatch event and do not set random password for existing users
53
        if ($entity->getPassword()) {
54
            return;
55
        }
56
57
        $entity->setEnabled(false);
58
        $entity->enforcePasswordChange(true);
59
        $entity->setPlainPassword(random_bytes(32));
60
61
        $this->eventDispatcher->dispatch(
62
            AdminSecurityEvents::USER_CREATED,
63
            new UserEvent($entity)
64
        );
65
    }
66
}
67