Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
11 / 11 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
| WPCom_Themes_Cache | |
100.00% |
11 / 11 |
|
100.00% |
2 / 2 |
6 | |
100.00% |
1 / 1 |
| run_cached | |
100.00% |
10 / 10 |
|
100.00% |
1 / 1 |
5 | |||
| forget_failures | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| 1 | <?php |
| 2 | /** |
| 3 | * Class WPCom_Themes_Cache. |
| 4 | * Caches WPCom themes. |
| 5 | * |
| 6 | * @package automattic/jetpack-mu-wpcom |
| 7 | */ |
| 8 | |
| 9 | /** |
| 10 | * Basic cache implementation for themes. |
| 11 | */ |
| 12 | class WPCom_Themes_Cache { |
| 13 | /** |
| 14 | * The cache group. |
| 15 | * |
| 16 | * @var string |
| 17 | */ |
| 18 | const CACHE_GROUP = 'wpcom-themes-cache'; |
| 19 | |
| 20 | /** |
| 21 | * Keys whose read failed during this request, shared because each reader has its own instance. |
| 22 | * |
| 23 | * @var array<string, true> |
| 24 | */ |
| 25 | private static $failed = array(); |
| 26 | |
| 27 | /** |
| 28 | * Executes the supplied callable and caches the result. |
| 29 | * |
| 30 | * @param string $cache_key The cache key. |
| 31 | * @param callable $lambda Callable that returns theme data. |
| 32 | * @param int $ttl Time to live in seconds. |
| 33 | * |
| 34 | * @return mixed Cached data. |
| 35 | */ |
| 36 | public function run_cached( string $cache_key, callable $lambda, int $ttl = DAY_IN_SECONDS ) { |
| 37 | if ( isset( self::$failed[ $cache_key ] ) ) { |
| 38 | return null; |
| 39 | } |
| 40 | |
| 41 | $data = wp_cache_get( $cache_key, self::CACHE_GROUP ); |
| 42 | |
| 43 | if ( false !== $data && ! defined( 'IGNORE_CACHED_WPCOM_THEMES' ) ) { |
| 44 | return $data; |
| 45 | } |
| 46 | |
| 47 | $data = $lambda(); |
| 48 | |
| 49 | // Null means the read failed rather than came back empty, and a failure is not cached: a |
| 50 | // moment's trouble reaching WordPress.com would otherwise empty the theme lists for a day. |
| 51 | // It is still remembered for the rest of this request, so an outage costs one timeout per key. |
| 52 | if ( null === $data ) { |
| 53 | self::$failed[ $cache_key ] = true; |
| 54 | } else { |
| 55 | wp_cache_set( $cache_key, $data, self::CACHE_GROUP, $ttl ); |
| 56 | } |
| 57 | |
| 58 | return $data; |
| 59 | } |
| 60 | |
| 61 | /** |
| 62 | * Forgets this request's failed reads, as a new request would. |
| 63 | * |
| 64 | * @return void |
| 65 | */ |
| 66 | public static function forget_failures() { |
| 67 | self::$failed = array(); |
| 68 | } |
| 69 | } |