Files

61 lines
2.2 KiB
PHP

<?php
declare( strict_types=1 );
namespace StreamGoals\Core;
/**
* Daily housekeeping: removes checkouts that were started but never paid.
*
* Only rows that never received a PayPal capture id are purged, and only after a week, so a slow payment
* that PayPal finalizes later through the webhook is never discarded.
*/
final class Maintenance {
public const HOOK = 'sg_purge_abandoned';
public const MAX_AGE_DAYS = 7;
public static function register(): void {
add_action( self::HOOK, array( self::class, 'purge_abandoned' ) );
if ( ! wp_next_scheduled( self::HOOK ) ) {
wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', self::HOOK );
}
}
public static function unschedule(): void {
wp_clear_scheduled_hook( self::HOOK );
}
/**
* The single definition of "abandoned checkout", mirrored by the DELETE below (MaintenancePurgeTest checks both).
* Never purgeable: not pending, younger than MAX_AGE_DAYS, a test row (goal_id 0), or ANY row carrying PayPal capture
* evidence (a capture id, even from a PENDING/under-review capture: PayPal may still finalize it by webhook).
*
* @param array|object $row status, goal_id, paypal_capture_id, created_at (UTC 'Y-m-d H:i:s')
*/
public static function isPurgeable( array|object $row, int $now ): bool {
$r = (array) $row;
if ( 'pending' !== (string) ( $r['status'] ?? '' ) || (int) ( $r['goal_id'] ?? 0 ) <= 0 ) {
return false;
}
if ( '' !== trim( (string) ( $r['paypal_capture_id'] ?? '' ) ) ) {
return false;
}
$created = strtotime( (string) ( $r['created_at'] ?? '' ) . ' UTC' );
return false !== $created && $created < $now - self::MAX_AGE_DAYS * DAY_IN_SECONDS;
}
/** @return int Number of rows removed. */
public static function purge_abandoned(): int {
global $wpdb;
$table = $wpdb->prefix . 'sg_donations';
$cutoff = gmdate( 'Y-m-d H:i:s', time() - self::MAX_AGE_DAYS * DAY_IN_SECONDS );
$n = $wpdb->query(
$wpdb->prepare(
"DELETE FROM {$table} WHERE status = 'pending' AND (paypal_capture_id IS NULL OR paypal_capture_id = '') AND goal_id > 0 AND created_at < %s", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$cutoff
)
);
return (int) $n;
}
}