CreateUserCommandHandler::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
c 1
b 0
f 0
nc 1
nop 4
dl 0
loc 11
ccs 0
cts 11
cp 0
crap 2
rs 10
1
<?php
2
3
namespace App\CommandHandler;
4
5
use App\Command\CreateUserCommand;
6
use App\Repository\UserRepository;
7
use Symfony\Component\Messenger\MessageBusInterface;
8
use App\CommandHandler\Exception\UserNotCreatedException;
9
use Psr\Log\LoggerInterface;
10
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
11
use App\Entity\User;
12
13
class CreateUserCommandHandler implements CommandHandlerInterface
14
{
15
    /**
16
     * @var UserRepository
17
     */
18
    private $repository;
19
    /**
20
     * @var MessageBusInterface
21
     */
22
    private $eventBus;
23
    /**
24
     * @var LoggerInterface
25
     */
26
    private $logger;
27
    /**
28
     * @var UserPasswordEncoderInterface
29
     */
30
    private $encoder;
31
32
    /**
33
     * @param MessageBusInterface $eventBus
34
     * @param UserRepository $repository
35
     * @param LoggerInterface $logger
36
     * @param UserPasswordEncoderInterface $encoder
37
     */
38
    public function __construct(
39
        MessageBusInterface $eventBus, 
40
        UserRepository $repository, 
41
        LoggerInterface $logger,
42
        UserPasswordEncoderInterface $encoder
43
    )
44
    {
45
        $this->eventBus = $eventBus;
46
        $this->repository = $repository;
47
        $this->logger = $logger;
48
        $this->encoder = $encoder;
49
    }
50
51
    /**
52
     * @param CreateUserCommand $command
53
     */
54
    public function __invoke(CreateUserCommand $command)
55
    {
56
        try {
57
            $user = new User($command->getId());
58
            $user->setFirstName($command->getFirstName());
59
            $user->setLastName($command->getLastName());
60
            $user->setEmail($command->getEmail());
61
            $user->setStatus($command->getStatus());
62
            
63
            $password = $this->encoder->encodePassword($user, $command->getPlainPassword());
64
            $user->setPassword($password);
65
66
            $this->repository->save($user);
67
        } catch (\Exception $e) {
68
            $this->logger->error($e->getMessage());
69
            throw new UserNotCreatedException('User was not created: '.$e->getMessage());
70
        }
71
72
    }
73
74
}
75