stats_get_from_restapi

Fetches stats data from the REST API.

Description

(array|WP_Error) stats_get_from_restapi( (array) $args = array(), (string) $resource = '' ); 

Caches locally for 5 minutes.

Returns (array|WP_Error)

Parameters (2)

0. $args — Optional. (array) => array()
The args that are passed to the endpoint
1. $resource — Optional. (string) => ''
Sub-endpoint following /stats/

Usage

  1. if ( !function_exists( 'stats_get_from_restapi' ) ) { 
  2. require_once ABSPATH . PLUGINDIR . 'jetpack-by-wordpress-com/modules/stats.php'; 
  3.  
  4. // The args that are passed to the endpoint 
  5. $args = array(); 
  6.  
  7. // Optional sub-endpoint following /stats/ 
  8. $resource = ''; 
  9.  
  10. // NOTICE! Understand what this does before running. 
  11. $result = stats_get_from_restapi($args, $resource); 
  12.  

Defined (1)

The function is defined in the following location(s).

/modules/stats.php  
  1. function stats_get_from_restapi( $args = array(), $resource = '' ) { 
  2. $endpoint = jetpack_stats_api_path( $resource ); 
  3. $api_version = '1.1'; 
  4. $args = wp_parse_args( $args, array() ); 
  5. $cache_key = md5( implode( '|', array( $endpoint, $api_version, serialize( $args ) ) ) ); 
  6.  
  7. // Get cache 
  8. $stats_cache = Jetpack_Options::get_option( 'restapi_stats_cache', array() ); 
  9. if ( ! is_array( $stats_cache ) ) { 
  10. $stats_cache = array(); 
  11.  
  12. // Return or expire this key 
  13. if ( isset( $stats_cache[ $cache_key ] ) ) { 
  14. $time = key( $stats_cache[ $cache_key ] ); 
  15. if ( time() - $time < ( 5 * MINUTE_IN_SECONDS ) ) { 
  16. $cached_stats = $stats_cache[ $cache_key ][ $time ]; 
  17. $cached_stats = (object) array_merge( array( 'cached_at' => $time ), (array) $cached_stats ); 
  18. return $cached_stats; 
  19. unset( $stats_cache[ $cache_key ] ); 
  20.  
  21. // Do the dirty work. 
  22. $response = Jetpack_Client::wpcom_json_api_request_as_blog( $endpoint, $api_version, $args ); 
  23. if ( 200 !== wp_remote_retrieve_response_code( $response ) ) { 
  24. // If bad, just return it, don't cache. 
  25. return $response; 
  26.  
  27. $data = json_decode( wp_remote_retrieve_body( $response ) ); 
  28.  
  29. // Expire old keys 
  30. foreach ( $stats_cache as $k => $cache ) { 
  31. if ( ! is_array( $cache ) || ( 5 * MINUTE_IN_SECONDS ) < time() - key( $cache ) ) { 
  32. unset( $stats_cache[ $k ] ); 
  33.  
  34. // Set cache 
  35. $stats_cache[ $cache_key ] = array( 
  36. time() => $data,  
  37. ); 
  38. Jetpack_Options::update_option( 'restapi_stats_cache', $stats_cache, false ); 
  39.  
  40. return $data;