store = $store; $this->limit = $limit; $this->window = $window; } /** @param string $key IP or user id; stored as a sha1 hash. */ public function allow( string $key, ?int $now = null ): bool { $now = $now ?? time(); $k = 'admirly_rl_' . sha1( $key ); $data = $this->store->get( $k ); if ( ! is_array( $data ) || ( $now - (int) $data['start'] ) >= $this->window ) { $this->store->set( $k, [ 'start' => $now, 'count' => 1, ], $this->window ); return true; } if ( (int) $data['count'] >= $this->limit ) { return false; } ++$data['count']; $remaining = max( 1, $this->window - ( $now - (int) $data['start'] ) ); $this->store->set( $k, $data, $remaining ); return true; } }