/
CreateRolesCommand.php
118 lines (100 loc) · 2.91 KB
/
CreateRolesCommand.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<?php
declare(strict_types = 1);
/**
* /src/Command/User/CreateRolesCommand.php
*
* @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
*/
namespace App\Command\User;
use App\Command\Traits\SymfonyStyleTrait;
use App\Entity\Role;
use App\Repository\RoleRepository;
use App\Security\RolesService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Throwable;
use function array_map;
use function array_sum;
use function sprintf;
/**
* Class CreateRolesCommand
*
* @package App\Command\User
* @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
*/
#[AsCommand(
name: self::NAME,
description: 'Console command to create roles to database',
)]
class CreateRolesCommand extends Command
{
use SymfonyStyleTrait;
public const NAME = 'user:create-roles';
public function __construct(
private EntityManagerInterface $entityManager,
private RoleRepository $roleRepository,
private RolesService $rolesService,
) {
parent::__construct();
}
/**
* @noinspection PhpMissingParentCallCommonInspection
*
* @throws Throwable
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = $this->getSymfonyStyle($input, $output);
$created = array_sum(
array_map(
fn (string $role): int => $this->createRole($role),
$this->rolesService->getRoles(),
),
);
$this->entityManager->flush();
$removed = $this->clearRoles($this->rolesService->getRoles());
if ($input->isInteractive()) {
$message = sprintf(
'Created total of %d role(s) and removed %d role(s) - have a nice day',
$created,
$removed,
);
$io->success($message);
}
return 0;
}
/**
* Method to check if specified role exists on database and if not create
* and persist it to database.
*
* @throws Throwable
*/
private function createRole(string $role): int
{
$output = 0;
if ($this->roleRepository->find($role) === null) {
$entity = new Role($role);
$this->entityManager->persist($entity);
$output = 1;
}
return $output;
}
/**
* Method to clean existing roles from database that does not really
* exists.
*
* @param array<int, string> $roles
*/
private function clearRoles(array $roles): int
{
return (int)$this->roleRepository->createQueryBuilder('role')
->delete()
->where('role.id NOT IN(:roles)')
->setParameter(':roles', $roles)
->getQuery()
->execute();
}
}