1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Silverback API Components 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\ApiComponentsBundle\Factory\User; |
15
|
|
|
|
16
|
|
|
use Doctrine\ORM\EntityManagerInterface; |
17
|
|
|
use Silverback\ApiComponentsBundle\Entity\User\AbstractUser; |
18
|
|
|
use Silverback\ApiComponentsBundle\Helper\Timestamped\TimestampedDataPersister; |
19
|
|
|
use Silverback\ApiComponentsBundle\Repository\User\UserRepository; |
20
|
|
|
use Symfony\Component\Validator\Validator\ValidatorInterface; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @author Daniel West <[email protected]> |
24
|
|
|
*/ |
25
|
|
|
class UserFactory |
26
|
|
|
{ |
27
|
|
|
private EntityManagerInterface $entityManager; |
28
|
|
|
private ValidatorInterface $validator; |
29
|
|
|
private UserRepository $userRepository; |
30
|
|
|
private TimestampedDataPersister $timestampedDataPersister; |
31
|
|
|
private string $userClass; |
32
|
|
|
|
33
|
5 |
|
public function __construct(EntityManagerInterface $entityManager, ValidatorInterface $validator, UserRepository $userRepository, TimestampedDataPersister $timestampedDataPersister, string $userClass) |
34
|
|
|
{ |
35
|
5 |
|
$this->entityManager = $entityManager; |
36
|
5 |
|
$this->validator = $validator; |
37
|
5 |
|
$this->userRepository = $userRepository; |
38
|
5 |
|
$this->timestampedDataPersister = $timestampedDataPersister; |
39
|
5 |
|
$this->userClass = $userClass; |
40
|
5 |
|
} |
41
|
|
|
|
42
|
2 |
|
public function create(string $username, string $password, string $email = null, bool $inactive = false, bool $superAdmin = false, bool $overwrite = false): void |
43
|
|
|
{ |
44
|
2 |
|
if (!$email) { |
45
|
|
|
$email = $username; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** @var AbstractUser|null $user */ |
49
|
2 |
|
$user = $overwrite ? $this->userRepository->loadUserByUsername($username) : null; |
50
|
|
|
|
51
|
2 |
|
if (!$user) { |
52
|
1 |
|
$user = new $this->userClass(); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
$user |
56
|
2 |
|
->setUsername($username) |
57
|
2 |
|
->setPlainPassword($password) |
58
|
2 |
|
->setEmailAddress($email) |
59
|
2 |
|
->setEnabled(!$inactive) |
60
|
2 |
|
->setEmailAddressVerified(true) |
61
|
2 |
|
->setRoles([ |
62
|
2 |
|
$superAdmin ? 'ROLE_SUPER_ADMIN' : 'ROLE_USER', |
63
|
|
|
]); |
64
|
|
|
|
65
|
2 |
|
$this->timestampedDataPersister->persistTimestampedFields($user, true); |
66
|
2 |
|
$this->validator->validate($user); |
67
|
2 |
|
$this->entityManager->persist($user); |
68
|
2 |
|
$this->entityManager->flush(); |
69
|
2 |
|
} |
70
|
|
|
} |
71
|
|
|
|