From 0dfac465b234d5490432d1920706e81c6a88b667 Mon Sep 17 00:00:00 2001 From: Matthew Poulter Date: Thu, 2 Nov 2023 08:00:41 +0100 Subject: [PATCH] Simplify connector --- src/VendConnector.php | 42 ++++++++++++++++++++++++++---------------- 1 file changed, 26 insertions(+), 16 deletions(-) diff --git a/src/VendConnector.php b/src/VendConnector.php index 5f69e6d..9ba812b 100644 --- a/src/VendConnector.php +++ b/src/VendConnector.php @@ -3,11 +3,11 @@ namespace SimpleSquid\Vend; use Composer\InstalledVersions; +use Saloon\Contracts\Authenticator; use Saloon\Helpers\OAuth2\OAuthConfig; use Saloon\Http\Connector; use Saloon\Traits\OAuth2\AuthorizationCodeGrant; use Saloon\Traits\Plugins\AcceptsJson; -use SimpleSquid\Vend\Common\Exceptions\AuthenticationDetailsMissingException; use SimpleSquid\Vend\Common\Exceptions\DomainPrefixMissingException; use SimpleSquid\Vend\Common\Responses\VendResponse; @@ -18,29 +18,26 @@ abstract class VendConnector extends Connector protected ?string $response = VendResponse::class; + protected ?string $domainPrefix; + + /** + * @var callable(): ?\Saloon\Contracts\Authenticator + */ + protected $defaultAuth; + public function __construct( ?string $clientId = null, ?string $clientSecret = null, ?string $redirectUri = null, - ?string $personalToken = null, - protected ?string $domainPrefix = null, ) { - if (! is_null($personalToken)) { - $this->withTokenAuth($personalToken); - - return; - } - - if (! is_null($clientId) && ! is_null($clientSecret) && ! is_null($redirectUri)) { - $this->oauthConfig() - ->setClientId($clientId) - ->setClientSecret($clientSecret) - ->setRedirectUri($redirectUri); - + if (is_null($clientId) || is_null($clientSecret) || is_null($redirectUri)) { return; } - throw new AuthenticationDetailsMissingException(); + $this->oauthConfig() + ->setClientId($clientId) + ->setClientSecret($clientSecret) + ->setRedirectUri($redirectUri); } public function resolveBaseUrl(): string @@ -59,6 +56,14 @@ public function withDomainPrefix(string $domainPrefix): static return $this; } + /** + * @param callable(): ?\Saloon\Contracts\Authenticator $callable + */ + public function authenticateWith(callable $callable): static + { + $this->defaultAuth = $callable; + } + protected function defaultHeaders(): array { return [ @@ -73,4 +78,9 @@ protected function defaultOauthConfig(): OAuthConfig ->setTokenEndpoint('/1.0/token') ->setUserEndpoint('/2.0/retailer'); } + + protected function defaultAuth(): ?Authenticator + { + return isset($this->defaultAuth) ? ($this->defaultAuth)() : null; + } }