Aws\Credentials\CredentialProvider::memoize PHP Method

memoize() public static method

Ensures that cached credentials are refreshed when they expire.
public static memoize ( callable $provider ) : callable
$provider callable Credentials provider function to wrap.
return callable
    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();
            });
        };
    }

Usage Example

 /**
  * This function keeps state for the credential provider
  * @return mixed
  */
 private function getCredentialProvider()
 {
     if ($this->CredentialProvider) {
         return $this->CredentialProvider;
     }
     $provider = $this->getCredentials();
     $this->CredentialProvider = CredentialProvider::memoize($provider);
     return $this->CredentialProvider;
 }