Files

72 lines
1.8 KiB
PHP
Raw Permalink Normal View History

2026-04-01 13:52:12 +08:00
<?php
declare(strict_types=1);
namespace App\Command;
use App\Model\User;
use Hyperf\Command\Annotation\Command;
use Hyperf\Command\Command as HyperfCommand;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Input\InputOption;
#[Command]
class UserListCommand extends HyperfCommand
{
public function __construct(protected ContainerInterface $container)
{
parent::__construct('user:list');
}
public function configure(): void
{
parent::configure();
$this->setDescription('List all system users');
$this->addOption('role', 'r', InputOption::VALUE_OPTIONAL, 'Filter by role name (e.g. administrator, developer, accessor)');
}
public function handle(): int
{
$query = User::query()->with('role');
$role_name = $this->input->getOption('role');
if ($role_name) {
$query->whereHas('role', fn ($q) => $q->where('name', $role_name));
}
$users = $query->orderBy('id')->get();
if ($users->isEmpty()) {
$this->info('No users found.');
return 0;
}
$rows = $users->map(fn (User $u) => [
$u->id,
$u->username,
$u->email,
$u->role?->name ?? '-',
$this->formatStatus($u->status),
$u->created_at?->toDateTimeString(),
])->toArray();
$this->table(
['ID', 'Username', 'Email', 'Role', 'Status', 'Created At'],
$rows,
);
$this->info(sprintf('Total: %d user(s)', count($rows)));
return 0;
}
private function formatStatus(int $status): string
{
return match ($status) {
1 => '<fg=green>enabled</>',
0 => '<fg=red>disabled</>',
default => '<fg=yellow>unknown</>',
};
}
}