From: Aaron Schulz Date: Sat, 3 Oct 2015 19:37:28 +0000 (-0700) Subject: objectcache: Add BagOStuff::getWithSetCallback() convenience method X-Git-Tag: 1.31.0-rc.0~9538^2 X-Git-Url: https://git.cyclocoop.org/%27.%24link.%27?a=commitdiff_plain;h=355ba8530ed923d23bba1b97e366dc0f906dd006;p=lhc%2Fweb%2Fwiklou.git objectcache: Add BagOStuff::getWithSetCallback() convenience method Change-Id: I9cc162ff1cc48c1c500f2999327bd18ba235bfd0 --- diff --git a/includes/libs/objectcache/BagOStuff.php b/includes/libs/objectcache/BagOStuff.php index 31bffd4447..647d938919 100644 --- a/includes/libs/objectcache/BagOStuff.php +++ b/includes/libs/objectcache/BagOStuff.php @@ -87,6 +87,33 @@ abstract class BagOStuff implements LoggerAwareInterface { $this->debugMode = $bool; } + /** + * Get an item with the given key, regenerating and setting it if not found + * + * If the callback returns false, then nothing is stored. + * + * @param string $key + * @param int $ttl Time-to-live (seconds) + * @param callable $callback Callback that derives the new value + * @return mixed The cached value if found or the result of $callback otherwise + * @since 1.27 + */ + final public function getWithSetCallback( $key, $ttl, $callback ) { + $value = $this->get( $key ); + + if ( $value === false ) { + if ( !is_callable( $callback ) ) { + throw new InvalidArgumentException( "Invalid cache miss callback provided." ); + } + $value = call_user_func( $callback ); + if ( $value !== false ) { + $this->set( $key, $value, $ttl ); + } + } + + return $value; + } + /** * Get an item with the given key * diff --git a/tests/phpunit/includes/objectcache/BagOStuffTest.php b/tests/phpunit/includes/objectcache/BagOStuffTest.php index dbccd28a20..b9fe4903c4 100644 --- a/tests/phpunit/includes/objectcache/BagOStuffTest.php +++ b/tests/phpunit/includes/objectcache/BagOStuffTest.php @@ -120,6 +120,23 @@ class BagOStuffTest extends MediaWikiTestCase { $this->assertEquals( $this->cache->get( $key ), $value ); } + /** + * @covers BagOStuff::getWithSetCallback + */ + public function testGetWithSetCallback() { + $key = wfMemcKey( 'test' ); + $value = $this->cache->getWithSetCallback( + $key, + 30, + function () { + return 'hello kitty'; + } + ); + + $this->assertEquals( 'hello kitty', $value ); + $this->assertEquals( $value, $this->cache->get( $key ) ); + } + /** * @covers BagOStuff::incr */