Skip to content

Commit

Permalink
Add support for validity set by callback function.
Browse files Browse the repository at this point in the history
  • Loading branch information
vegardlarsen committed Oct 27, 2014
1 parent f517bde commit c3f0fed
Showing 1 changed file with 9 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/Cache.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ function set($key, $value, $validity = null)
*
* @param string $key
* @param callable $fallback
* @param int|\DateInterval|\DateTime $validity Number of seconds this is valid for (if int)
* @param int|\DateInterval|\DateTime|callable $validity Number of seconds this is valid for (if int). If this is a callable, it will get the return value as its only argument, and will need to return int|\DateInterval|\DateTime.
* @return mixed
*/
function getWithFallback($key, callable $fallback, $validity = null)
Expand All @@ -78,6 +78,14 @@ function getWithFallback($key, callable $fallback, $validity = null)
// serializing everything that goes in, and having get() throw if the content is not serialized
if ($value === false) {
$value = $fallback();
if (is_callable($validity)) {
$validity = $validity($value);
if (!($validity instanceof \DateInterval) &&
!($validity instanceof \DateTime) &&
!is_int($validity)) {
throw new \UnexpectedValueException('Validity callback should return instance of \DateTime or \DateInterval or int.');
}
}
$this->set($key, $value, $validity);
}
return $value;
Expand Down

0 comments on commit c3f0fed

Please sign in to comment.