/
ListUsersCommand.php
106 lines (94 loc) · 2.64 KB
/
ListUsersCommand.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
<?php
declare(strict_types = 1);
/**
* /src/Command/User/ListUsersCommand.php
*
* @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
*/
namespace App\Command\User;
use App\Command\Traits\SymfonyStyleTrait;
use App\Entity\User;
use App\Entity\UserGroup;
use App\Resource\UserResource;
use App\Security\RolesService;
use Closure;
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 implode;
use function sprintf;
/**
* Class ListUsersCommand
*
* @package App\Command\User
* @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
*/
class ListUsersCommand extends Command
{
use SymfonyStyleTrait;
public function __construct(
private UserResource $userResource,
private RolesService $roles,
) {
parent::__construct('user:list');
$this->setDescription('Console command to list users');
}
/**
* @noinspection PhpMissingParentCallCommonInspection
*
* @throws Throwable
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = $this->getSymfonyStyle($input, $output);
$headers = [
'Id',
'Username',
'Email',
'Full name',
'Roles (inherited)',
'Groups',
];
$io->title('Current users');
$io->table($headers, $this->getRows());
return 0;
}
/**
* Getter method for formatted user rows for console table.
*
* @return array<int, string>
*
* @throws Throwable
*/
private function getRows(): array
{
return array_map(
$this->getFormatterUser(),
$this->userResource->find(orderBy: [
'username' => 'ASC',
])
);
}
/**
* Getter method for user formatter closure. This closure will format
* single User entity for console table.
*/
private function getFormatterUser(): Closure
{
$userGroupFormatter = static fn (UserGroup $userGroup): string => sprintf(
'%s (%s)',
$userGroup->getName(),
$userGroup->getRole()->getId(),
);
return fn (User $user): array => [
$user->getId(),
$user->getUsername(),
$user->getEmail(),
$user->getFirstName() . ' ' . $user->getLastName(),
implode(",\n", $this->roles->getInheritedRoles($user->getRoles())),
implode(",\n", $user->getUserGroups()->map($userGroupFormatter)->toArray()),
];
}
}