Skip to content

Commit

Permalink
Added ability to set auth headers
Browse files Browse the repository at this point in the history
  • Loading branch information
lonnylot committed Dec 9, 2019
1 parent fd3a257 commit 15bf9ab
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 6 deletions.
27 changes: 21 additions & 6 deletions src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ class Client {

protected $validator = null;

protected $authHeaders = null;

public function setValidatorFactory(Factory $validator) {
$this->validator = $validator;
}
Expand Down Expand Up @@ -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']
Expand All @@ -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';
}
Expand Down
26 changes: 26 additions & 0 deletions tests/Unit/ClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

0 comments on commit 15bf9ab

Please sign in to comment.