| 1 |
<?php |
| 2 |
/** |
| 3 |
* Remote API: Caching decorator class |
| 4 |
* |
| 5 |
* @package Parsely |
| 6 |
* @since 3.2.0 |
| 7 |
*/ |
| 8 |
|
| 9 |
declare(strict_types=1); |
| 10 |
|
| 11 |
namespace Parsely\RemoteAPI; |
| 12 |
|
| 13 |
use WP_Error; |
| 14 |
|
| 15 |
/** |
| 16 |
* Caching Decorator for remote API endpoints. |
| 17 |
*/ |
| 18 |
class Remote_API_Cache implements Remote_API_Interface { |
| 19 |
private const CACHE_GROUP = 'wp-parsely'; |
| 20 |
private const OBJECT_CACHE_TTL = 5 * MINUTE_IN_SECONDS; |
| 21 |
|
| 22 |
/** |
| 23 |
* The Remote API instance which we will cache. |
| 24 |
* |
| 25 |
* @var Remote_API_Base |
| 26 |
*/ |
| 27 |
private $remote_api; |
| 28 |
|
| 29 |
/** |
| 30 |
* A wrapped object that's compatible with the Cache Interface. |
| 31 |
* |
| 32 |
* @var Cache |
| 33 |
*/ |
| 34 |
private $cache; |
| 35 |
|
| 36 |
/** |
| 37 |
* Constructor. |
| 38 |
* |
| 39 |
* @param Remote_API_Base $remote_api The remote api object to cache. |
| 40 |
* @param Cache $cache An object cache instance. |
| 41 |
*/ |
| 42 |
public function __construct( Remote_API_Base $remote_api, Cache $cache ) { |
| 43 |
$this->remote_api = $remote_api; |
| 44 |
$this->cache = $cache; |
| 45 |
} |
| 46 |
|
| 47 |
/** |
| 48 |
* Implements caching for the Remote API interface. |
| 49 |
* |
| 50 |
* @param array<string, mixed> $query The query arguments to send to the remote API. |
| 51 |
* @param bool $associative Always `false`, just present to make definition compatible with interface. |
| 52 |
* |
| 53 |
* @return array<string, mixed>|WP_Error|false The response from the remote API, or false if the |
| 54 |
* response is empty. |
| 55 |
*/ |
| 56 |
public function get_items( $query, $associative = false ) { |
| 57 |
$cache_key = 'parsely_api_' . |
| 58 |
wp_hash( $this->remote_api->get_endpoint() ) . '_' . |
| 59 |
wp_hash( (string) wp_json_encode( $query ) ); |
| 60 |
|
| 61 |
/** |
| 62 |
* Variable. |
| 63 |
* |
| 64 |
* @var array<string, mixed>|false |
| 65 |
*/ |
| 66 |
$items = $this->cache->get( $cache_key, self::CACHE_GROUP ); |
| 67 |
|
| 68 |
if ( false === $items ) { |
| 69 |
$items = $this->remote_api->get_items( $query ); |
| 70 |
$this->cache->set( $cache_key, $items, self::CACHE_GROUP, self::OBJECT_CACHE_TTL ); |
| 71 |
} |
| 72 |
|
| 73 |
return $items; |
| 74 |
} |
| 75 |
|
| 76 |
/** |
| 77 |
* Checks if the current user is allowed to make the API call. |
| 78 |
* |
| 79 |
* @since 3.7.0 |
| 80 |
* |
| 81 |
* @return bool |
| 82 |
*/ |
| 83 |
public function is_user_allowed_to_make_api_call(): bool { |
| 84 |
return $this->remote_api->is_user_allowed_to_make_api_call(); |
| 85 |
} |
| 86 |
} |
| 87 |
|