shopware-php-sdk icon indicating copy to clipboard operation
shopware-php-sdk copied to clipboard

add RenewableContext to automatically create new accessTokens

Open Scarbous opened this issue 1 year ago • 4 comments

Scarbous avatar Jan 05 '24 15:01 Scarbous

In my opinion, this solution has the least impact on the project.

Scarbous avatar Jan 05 '24 15:01 Scarbous

Hi @Scarbous First of all, thanks for your contribution,

Could you give me an example why there's need to this "magic" getter?, the Context class is an DTO so i'd expect less magic code there :)

vienthuong avatar Jan 11 '24 07:01 vienthuong

@vienthuong my aim is to have a context that can renew the token independently.

I am aware that a DTO should not contain any logic, but the question for me is where this can be better implemented without rebuilding everything.

Übersetzt mit DeepL (https://www.deepl.com/app/?utm_source=ios&utm_medium=app&utm_campaign=share-translation)

Scarbous avatar Jan 11 '24 13:01 Scarbous

Hi @Scarbous

In that case, you can just create a class in your project and do exactly the same

class ContextRenewable
{
    private Context $originContext;
    public function __construct(Context $originContext) {
        $this->originContext = $originContext;
    }

    public function getContext(): Context
    {
        if (!$this->originContext->accessToken->isExpired()) {
            return $this->originContext;
        }

        $adminClient = new AdminAuthenticator(
            new RefreshTokenGrantType($this->originContext->accessToken->refreshToken),
            $this->originContext->apiEndpoint
        );

        $this->originContext = new Context($this->originContext->shopUrl, $adminClient->fetchAccessToken());

        return $this->originContext;
    }
}

// Usage:
$nonExpiredContext = (new ContextRenewable($context))->getContext();

vienthuong avatar Jan 11 '24 14:01 vienthuong