Passed
Push — develop ( 370f48...cc396d )
by Laurent
07:33 queued 04:53
created

CreateUserHandler::__invoke()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 15
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 24
rs 9.7666
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the G.L.S.R. Apps package.
7
 *
8
 * (c) Dev-Int Création <[email protected]>.
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Administration\Infrastructure\User\Handler;
15
16
use Administration\Domain\User\Command\CreateUser;
17
use Administration\Domain\User\Model\VO\UserUuid;
18
use Administration\Infrastructure\Persistence\DoctrineOrm\Repositories\DoctrineUserRepository;
19
use Core\Domain\Model\User;
20
use Core\Domain\Protocol\Common\Command\CommandHandlerProtocol;
21
use Doctrine\ORM\NonUniqueResultException;
22
use Doctrine\ORM\OptimisticLockException;
23
use Doctrine\ORM\ORMException;
24
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
25
26
class CreateUserHandler implements CommandHandlerProtocol
27
{
28
    private DoctrineUserRepository $repository;
29
    private UserPasswordEncoderInterface $passwordEncoder;
30
31
    public function __construct(DoctrineUserRepository $repository, UserPasswordEncoderInterface $passwordEncoder)
32
    {
33
        $this->repository = $repository;
34
        $this->passwordEncoder = $passwordEncoder;
35
    }
36
37
    /**
38
     * @throws NonUniqueResultException
39
     * @throws ORMException
40
     * @throws OptimisticLockException
41
     */
42
    public function __invoke(CreateUser $command): void
43
    {
44
        if ($this->repository->existWithUsername($command->username()->getValue())) {
45
            throw new \DomainException("User with username: {$command->username()->getValue()} already exist");
46
        }
47
        if ($this->repository->existWithEmail($command->email()->getValue())) {
48
            throw new \DomainException("User with email: {$command->email()->getValue()} already exist");
49
        }
50
51
        $user = User::create(
52
            UserUuid::generate(),
53
            $command->username(),
54
            $command->email(),
55
            $command->password(),
56
            $command->roles()
57
        );
58
        $user->changePassword(
59
            $this->passwordEncoder->encodePassword(
60
                $user,
61
                $command->password()
62
            )
63
        );
64
65
        $this->repository->add($user);
66
    }
67
}
68