feat: database anonymization command

This commit is contained in:
Björn Fromme
2026-08-10 11:19:44 +02:00
parent 73e66a9458
commit e89d8a43ad
5 changed files with 712 additions and 1 deletions
+89
View File
@@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
namespace App\Command;
use App\Service\Common\DatabaseAnonymizer;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand(
name: 'app:db:anonymize',
description: 'Anonymize personal data in the local database',
)]
class DbAnonymizeCommand extends Command
{
public function __construct(
private readonly DatabaseAnonymizer $databaseAnonymizer,
private readonly LoggerInterface $logger,
private readonly string $environment,
) {
parent::__construct();
}
protected function configure(): void
{
$this
->addOption('dry-run', null, InputOption::VALUE_NONE, 'Report the affected rows without writing anything')
->addOption('seed', null, InputOption::VALUE_REQUIRED, 'Seed for the synthetic data, so repeated runs produce identical output')
;
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
if ('prod' === $this->environment) {
$io->error('The database anonymizer is disabled in the prod environment.');
return Command::FAILURE;
}
$dryRun = true === $input->getOption('dry-run');
$seed = $input->getOption('seed');
if (false === $dryRun && true === $input->isInteractive() && false === $io->confirm('This irreversibly overwrites personal data in the current database. Continue?', false)) {
$io->warning('Aborted.');
return Command::SUCCESS;
}
try {
$report = null === $seed
? $this->databaseAnonymizer->anonymizeAll($dryRun)
: $this->databaseAnonymizer->anonymizeAll($dryRun, (int) $seed);
} catch (\Throwable $exception) {
$this->logger->error('Database anonymization failed', [
'environment' => $this->environment,
'error' => $exception->getMessage(),
]);
$io->error($exception->getMessage());
return Command::FAILURE;
}
$rows = [];
foreach ($report as $table => $count) {
$rows[] = [$table, $count];
}
$io->table(['Table', 'Rows'], $rows);
if (true === $dryRun) {
$io->note('Dry run: all changes have been rolled back.');
return Command::SUCCESS;
}
$io->success('Anonymized the local database.');
return Command::SUCCESS;
}
}