feat: tenant management console commands

Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
This commit is contained in:
2026-07-19 22:38:43 -04:00
parent 2c640125e8
commit 934fb24217
16 changed files with 793 additions and 5 deletions
@@ -0,0 +1,120 @@
<?php
declare(strict_types=1);
namespace KTXC\Console\Tenant;
use KTXC\Models\Tenant\DomainCollection;
use KTXC\Models\Tenant\TenantConfiguration;
use KTXC\Models\Tenant\TenantObject;
use KTXC\Service\TenantService;
use KTXF\Utile\UUID;
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;
/**
* Tenant Create Command
*
* Creates a new tenant.
*/
#[AsCommand(
name: 'tenant:create',
description: 'Create a new tenant',
)]
class TenantCreateCommand extends Command
{
public function __construct(
private readonly TenantService $tenantService,
private readonly LoggerInterface $logger
) {
parent::__construct();
}
protected function configure(): void
{
$this
->addArgument('domain', InputArgument::REQUIRED | InputArgument::IS_ARRAY, 'Domain(s) served by this tenant')
->addOption('label', 'l', InputOption::VALUE_REQUIRED, 'Display label for the tenant')
->addOption('description', 'd', InputOption::VALUE_REQUIRED, 'Tenant description')
->addOption('identifier', null, InputOption::VALUE_REQUIRED, 'Explicit tenant identifier (defaults to a generated UUID)')
->addOption('disabled', null, InputOption::VALUE_NONE, 'Create the tenant in a disabled state')
->setHelp('This command creates a new tenant with one or more domains. The tenant identifier is generated automatically unless --identifier is provided.')
;
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$identifier = $input->getOption('identifier') ?? UUID::v4();
$domains = array_values(array_unique(array_filter(array_map('trim', $input->getArgument('domain')))));
$io->title('Create Tenant');
try {
if (empty($domains)) {
$io->error('At least one non-empty domain is required.');
return Command::FAILURE;
}
// Ensure identifier is unique
if ($this->tenantService->fetchById($identifier)) {
$io->error("Tenant '{$identifier}' already exists.");
return Command::FAILURE;
}
// Ensure domains are not claimed by another tenant
foreach ($domains as $domain) {
$existing = $this->tenantService->fetchByDomain($domain);
if ($existing) {
$io->error("Domain '{$domain}' is already assigned to tenant '{$existing->getIdentifier()}'.");
return Command::FAILURE;
}
}
$tenant = new TenantObject();
$tenant->setIdentifier($identifier);
$tenant->setEnabled(!$input->getOption('disabled'));
$tenant->setLabel($input->getOption('label') ?? $domains[0]);
$tenant->setDescription($input->getOption('description') ?? '');
$tenant->setDomains(new DomainCollection($domains));
$tenant->setConfiguration(new TenantConfiguration());
$tenant = $this->tenantService->deposit($tenant);
if (!$tenant) {
$io->error('Failed to create tenant.');
return Command::FAILURE;
}
$this->logger->info('Tenant created via console', [
'identifier' => $identifier,
'command' => $this->getName(),
]);
$io->success("Tenant '{$identifier}' created successfully!");
$io->definitionList(
['Id' => $tenant->getId()],
['Identifier' => $tenant->getIdentifier()],
['Label' => $tenant->getLabel()],
['Enabled' => $tenant->getEnabled() ? 'yes' : 'no'],
['Domains' => implode(', ', $domains)],
);
return Command::SUCCESS;
} catch (\Throwable $e) {
$io->error('Failed to create tenant: ' . $e->getMessage());
$this->logger->error('Tenant create failed', [
'identifier' => $identifier,
'error' => $e->getMessage(),
]);
return Command::FAILURE;
}
}
}
@@ -0,0 +1,100 @@
<?php
declare(strict_types=1);
namespace KTXC\Console\Tenant;
use KTXC\Service\TenantService;
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;
/**
* Tenant Delete Command
*
* Deletes an existing tenant.
*/
#[AsCommand(
name: 'tenant:delete',
description: 'Delete a tenant',
)]
class TenantDeleteCommand extends Command
{
public function __construct(
private readonly TenantService $tenantService,
private readonly LoggerInterface $logger
) {
parent::__construct();
}
protected function configure(): void
{
$this
->addArgument('identifier', InputArgument::REQUIRED, 'Tenant identifier to delete')
->addOption('force', 'f', InputOption::VALUE_NONE, 'Skip confirmation prompt')
->setHelp('This command deletes a tenant. Deletion must be confirmed by typing the tenant\'s primary domain. User accounts and module data belonging to the tenant are not removed.')
;
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$identifier = $input->getArgument('identifier');
$force = $input->getOption('force');
$io->title('Delete Tenant');
try {
$tenant = $this->tenantService->fetchById($identifier);
if (!$tenant) {
$io->error("Tenant '{$identifier}' not found.");
return Command::FAILURE;
}
if (!$force) {
// Confirm by typing the tenant's primary domain (identifier for
// legacy tenants without domains)
$domains = $tenant->getDomains()?->getArrayCopy() ?? [];
$confirmation = $domains[0] ?? $identifier;
$io->definitionList(
['Identifier' => $tenant->getIdentifier()],
['Label' => $tenant->getLabel()],
['Domains' => implode(', ', $domains)],
);
$answer = $io->ask("Type '{$confirmation}' to confirm deletion");
if ($answer !== $confirmation) {
$io->error('Confirmation did not match. Delete cancelled.');
return Command::FAILURE;
}
}
$this->tenantService->destroy($tenant);
$this->logger->info('Tenant deleted via console', [
'identifier' => $identifier,
'command' => $this->getName(),
]);
$io->success("Tenant '{$identifier}' deleted successfully!");
return Command::SUCCESS;
} catch (\Throwable $e) {
$io->error('Failed to delete tenant: ' . $e->getMessage());
$this->logger->error('Tenant delete failed', [
'identifier' => $identifier,
'error' => $e->getMessage(),
]);
return Command::FAILURE;
}
}
}
@@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
namespace KTXC\Console\Tenant;
use KTXC\Service\TenantService;
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 Symfony\Component\Console\Style\SymfonyStyle;
/**
* Tenant List Command
*
* Lists all tenants.
*/
#[AsCommand(
name: 'tenant:list',
description: 'List all tenants',
)]
class TenantListCommand extends Command
{
public function __construct(
private readonly TenantService $tenantService
) {
parent::__construct();
}
protected function configure(): void
{
$this->setHelp('This command lists all tenants.');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$io->title('Tenants');
try {
$tenants = $this->tenantService->list();
if (empty($tenants)) {
$io->text('No tenants found.');
return Command::SUCCESS;
}
$rows = [];
foreach ($tenants as $tenant) {
$domains = $tenant->getDomains();
$rows[] = [
$tenant->getIdentifier(),
$tenant->getLabel(),
$tenant->getEnabled() ? 'yes' : 'no',
$domains ? implode(', ', $domains->getArrayCopy()) : '',
];
}
$io->table(['Identifier', 'Label', 'Enabled', 'Domains'], $rows);
$io->text(sprintf('Total: %d tenant(s)', count($rows)));
return Command::SUCCESS;
} catch (\Throwable $e) {
$io->error('Failed to list tenants: ' . $e->getMessage());
return Command::FAILURE;
}
}
}
+2 -2
View File
@@ -52,8 +52,8 @@ class TenantObject extends JsonSerializableObject
'enabled' => $this->enabled,
'label' => $this->label,
'description' => $this->description,
'domains' => $this->domains,
'configuration' => $this->configuration,
'domains' => $this->domains?->getArrayCopy(),
'configuration' => $this->configuration?->jsonSerialize(),
];
}
+25
View File
@@ -21,6 +21,31 @@ class TenantService
return $this->store->fetch($identifier);
}
/**
* List all tenants keyed by id
*
* @return array<string, TenantObject>
*/
public function list(): array
{
return $this->store->list();
}
public function deposit(TenantObject $tenant): ?TenantObject
{
$domains = $tenant->getDomains();
if ($domains === null || count($domains) === 0) {
throw new \InvalidArgumentException('A tenant must have at least one domain.');
}
return $this->store->deposit($tenant);
}
public function destroy(TenantObject $tenant): void
{
$this->store->destroy($tenant);
}
// =========================================================================
// Settings
// =========================================================================
+8 -3
View File
@@ -3,6 +3,7 @@
namespace KTXC\Stores;
use KTXC\Db\DataStore;
use KTXC\Db\ObjectId;
use KTXC\Models\Tenant\TenantObject;
class TenantStore
@@ -52,7 +53,9 @@ class TenantStore
private function create(TenantObject $entry): ?TenantObject
{
$result = $this->dataStore->selectCollection(self::COLLECTION_NAME)->insertOne($entry->jsonSerialize());
$document = $entry->jsonSerialize();
unset($document['id']);
$result = $this->dataStore->selectCollection(self::COLLECTION_NAME)->insertOne($document);
$entry->setId((string)$result->getInsertedId());
return $entry;
}
@@ -61,7 +64,9 @@ class TenantStore
{
$id = $entry->getId();
if (!$id) { return null; }
$this->dataStore->selectCollection(self::COLLECTION_NAME)->updateOne(['_id' => $id], ['$set' => $entry->jsonSerialize()]);
$document = $entry->jsonSerialize();
unset($document['id']);
$this->dataStore->selectCollection(self::COLLECTION_NAME)->updateOne(['_id' => new ObjectId($id)], ['$set' => $document]);
return $entry;
}
@@ -69,7 +74,7 @@ class TenantStore
{
$id = $entry->getId();
if (!$id) { return; }
$this->dataStore->selectCollection(self::COLLECTION_NAME)->deleteOne([ '_id' => $id]);
$this->dataStore->selectCollection(self::COLLECTION_NAME)->deleteOne(['_id' => new ObjectId($id)]);
}
// =========================================================================