1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Gbere\SimpleAuth\DataFixtures; |
6
|
|
|
|
7
|
|
|
use Doctrine\Bundle\FixturesBundle\Fixture; |
8
|
|
|
use Doctrine\Common\DataFixtures\DependentFixtureInterface; |
9
|
|
|
use Doctrine\ORM\OptimisticLockException; |
10
|
|
|
use Doctrine\ORM\ORMException; |
11
|
|
|
use Doctrine\Persistence\ObjectManager; |
12
|
|
|
use Gbere\SimpleAuth\Entity\Role; |
13
|
|
|
use Gbere\SimpleAuth\Repository\RoleRepository; |
14
|
|
|
use Gbere\SimpleAuth\Repository\UserRepository; |
15
|
|
|
|
16
|
|
|
class UserFixtures extends Fixture implements DependentFixtureInterface |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* @var array |
20
|
|
|
*/ |
21
|
|
|
private const USERS = [ |
22
|
|
|
'role-user' => 'ROLE_USER', |
23
|
|
|
'role-admin' => 'ROLE_ADMIN', |
24
|
|
|
]; |
25
|
|
|
|
26
|
|
|
/** @var UserRepository */ |
27
|
|
|
private $userRepository; |
28
|
|
|
/** @var RoleRepository */ |
29
|
|
|
private $roleRepository; |
30
|
|
|
|
31
|
|
|
public function __construct(UserRepository $userRepository, RoleRepository $roleRepository) |
32
|
|
|
{ |
33
|
|
|
$this->userRepository = $userRepository; |
34
|
|
|
$this->roleRepository = $roleRepository; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
public function load(ObjectManager $manager): void |
38
|
|
|
{ |
39
|
|
|
foreach (self::USERS as $userName => $userRole) { |
40
|
|
|
// Email = name + @fixture.com |
41
|
|
|
// Password = name |
42
|
|
|
$this->createAndPersistUser($userName, $userRole); |
43
|
|
|
} |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* {@inheritdoc} |
48
|
|
|
*/ |
49
|
|
|
public function getDependencies(): array |
50
|
|
|
{ |
51
|
|
|
return [ |
52
|
|
|
RoleFixtures::class, |
53
|
|
|
]; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @throws ORMException |
58
|
|
|
* @throws OptimisticLockException |
59
|
|
|
*/ |
60
|
|
|
private function createAndPersistUser(string $name, string $role): void |
61
|
|
|
{ |
62
|
|
|
$user = $this->userRepository->createUser(); |
63
|
|
|
$user->setEmail(sprintf('%[email protected]', $name)); |
64
|
|
|
$user->setName($name); |
65
|
|
|
$user->setPassword($this->userRepository->encodePassword($name)); |
66
|
|
|
/** @var Role $role */ |
67
|
|
|
$role = $this->roleRepository->findOneBy(['name' => $role]); |
68
|
|
|
$user->addRoleEntity($role); |
69
|
|
|
$user->hasEnabled(true); |
70
|
|
|
$this->userRepository->persistAndFlush($user); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|