| 1 |
<?php |
| 2 |
/** |
| 3 |
* Remote API: `/related` REST 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 |
/** |
| 14 |
* Caching Decorator for the remote /related endpoint. |
| 15 |
*/ |
| 16 |
class Cached_Proxy implements Proxy { |
| 17 |
private const CACHE_GROUP = 'wp-parsely'; |
| 18 |
private const OBJECT_CACHE_TTL = 5 * MINUTE_IN_SECONDS; |
| 19 |
|
| 20 |
/** |
| 21 |
* The Proxy instance this will cache. |
| 22 |
* |
| 23 |
* @var Proxy |
| 24 |
*/ |
| 25 |
private $proxy; |
| 26 |
|
| 27 |
/** |
| 28 |
* A wrapped object that's compatible with the Cache Interface. |
| 29 |
* |
| 30 |
* @var Cache |
| 31 |
*/ |
| 32 |
private $cache; |
| 33 |
|
| 34 |
/** |
| 35 |
* Constructor. |
| 36 |
* |
| 37 |
* @param Proxy $proxy The Proxy object to cache. |
| 38 |
* @param Cache $cache An object cache instance. |
| 39 |
*/ |
| 40 |
public function __construct( Proxy $proxy, Cache $cache ) { |
| 41 |
$this->proxy = $proxy; |
| 42 |
$this->cache = $cache; |
| 43 |
} |
| 44 |
|
| 45 |
/** |
| 46 |
* Implements caching for the proxy interface. |
| 47 |
* |
| 48 |
* @param array<string, mixed> $query The query arguments to send to the remote API. |
| 49 |
* @return array<string, mixed>|false The response from the remote API, or false if the |
| 50 |
* response is empty. |
| 51 |
*/ |
| 52 |
public function get_items( array $query ) { |
| 53 |
$cache_key = 'parsely_api_' . wp_hash( (string) wp_json_encode( $this->proxy ) ) . '_' . wp_hash( (string) wp_json_encode( $query ) ); |
| 54 |
$items = $this->cache->get( $cache_key, self::CACHE_GROUP ); |
| 55 |
|
| 56 |
if ( false === $items ) { |
| 57 |
$items = $this->proxy->get_items( $query ); |
| 58 |
$this->cache->set( $cache_key, $items, self::CACHE_GROUP, self::OBJECT_CACHE_TTL ); |
| 59 |
} |
| 60 |
|
| 61 |
return $items; |
| 62 |
} |
| 63 |
} |
| 64 |
|