restforcephp icon indicating copy to clipboard operation
restforcephp copied to clipboard

OAuthAccessToken to implements Serializable

Open drzraf opened this issue 4 years ago • 0 comments

OAuthRestClient is not serializable out of the box.

One benefit of implementing Serializable like Symfony\Component\Security\Core\Authentication\Token\TokenInterface is to offer built-in support for general string-like operations and in particular cache-like operation.

When it comes to (renewal) tokens, persistent storage and reuse are a must-have.

I would like to implement this missing part of token cache & storage (here on Symfony) and as such having OAuthRestClient would help me to use symfony/cache with no subclassing involved.

Another alternative would be to make it (array)-casting friendly and allow loading its properties from an array.

Here is a sample:

class ...  implements \Serializable
{
    public function toArray()
    {
        return [
            'token_type' => $this->getTokenType(),
            'access_token' => $this->getAccessToken(),
            'refresh_token' => $this->getRefreshToken(),
            'instance_url' => $this->getInstanceUrl(),
            'id' => $this->getResourceOwnerUrl(),
            'expire_at' => $this->getExpiresAt()
        ];
    }

    public function serialize()
    {
        return json_encode($this->toArray());
    }

    public function unserialize($serialized)
    {
        $this->loadFromArray(json_dencode($serialized));
    }

    // And optionally:
    public static function loadFromArray(array $array) : OAuthAccessToken
    {
        return new self(
            $tokenType = $token['token_type'],
            $accessToken = $token['access_token'],
            $instanceUrl = $token['instance_url'],
            $resourceOwnerUrl = $token['id'],
            $refreshToken = $token['refresh_token'] ?? null,
            $expiresAt =  $token['expire_at'] ?? null
        );
    }
}

drzraf avatar Mar 09 '20 20:03 drzraf