Skip to content

Commit

Permalink
fix: clear cache on API key change
Browse files Browse the repository at this point in the history
  • Loading branch information
dkoo committed Nov 7, 2024
1 parent bb82561 commit 84044fc
Showing 1 changed file with 13 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,9 @@ public static function init() {
add_action( 'wp_ajax_' . self::AJAX_ACTION, [ __CLASS__, 'handle_dispatch_refresh' ] );
add_action( 'wp_ajax_nopriv_' . self::AJAX_ACTION, [ __CLASS__, 'handle_dispatch_refresh' ] );

// Invalidate all cached data if API key changes.
add_action( 'update_option_newspack_mailchimp_api_key', [ __CLASS__, 'invalidate_cache' ] );

add_action( self::CRON_HOOK, [ __CLASS__, 'handle_cron' ] );
add_filter( 'cron_schedules', [ __CLASS__, 'add_cron_interval' ] ); // phpcs:ignore

Expand Down Expand Up @@ -518,28 +521,29 @@ private static function refresh_cached_data( $list_id ) {
}
}

/**
* Invalidate cached data by clearing the cache date key for all lists.
*/
public static function invalidate_cache() {
Newspack_Newsletters_Logger::log( 'Mailchimp cache: Invalidating cached data' );
delete_option( self::get_cache_date_key() );
delete_option( self::get_lists_cache_key() );
}

/**
* Handles the cron job and triggers the async requests to refresh the cache for all lists
*
* @return void
*/
public static function handle_cron() {
Newspack_Newsletters_Logger::log( 'Mailchimp cache: Handling cron request to refresh cache' );
delete_option( self::get_lists_cache_key() );
delete_option( self::get_cache_date_key() );

try {
$lists = self::fetch_lists(); // Force a cache refresh.
} catch ( Exception $e ) {
Newspack_Newsletters_Logger::log( 'Mailchimp cache: Error refreshing lists cache: ' . $e->getMessage() );
return;
}

if ( is_wp_error( $lists ) ) {
Newspack_Newsletters_Logger::log( 'Mailchimp cache: Error refreshing lists cache: ' . $lists->get_error_message() );
return;
}

foreach ( $lists as $list ) {
Newspack_Newsletters_Logger::log( 'Mailchimp cache: Dispatching request to refresh cache for list ' . $list['id'] );
self::dispatch_refresh( $list['id'] );
Expand All @@ -557,7 +561,7 @@ public static function handle_cron() {
public static function fetch_lists( $limit = null ) {
$mc = self::get_mc_api();
if ( \is_wp_error( $mc ) ) {
return $mc;
return [];
}
$lists_response = ( self::get_mc_instance() )->validate(
$mc->get(
Expand Down

0 comments on commit 84044fc

Please sign in to comment.