Skip to content

Commit 174992d

Browse files
committed
Improve: Added duplicate request limiting
1 parent 5bc8880 commit 174992d

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

src/services/class-service.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,4 +161,31 @@ protected function set_transient( string $key, $value, int $expiration = 0 ): bo
161161
protected function delete_transient( string $key ): bool {
162162
return delete_site_transient( $this->get_transient_key( $key ) );
163163
}
164+
165+
/**
166+
* Checks if a request is too frequent.
167+
*
168+
* @since 1.0.0
169+
*
170+
* @param string $key Transient key.
171+
*
172+
* @return bool
173+
*/
174+
protected function is_duplicate_request( string $key ): bool {
175+
return $this->get_transient( $key ) ?? false;
176+
}
177+
178+
/**
179+
* Sets a flag for request time.
180+
*
181+
* @since 1.0.0
182+
*
183+
* @param string $key Transient key.
184+
* @param int $expiration Expiration.
185+
*
186+
* @return bool
187+
*/
188+
protected function set_request_time( string $key, $expiration = MINUTE_IN_SECONDS * 5 ): bool {
189+
return $this->set_transient( $key, time(), $expiration );
190+
}
164191
}

src/services/class-update.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,15 +50,19 @@ public function __construct( Plugin $plugin ) {
5050
*/
5151
public function get_update_data() {
5252
// On force-check, delete transient.
53-
if ( isset( $_GET['force-check'] ) ) {
53+
if ( isset( $_GET['force-check'] ) && ! $this->is_duplicate_request( 'update_check' ) ) {
5454
$this->delete_transient( 'update_data' );
5555
}
5656

5757
// Save update data to transient if required.
5858
$update_data = $this->get_transient( 'update_data' );
5959
if ( ! $update_data ) {
6060
$update_data = $this->get_remote_latest();
61-
$this->set_transient( 'update_data', $update_data, DAY_IN_SECONDS );
61+
// To prevent multiple requests for 5 mins.
62+
$this->set_request_time( 'update_check' );
63+
if ( ! is_wp_error( $update_data ) ) {
64+
$this->set_transient( 'update_data', $update_data, DAY_IN_SECONDS );
65+
}
6266
}
6367

6468
return $update_data;

0 commit comments

Comments
 (0)