Path: blob/master/src/infrastructure/cache/PhutilInRequestKeyValueCache.php
12241 views
<?php12/**3* Key-value cache implemented in the current request. All storage is local4* to this request (i.e., the current page) and destroyed after the request5* exits. This means the first request to this cache for a given key on a page6* will ALWAYS miss.7*8* This cache exists mostly to support unit tests. In a well-designed9* applications, you generally should not be fetching the same data over and10* over again in one request, so this cache should be of limited utility.11* If using this cache improves application performance, especially if it12* improves it significantly, it may indicate an architectural problem in your13* application.14*/15final class PhutilInRequestKeyValueCache extends PhutilKeyValueCache {1617private $cache = array();18private $ttl = array();19private $limit = 0;202122/**23* Set a limit on the number of keys this cache may contain.24*25* When too many keys are inserted, the oldest keys are removed from the26* cache. Setting a limit of `0` disables the cache.27*28* @param int Maximum number of items to store in the cache.29* @return this30*/31public function setLimit($limit) {32$this->limit = $limit;33return $this;34}353637/* -( Key-Value Cache Implementation )------------------------------------- */383940public function isAvailable() {41return true;42}4344public function getKeys(array $keys) {45$results = array();46$now = time();47foreach ($keys as $key) {48if (!isset($this->cache[$key]) && !array_key_exists($key, $this->cache)) {49continue;50}51if (isset($this->ttl[$key]) && ($this->ttl[$key] < $now)) {52continue;53}54$results[$key] = $this->cache[$key];55}5657return $results;58}5960public function setKeys(array $keys, $ttl = null) {6162foreach ($keys as $key => $value) {63$this->cache[$key] = $value;64}6566if ($ttl) {67$end = time() + $ttl;68foreach ($keys as $key => $value) {69$this->ttl[$key] = $end;70}71} else {72foreach ($keys as $key => $value) {73unset($this->ttl[$key]);74}75}7677if ($this->limit) {78$count = count($this->cache);79if ($count > $this->limit) {80$remove = array();81foreach ($this->cache as $key => $value) {82$remove[] = $key;8384$count--;85if ($count <= $this->limit) {86break;87}88}8990$this->deleteKeys($remove);91}92}9394return $this;95}9697public function deleteKeys(array $keys) {98foreach ($keys as $key) {99unset($this->cache[$key]);100unset($this->ttl[$key]);101}102103return $this;104}105106public function getAllKeys() {107return $this->cache;108}109110public function destroyCache() {111$this->cache = array();112$this->ttl = array();113114return $this;115}116117}118119120