summaryrefslogtreecommitdiff
blob: b10342e809f06d2fddd18eb721bae078fe62a179 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?php

/**
 * Caches an EchoContainmentList within a BagOStuff(memcache, etc) to prevent needing
 * to load the nested list from a potentially slow source (mysql, etc).
 */
class EchoCachedList implements EchoContainmentList {
	const ONE_WEEK = 4233600;
	const ONE_DAY = 86400;

	protected $cache;
	protected $partialCacheKey;
	protected $nestedList;
	protected $timeout;
	private $result;

	/**
	 * @param BagOStuff $cache Bag to stored cached data in.
	 * @param string $partialCacheKey Partial cache key, $nestedList->getCacheKey() will be appended
	 *   to this to construct the cache key used.
	 * @param EchoContainmentList $nestedList The nested EchoContainmentList to cache the result of.
	 * @param int $timeout How long in seconds to cache the nested list, defaults to 1 week.
	 */
	public function __construct( BagOStuff $cache, $partialCacheKey, EchoContainmentList $nestedList, $timeout = self::ONE_WEEK ) {
		$this->cache = $cache;
		$this->partialCacheKey = $partialCacheKey;
		$this->nestedList = $nestedList;
		$this->timeout = $timeout;
	}

	/**
	 * @inheritDoc
	 */
	public function getValues() {
		if ( $this->result ) {
			return $this->result;
		}
		$this->result = $this->cache->getWithSetCallback(
			$this->getCacheKey(),
			$this->timeout,
			function () {
				$result = $this->nestedList->getValues();
				if ( !is_array( $result ) ) {
					throw new MWException( sprintf(
						"Expected array but received '%s' from '%s::getValues'",
						is_object( $result ) ? get_class( $result ) : gettype( $result ),
						get_class( $this->nestedList )
					) );
				}
				return $result;
			}
		);
		return $this->result;
	}

	/**
	 * @inheritDoc
	 */
	public function getCacheKey() {
		return $this->partialCacheKey . '_' . $this->nestedList->getCacheKey();
	}
}