public static function memoize(callable $provider)
{
return function () use($provider) {
static $result;
static $isConstant;
// Constant credentials will be returned constantly.
if ($isConstant) {
return $result;
}
// Create the initial promise that will be used as the cached value
// until it expires.
if (null === $result) {
$result = $provider();
}
// Return credentials that could expire and refresh when needed.
return $result->then(function (CredentialsInterface $creds) use($provider, &$isConstant, &$result) {
// Determine if these are constant credentials.
if (!$creds->getExpiration()) {
$isConstant = true;
return $creds;
}
// Refresh expired credentials.
if (!$creds->isExpired()) {
return $creds;
}
// Refresh the result and forward the promise.
return $result = $provider();
});
};
}