Files
server/core/lib/Console/Role/RoleDeleteCommand.php
T
Sebastian a723051d11 feat: console role management
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-24 21:58:16 -04:00

104 lines
3.3 KiB
PHP

<?php
declare(strict_types=1);
namespace KTXC\Console\Role;
use KTXC\Stores\UserRolesStore;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
/**
* Role Delete Command
*
* Deletes a role from a tenant.
*/
#[AsCommand(
name: 'role:delete',
description: 'Delete a role from a tenant',
)]
class RoleDeleteCommand extends Command
{
public function __construct(
private readonly UserRolesStore $rolesStore,
private readonly LoggerInterface $logger
) {
parent::__construct();
}
protected function configure(): void
{
$this
->addArgument('tenant', InputArgument::REQUIRED, 'Tenant identifier')
->addArgument('rid', InputArgument::REQUIRED, 'Role id')
->addOption('force', 'f', InputOption::VALUE_NONE, 'Skip confirmation prompt')
->setHelp('This command deletes a role from a tenant. System roles cannot be deleted, and roles still assigned to users cannot be deleted.')
;
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$tenant = $input->getArgument('tenant');
$rid = $input->getArgument('rid');
$force = $input->getOption('force');
$io->title('Delete Role');
try {
$role = $this->rolesStore->fetchByRid($tenant, $rid);
if (!$role) {
$io->error("Role '{$rid}' not found in tenant '{$tenant}'.");
return Command::FAILURE;
}
if ($role['system'] ?? false) {
$io->error("Role '{$rid}' is a system role and cannot be deleted.");
return Command::FAILURE;
}
$userCount = $this->rolesStore->countUsersInRole($tenant, $rid);
if ($userCount > 0) {
$io->error("Role '{$rid}' is assigned to {$userCount} user(s) and cannot be deleted.");
return Command::FAILURE;
}
if (!$force && !$io->confirm("Are you sure you want to delete role '{$rid}' from tenant '{$tenant}'?", false)) {
$io->text('Delete cancelled.');
return Command::SUCCESS;
}
if (!$this->rolesStore->deleteRole($tenant, $rid)) {
$io->error("Failed to delete role '{$rid}'.");
return Command::FAILURE;
}
$this->logger->info('Role deleted via console', [
'tenant' => $tenant,
'rid' => $rid,
'command' => $this->getName(),
]);
$io->success("Role '{$rid}' deleted successfully!");
return Command::SUCCESS;
} catch (\Throwable $e) {
$io->error('Failed to delete role: ' . $e->getMessage());
$this->logger->error('Role delete failed', [
'tenant' => $tenant,
'rid' => $rid,
'error' => $e->getMessage(),
]);
return Command::FAILURE;
}
}
}