1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace App\Command; |
4
|
|
|
|
5
|
|
|
use App\Repository\UserRepositoryInterface; |
6
|
|
|
use Doctrine\ORM\EntityManagerInterface; |
7
|
|
|
use Exception; |
8
|
|
|
use function in_array; |
9
|
|
|
use Symfony\Component\Console\Command\Command; |
10
|
|
|
use Symfony\Component\Console\Input\InputArgument; |
11
|
|
|
use Symfony\Component\Console\Input\InputInterface; |
12
|
|
|
use Symfony\Component\Console\Output\OutputInterface; |
13
|
|
|
use Symfony\Component\Console\Style\SymfonyStyle; |
14
|
|
|
|
15
|
|
|
class UserPromoteCommand extends Command |
16
|
|
|
{ |
17
|
|
|
protected static $defaultName = 'app:user:promote'; |
18
|
|
|
|
19
|
|
|
private UserRepositoryInterface $userRepository; |
20
|
|
|
private EntityManagerInterface $entityManager; |
21
|
|
|
|
22
|
|
|
public function __construct(UserRepositoryInterface $userRepository, EntityManagerInterface $entityManager) |
23
|
|
|
{ |
24
|
|
|
parent::__construct(); |
25
|
|
|
$this->userRepository = $userRepository; |
26
|
|
|
$this->entityManager = $entityManager; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
protected function configure() |
30
|
|
|
{ |
31
|
|
|
$this |
32
|
|
|
->setDescription('Add new role to user') |
33
|
|
|
->addArgument('user', InputArgument::REQUIRED, 'User email') |
34
|
|
|
->addArgument('role', InputArgument::REQUIRED, 'User role') |
35
|
|
|
; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
protected function execute(InputInterface $input, OutputInterface $output) |
39
|
|
|
{ |
40
|
|
|
$io = new SymfonyStyle($input, $output); |
41
|
|
|
$userEmail = (string) $input->getArgument('user'); |
42
|
|
|
$role = (string) $input->getArgument('role'); |
43
|
|
|
|
44
|
|
|
$user = $this->userRepository->getOneByEmail($userEmail); |
45
|
|
|
if (null === $user) { |
46
|
|
|
throw new Exception('User with provided email was not found!'); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
$userRoles = $user->getRoles(); |
50
|
|
|
if (!in_array($role, $userRoles, true)) { |
51
|
|
|
$userRoles[] = $role; |
52
|
|
|
$user->setRoles($userRoles); |
53
|
|
|
$this->entityManager->flush(); |
54
|
|
|
|
55
|
|
|
$io->success(sprintf('Role %s was successfully added to user %s', $role, $userEmail)); |
56
|
|
|
|
57
|
|
|
return 0; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
$io->success(sprintf('User %s already have role %s', $userEmail, $role)); |
61
|
|
|
|
62
|
|
|
return 1; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|