Add RemoveOldAuditCronJob to clean up outdated audit trails

- Introduced `RemoveOldAuditCronJob` class implementing `CronJobInterface` to delete old audit trails based on configured retention period.
- Added `deleteBefore` method to `AuditTrailRepository` to handle removal of records older than the specified date.
- Created `RemoveOldAuditCronJobTest` to ensure correct functionality for job execution and canRun logic.
- Updated DI configuration to include the `delete_after` parameter for audit trail retention settings.
This commit is contained in:
2026-02-17 12:04:22 +01:00
parent ceb58de858
commit b89911e307
5 changed files with 147 additions and 0 deletions

View File

@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Audit;
use Chill\MainBundle\Cron\CronJobInterface;
use Chill\MainBundle\Entity\CronJobExecution;
use Chill\MainBundle\Repository\AuditTrailRepository;
use Symfony\Component\Clock\ClockInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
final readonly class RemoveOldAuditCronJob implements CronJobInterface
{
private \DateInterval $deleteBefore;
private const KEY = 'remove-old-audit-cron-job';
public function __construct(
ParameterBagInterface $bag,
private AuditTrailRepository $auditTrailRepository,
private ClockInterface $clock,
) {
$config = $bag->get('chill_main.audit_trail');
if (is_array($config) && is_string($intervalString = $config['delete_after'] ?? null)) {
$this->deleteBefore = new \DateInterval($intervalString);
}
}
public function canRun(?CronJobExecution $cronJobExecution): bool
{
if (null === $cronJobExecution) {
return true;
}
return $this->clock->now() >= $cronJobExecution->getLastStart()->add(new \DateInterval('PT23H58M'));
}
public function getKey(): string
{
return self::KEY;
}
public function run(array $lastExecutionData): ?array
{
$deleteBefore = $this->clock->now()->sub($this->deleteBefore);
$this->auditTrailRepository->deleteBefore($deleteBefore);
return ['delete-before' => $deleteBefore->format(\DateTimeImmutable::ISO8601_EXPANDED)];
}
}