function test_caching_expired() { $url = 'http://example.org/'; $args = array('method' => 'GET'); // ensure a previous cache file doesn't exists. $hash_0 = wl_caching_hash($url, $args); wl_caching_delete($hash_0); // Cache for 5 seconds. $response_0 = wl_caching_remote_request($url, $args, false, 5); #$this->assertFalse( wl_caching_response_is_cached( $response_0 ) ); // Check that the first request is still cached. $response_1 = wl_caching_remote_request($url, $args); $this->assertTrue(wl_caching_response_is_cached($response_1)); // Wait 5 seconds and check that another request is not cached. sleep(5); $response_2 = wl_caching_remote_request($url, $args); $this->assertFalse(wl_caching_response_is_cached($response_2)); }
/** * Perform a remote request and return the local copy if any. * * @since 3.0.0 * * @uses wl_caching_hash() to get the hash for a request. * @uses wl_caching_get_filename() to check whether a request is cached. * @uses wl_caching_get() to get a cached response. * @uses wl_caching_put() to store a response in the cache. * * @param string $url The remote URL. * @param array $args The request parameters. * @param bool $refresh If true, a remote request will be made and the cache will be refreshed. * @param int $expires_in_seconds How many seconds the cache is valid. * @return array The remote response. */ function wl_caching_remote_request($url, $args, $refresh = false, $expires_in_seconds = 3600) { // Merge the default settings for remote queries. $args = array_merge_recursive(unserialize(WL_REDLINK_API_HTTP_OPTIONS), $args); // echo $url . "\n"; // print_r( $args ); // Create an hash of the request. $hash = wl_caching_hash($url, $args); // If the document is cached, return the cached copy. if (!$refresh && false !== ($response = wl_caching_get($hash))) { return $response; } // Make the request, put the response in the cache and return it to the client. $response = wp_remote_request($url, $args); // Cache only valid responses. if (!is_wp_error($response) && 200 === (int) $response['response']['code']) { wl_caching_put($hash, $response, $expires_in_seconds); } return $response; }