diff --git a/src/Client.php b/src/Client.php index b46dd0c..b9df1bf 100644 --- a/src/Client.php +++ b/src/Client.php @@ -30,6 +30,8 @@ class Client { protected $validator = null; + protected $authHeaders = null; + public function setValidatorFactory(Factory $validator) { $this->validator = $validator; } @@ -117,16 +119,17 @@ public function request($method, $path, $data = null) { $clientOptions['handler'] = $this->handler; } + $headers = array_merge([ + 'Accept' => 'application/json', + 'Content-Type' => 'application/json', + 'User-Agent' => $this->getUserAgent(), + ], $this->getAuthHeaders()); + $guzzleClient = new GuzzleClient($clientOptions); try { $guzzleResponse = $guzzleClient->request($method, $uri, [ - 'headers' => [ - 'Authorization' => 'Bearer '.$this->getApiKey(), - 'Accept' => 'application/json', - 'Content-Type' => 'application/json', - 'User-Agent' => $this->getUserAgent(), - ], + 'headers' => $headers, 'timeout' => 10, 'body' => $data, 'on_stats' => [$this, 'recordStats'] @@ -138,6 +141,18 @@ public function request($method, $path, $data = null) { } } + public function getAuthHeaders() { + if (is_array($this->authHeaders)) { + return $this->authHeaders; + } + + return ['Authorization' => 'Bearer '.$this->getApiKey()]; + } + + public function setAuthHeaders(array $headers) { + $this->authHeaders = $headers; + } + public function getUserAgent(): string { return 'crud-sugar-sdk/1.0.0'; } diff --git a/tests/Unit/ClientTest.php b/tests/Unit/ClientTest.php index 1274f4d..11548c5 100644 --- a/tests/Unit/ClientTest.php +++ b/tests/Unit/ClientTest.php @@ -173,4 +173,30 @@ public function testUserAgent() { // Then $this->assertIsString($userAgent); } + + public function testGetDefaultAuthHeaders() { + // Given + $apiKey = uniqid(); + $this->getClient()->setApiKey($apiKey); + + // When + $authHeaders = $this->getClient()->getAuthHeaders(); + + // Then + $this->assertEquals(['Authorization' => 'Bearer '.$apiKey], $authHeaders); + } + + public function testSetAuthHeaders() { + // Given + $authHeaderKey = uniqid(); + $apiKey = uniqid(); + $this->getClient()->setApiKey($apiKey); + $this->getClient()->setAuthHeaders([$authHeaderKey => $apiKey]); + + // When + $authHeaders = $this->getClient()->getAuthHeaders(); + + // Then + $this->assertEquals([$authHeaderKey => $apiKey], $authHeaders); + } }