PluginProbe
Parse.ly / 3.16.1
Parse.ly v3.16.1
3.24.1 3.24.0 3.23.7 3.23.6 3.23.5 3.23.4 3.23.3 3.16.0 3.16.1 3.16.2 3.16.3 3.16.4 3.17.0 3.18.0 3.18.1 3.19.0 3.19.1 3.19.2 3.19.3 3.2.0 3.2.1 3.20.0 3.20.1 3.20.2 3.20.3 All 105 releases
wp-parsely / src / RemoteAPI / class-remote-api-cache.php

class-remote-api-cache.php in Parse.ly 3.16.1, at src/RemoteAPI/class-remote-api-cache.php

92 lines 2.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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 use WP_REST_Request;
15
16 /**
17 * Caching Decorator for remote API endpoints.
18 */
19 class Remote_API_Cache implements Remote_API_Interface {
20 private const CACHE_GROUP = 'wp-parsely';
21 private const OBJECT_CACHE_TTL = 5 * MINUTE_IN_SECONDS;
22
23 /**
24 * The Remote API instance which we will cache.
25 *
26 * @var Base_Endpoint_Remote
27 */
28 private $remote_api;
29
30 /**
31 * A wrapped object that's compatible with the Cache Interface.
32 *
33 * @var Cache
34 */
35 private $cache;
36
37 /**
38 * Constructor.
39 *
40 * @param Base_Endpoint_Remote $remote_api The remote api object to cache.
41 * @param Cache $cache An object cache instance.
42 */
43 public function __construct( Base_Endpoint_Remote $remote_api, Cache $cache ) {
44 $this->remote_api = $remote_api;
45 $this->cache = $cache;
46 }
47
48 /**
49 * Implements caching for the Remote API interface.
50 *
51 * @param array<string, mixed> $query The query arguments to send to the remote API.
52 * @param bool $associative Always `false`, just present to make definition compatible
53 * with interface.
54 * @return array<string, mixed>|object|WP_Error The response from the remote API, or false if the
55 * response is empty.
56 */
57 public function get_items( array $query, bool $associative = false ) {
58 $cache_key = 'parsely_api_' .
59 wp_hash( $this->remote_api->get_endpoint() ) . '_' .
60 wp_hash( (string) wp_json_encode( $query ) );
61
62 /**
63 * Variable.
64 *
65 * @var array<string, mixed>|false
66 */
67 $items = $this->cache->get( $cache_key, self::CACHE_GROUP );
68
69 if ( false === $items ) {
70 $items = $this->remote_api->get_items( $query );
71 $this->cache->set( $cache_key, $items, self::CACHE_GROUP, self::OBJECT_CACHE_TTL );
72 }
73
74 return $items;
75 }
76
77 /**
78 * Returns whether the endpoint is available for access by the current
79 * user.
80 *
81 * @since 3.7.0
82 * @since 3.14.0 Renamed from `is_user_allowed_to_make_api_call()`.
83 * @since 3.16.0 Added the `$request` parameter.
84 *
85 * @param WP_REST_Request|null $request The request object.
86 * @return bool
87 */
88 public function is_available_to_current_user( $request = null ): bool {
89 return $this->remote_api->is_available_to_current_user( $request );
90 }
91 }
92