Skip to content

OAuthAccessToken to implements Serializable  #20

@drzraf

Description

@drzraf

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
        );
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions