Passed
Pull Request — master (#6182)
by Yannick
16:31 queued 06:13
created

CreateUserOnAccessUrlAction::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 0
c 1
b 0
f 0
nc 1
nop 4
dl 0
loc 6
rs 10
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
declare(strict_types=1);
6
7
namespace Chamilo\CoreBundle\Controller\Api;
8
9
use ApiPlatform\Validator\ValidatorInterface;
10
use Chamilo\CoreBundle\Dto\CreateUserOnAccessUrlInput;
11
use Chamilo\CoreBundle\Entity\AccessUrlRelUser;
12
use Chamilo\CoreBundle\Entity\User;
13
use Chamilo\CoreBundle\Repository\Node\AccessUrlRepository;
14
use Doctrine\ORM\EntityManagerInterface;
15
use Symfony\Component\HttpKernel\Attribute\AsController;
16
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
17
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
18
19
#[AsController]
20
class CreateUserOnAccessUrlAction
21
{
22
    public function __construct(
23
        private EntityManagerInterface $em,
24
        private AccessUrlRepository $accessUrlRepo,
25
        private ValidatorInterface $validator,
26
        private UserPasswordHasherInterface $passwordHasher
27
    ) {}
28
29
    public function __invoke(CreateUserOnAccessUrlInput $data): User
30
    {
31
        $this->validator->validate($data);
32
33
        $url = $this->accessUrlRepo->find($data->getAccessUrlId());
34
        if (!$url) {
35
            throw new NotFoundHttpException("Access URL not found.");
36
        }
37
38
        $user = new User();
39
        $user
40
            ->setUsername($data->getUsername())
41
            ->setFirstname($data->getFirstname())
42
            ->setLastname($data->getLastname())
43
            ->setEmail($data->getEmail())
44
            ->setLocale($data->getLocale() ?? 'en')
45
            ->setTimezone($data->getTimezone() ?? 'Europe/Paris')
46
            ->setStatus($data->getStatus() ?? 5)
47
            ->setPassword(
48
                $this->passwordHasher->hashPassword($user, $data->getPassword())
49
            );
50
51
        $this->em->persist($user);
52
        $this->em->flush();
53
54
        $rel = new AccessUrlRelUser();
55
        $rel->setUser($user)->setUrl($url);
56
57
        $this->em->persist($rel);
58
        $this->em->flush();
59
60
        return $user;
61
    }
62
}
63