Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
CRAP
100.00% covered (success)
100.00%
1 / 1
WPCom_Themes_Cache
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
100.00% covered (success)
100.00%
1 / 1
 run_cached
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
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 */
12class WPCom_Themes_Cache {
13    /**
14     * The cache group.
15     *
16     * @var string
17     */
18    const CACHE_GROUP = 'wpcom-themes-cache';
19
20    /**
21     * Executes the supplied callable and caches the result.
22     *
23     * @param string   $cache_key The cache key.
24     * @param callable $lambda    Callable that returns theme data.
25     * @param int      $ttl       Time to live in seconds.
26     *
27     * @return mixed Cached data.
28     */
29    public function run_cached( string $cache_key, callable $lambda, int $ttl = DAY_IN_SECONDS ) {
30        $data = wp_cache_get( $cache_key, self::CACHE_GROUP );
31
32        if ( false !== $data && ! defined( 'IGNORE_CACHED_WPCOM_THEMES' ) ) {
33            return $data;
34        }
35
36        $data = $lambda();
37
38        // Null means the read failed rather than came back empty, and a failure is not cached: a
39        // moment's trouble reaching WordPress.com would otherwise empty the theme lists for a day.
40        if ( null !== $data ) {
41            wp_cache_set( $cache_key, $data, self::CACHE_GROUP, $ttl );
42        }
43
44        return $data;
45    }
46}