diff --git a/.gitignore b/.gitignore index 8c109a9..cf092c6 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ composer.lock phpunit.xml tasks.md +/.idea diff --git a/src/Api/Client.php b/src/Api/Client.php index 2a04f7e..3c1ff39 100644 --- a/src/Api/Client.php +++ b/src/Api/Client.php @@ -23,11 +23,19 @@ class Client public function __construct( protected array $configs, protected Guzzle $guzzle = new Guzzle, - protected Token $token = new Token, + protected Token|string|null $token = null, protected bool $debug = false, ) { $this->setConfigs($configs); - $this->setToken($token); + + // If a token was passed in explicitly, use that + if (!is_null($token)) { + $this->setToken($token); + } + // Otherwise, request token from jwt + elseif (!empty($configs['jwt'])) { + $this->requestToken(); + } } /** @@ -139,24 +147,24 @@ public function request(?string $path, ?array $data = [], ?string $method = 'GET { // TODO: Decide if going to do more than let the exception bubble up // try { - return json_decode( - associative: true, - json: $this->guzzle->request( - method: $method, - options: [ - 'debug' => $this->debug, - 'headers' => [ - 'Authorization' => (string) $this->getToken(), - 'Content-Type' => 'application/json', - 'User-Agent' => 'SPINEN/'.$this->getVersion(), - ], - 'body' => empty($data) ? null : json_encode($data), + return json_decode( + associative: true, + json: $this->guzzle->request( + method: $method, + options: [ + 'debug' => $this->debug, + 'headers' => [ + 'Authorization' => (string) $this->getToken(), + 'Content-Type' => 'application/json', + 'User-Agent' => 'SPINEN/' . trim((string) $this->getVersion()), ], - uri: $this->uri($path), - ) - ->getBody() - ->getContents(), - ); + 'body' => empty($data) ? null : json_encode($data), + ], + uri: $this->uri($path), + ) + ->getBody() + ->getContents(), + ); // } catch (GuzzleException $e) { // $this->processException($e); // } @@ -185,7 +193,7 @@ public function refreshToken(): Token 'Accept' => '*/*', 'Authorization' => 'Bearer'.' '.$this->configs['jwt'], 'Content-Type' => 'text/plain', - 'User-Agent' => 'SPINEN/'.$this->getVersion(), + 'User-Agent' => 'SPINEN/' . trim((string) $this->getVersion()), 'X-ACCESS-EXPIRY-OVERRIDE' => $this->configs['override']['access'].'s', 'X-REFRESH-EXPIRY-OVERRIDE' => $this->configs['override']['refresh'].'s', ], @@ -221,12 +229,11 @@ public function requestToken(): Token options: [ 'debug' => $this->debug, 'headers' => [ - 'Accept' => '*/*', 'Authorization' => 'Bearer'.' '.$this->configs['jwt'], - 'Content-Type' => 'text/plain', - 'User-Agent' => 'SPINEN/'.$this->getVersion(), + 'Content-Type' => 'text/plain', + 'User-Agent' => 'SPINEN/' . trim((string) $this->getVersion()), 'X-ACCESS-EXPIRY-OVERRIDE' => $this->configs['override']['access'].'s', - 'X-REFRESH-EXPIRY-OVERRIDE' => $this->configs['override']['refresh'].'s', + 'X-REFRESH-EXPIRY-OVERRIDE' => $this->configs['override']['refresh'].'s' ], ], uri: $this->uri('auth/authenticate'),