From e73e7ec8112236a76ced37aafc9805beb6bf054c Mon Sep 17 00:00:00 2001 From: Tim Otten Date: Tue, 26 Jun 2018 16:08:50 -0700 Subject: [PATCH] (dev/core#174) CRM_Utils_Date - Add helpers for handling PSR-16 TTL's --- CRM/Utils/Date.php | 52 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/CRM/Utils/Date.php b/CRM/Utils/Date.php index 3d4570d7e1..74aa2e35ca 100644 --- a/CRM/Utils/Date.php +++ b/CRM/Utils/Date.php @@ -695,6 +695,58 @@ class CRM_Utils_Date { return TRUE; } + /** + * Translate a TTL to a concrete expiration time. + * + * @param NULL|int|DateInterval $ttl + * @param int $default + * The value to use if $ttl is not specified (NULL). + * @return int + * Timestamp (seconds since epoch). + * @throws \CRM_Utils_Cache_InvalidArgumentException + */ + public static function convertCacheTtlToExpires($ttl, $default) { + if ($ttl === NULL) { + $ttl = $default; + } + + if (is_int($ttl)) { + return time() + $ttl; + } + elseif ($ttl instanceof DateInterval) { + return date_add(new DateTime(), $ttl)->getTimestamp(); + } + else { + throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache TTL"); + } + } + + /** + * Normalize a TTL. + * + * @param NULL|int|DateInterval $ttl + * @param int $default + * The value to use if $ttl is not specified (NULL). + * @return int + * Seconds until expiration. + * @throws \CRM_Utils_Cache_InvalidArgumentException + */ + public static function convertCacheTtl($ttl, $default) { + if ($ttl === NULL) { + return $default; + } + elseif (is_int($ttl)) { + return $ttl; + } + elseif ($ttl instanceof DateInterval) { + return date_add(new DateTime(), $ttl)->getTimestamp() - time(); + } + else { + throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache TTL"); + } + } + + /** * @param null $timeStamp * -- 2.25.1