From c3f0fed8dd592e3b8ffcb6f57244dfd0f8e2daec Mon Sep 17 00:00:00 2001 From: Vegard Andreas Larsen Date: Mon, 27 Oct 2014 09:46:46 +0100 Subject: [PATCH] Add support for validity set by callback function. See digitalcreations/cache#1. --- src/Cache.php | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/Cache.php b/src/Cache.php index 9adfe1d..36805ce 100644 --- a/src/Cache.php +++ b/src/Cache.php @@ -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) @@ -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;