Passed
Pull Request — feature/unit-tests (#37)
by Daniel
05:46
created

UserFactory::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 6
ccs 0
cts 5
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 4
crap 2
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Component Bundle Project
5
 *
6
 * (c) Daniel West <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Silverback\ApiComponentBundle\Factory\User;
15
16
use Doctrine\ORM\EntityManagerInterface;
17
use Silverback\ApiComponentBundle\Entity\User\AbstractUser;
18
use Silverback\ApiComponentBundle\Repository\User\UserRepository;
19
use Symfony\Component\Validator\Validator\ValidatorInterface;
20
21
/**
22
 * @author Daniel West <[email protected]>
23
 */
24
class UserFactory
25
{
26
    private EntityManagerInterface $entityManager;
27
    private ValidatorInterface $validator;
28
    private UserRepository $userRepository;
29
    private string $userClass;
30
31
    public function __construct(EntityManagerInterface $entityManager, ValidatorInterface $validator, UserRepository $userRepository, string $userClass)
32
    {
33
        $this->entityManager = $entityManager;
34
        $this->validator = $validator;
35
        $this->userRepository = $userRepository;
36
        $this->userClass = $userClass;
37
    }
38
39
    public function create(string $username, string $password, string $email = null, bool $inactive = false, bool $superAdmin = false, bool $overwrite = false): void
40
    {
41
        if (!$email) {
42
            $email = $username;
43
        }
44
45
        /** @var AbstractUser|null $user */
46
        $user = $overwrite ? $this->userRepository->loadUserByUsername($username) : null;
47
48
        if (!$user) {
49
            $user = new $this->userClass();
50
        }
51
52
        $user
53
            ->setUsername($username)
54
            ->setPlainPassword($password)
55
            ->setEmailAddress($email)
56
            ->setEnabled(!$inactive)
57
            ->setEmailAddressVerified(true)
58
            ->setRoles([
59
                $superAdmin ? 'ROLE_SUPER_ADMIN' : 'ROLE_USER',
60
            ]);
61
62
        $this->validator->validate($user);
63
        $this->entityManager->persist($user);
64
        $this->entityManager->flush();
65
    }
66
}
67