key = $key; $this->threshold = $threshold; $this->delay = $delay; } /** * Saves an event in an specified registry using a key. * If the number of events in the registry match the threshold, * a new rate limiter is enabled with the given delay. * * The registry of declined card attemps is cleaned after a new rate limiter is enabled. */ public function bump() { if ( ! isset( WC()->session ) ) { return; } $registry = WC()->session->get( $this->key ) ?? []; $registry[] = time(); WC()->session->set( $this->key, $registry ); } /** * Checks if the rate limiter is enabled. * * Returns a boolean. * * @return bool The rate limiter is in use. */ public function is_limited(): bool { if ( ! isset( WC()->session ) ) { return false; } if ( 'yes' === get_option( 'wcpay_session_rate_limiter_disabled_' . $this->key ) ) { return false; } $registry = WC()->session->get( $this->key ) ?? []; if ( ( is_countable( $registry ) ? count( $registry ) : 0 ) >= $this->threshold ) { $start_time_limiter = end( $registry ); $next_try_allowed_at = $start_time_limiter + $this->delay; $is_limited = time() <= $next_try_allowed_at; if ( ! $is_limited ) { WC()->session->set( $this->key, [] ); } return $is_limited; } return false; } }