repository = $repository ?? new MonitorRepository(); $this->settings = $settings ?? new MonitorSettings(); } /** * Enforce both limits, age first, then count. * * @return int Total deleted rows across both passes. */ public function prune(): int { $deleted = $this->pruneByAge(); return $deleted + $this->pruneByCount(); } /** * Delete rows older than the retention cutoff, one bounded batch. * * @return int Deleted row count. */ public function pruneByAge(): int { return $this->repository->deleteOlderThan( $this->cutoff(), self::AGE_BATCH ); } /** * Delete the oldest rows past the maximum, one bounded batch. * * Removes the excess plus a margin of 20 percent of the maximum, capped * at 500 rows per pass. The margin is passed as a floor below the * maximum so the requested batch is actually deleted, which amortizes * cost so a sustained flood performs one small delete per request * instead of repruning the full excess every time. * * @return int Deleted row count. */ public function pruneByCount(): int { $max = $this->settings->getMaxRows(); $total = $this->repository->count(); if ( $total <= $max ) { return 0; } $excess = $total - $max; $margin = (int) ceil( $max * 0.2 ); $limit = min( $excess + $margin, self::COUNT_BATCH_CAP ); return $this->repository->deleteOldestOver( $max, $limit, $margin, $total ); } /** * Retention cutoff as a MySQL datetime. * * @return string Cutoff, rows last seen before this are stale. */ public function cutoff(): string { $now = function_exists( 'current_time' ) ? (string) current_time( 'mysql' ) : gmdate( 'Y-m-d H:i:s' ); $cut = strtotime( $now ); if ( false === $cut ) { $cut = time(); } return gmdate( 'Y-m-d H:i:s', $cut - $this->settings->getRetentionDays() * 86400 ); } }