Skip to content

Commit

Permalink
Merge pull request #9 from car-api-team/feature/http2-and-encoding
Browse files Browse the repository at this point in the history
Add http2 and encoding
  • Loading branch information
carapidev authored Oct 9, 2024
2 parents c3b48d7 + babc87a commit b7f0ee0
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 8 deletions.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,20 @@ $sdk = \CarApiSdk\CarApi::build([

You have now created an instance of the SDK.

### Other Options

You may also set `httpVersion` and `encoding`. The HTTP version defaults to 1.1 and we recommend keeping at that level.
Encoding is off by default, but GZIP is supported. Example:

```php
$sdk = \CarApiSdk\CarApi::build([
'token' => getenv('CARAPI_TOKEN'),
'secret' => getenv('CARAPI_SECRET'),
'httpVersion' => '2.0', // we recommend keeping the default 1.1
'encoding' => ['gzip'],
]);
```

### Authentication

The authenticate method will both return a JWT and store the JWT in the SDK internally. There is no persistent
Expand Down
31 changes: 28 additions & 3 deletions src/CarApi.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,14 +57,21 @@ public function authenticate(): string
{
try {
$json = json_encode(AuthDto::build($this->config), JSON_THROW_ON_ERROR);
if ($json === false) {
throw new \JsonException('JSON Payload is false');
}
} catch (\JsonException $e) {
throw new CarApiException('Unable to build JSON payload', 500, $e);
}

$stream = $this->streamFactory->createStream($json);

$request = $this->client->createRequest('POST', sprintf('%s/auth/login', $this->host))
->withProtocolVersion($this->config->httpVersion)
->withHeader('accept', 'text/plain')
->withHeader('Content-Type', 'application/json')
->withBody($this->streamFactory->createStream($json));
->withHeader('content-type', 'application/json')
->withHeader('content-length', (string) $stream->getSize())
->withBody($stream);

$response = $this->sendRequest($request);
$body = (string) $response->getBody();
Expand All @@ -78,6 +85,13 @@ public function authenticate(): string
);
}

if (in_array('gzip', $this->config->encoding) && \extension_loaded('zlib')) {
$body = gzdecode($body);
if ($body === false) {
throw new CarApiException('Unable to decompress response. Maybe try without gzip.');
}
}

$pieces = explode('.', $body);
if (count($pieces) !== 3) {
throw new CarApiException('Invalid JWT');
Expand Down Expand Up @@ -369,6 +383,13 @@ private function getDecoded(string $url, array $options = [], ?bool $associative
$response = $this->get($url, $options);
$body = (string) $response->getBody();

if (in_array('gzip', $this->config->encoding) && \extension_loaded('zlib')) {
$body = gzdecode($body);
if ($body === false) {
throw new CarApiException('Unable to decompress response. Maybe try without gzip.');
}
}

try {
$decoded = json_decode($body, $associative, 512, JSON_THROW_ON_ERROR);
if ($response->getStatusCode() !== 200) {
Expand Down Expand Up @@ -430,8 +451,12 @@ function ($param) {
*/
private function sendRequest(RequestInterface $request): ResponseInterface
{
if (in_array('gzip', $this->config->encoding) && \extension_loaded('zlib')) {
$request = $request->withHeader('accept-encoding', 'gzip');
}

try {
return $this->client->sendRequest($request);
return $this->client->sendRequest($request->withProtocolVersion($this->config->httpVersion));
} catch (ClientExceptionInterface $e) {
throw new CarApiException($e->getMessage(), $e->getCode(), $e);
}
Expand Down
26 changes: 21 additions & 5 deletions src/CarApiConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,32 @@ class CarApiConfig
public string $token;
public string $secret;
public ?string $host;
public string $httpVersion;
public array $encoding;

/**
* Constructor
*
* @param string $token Your token
* @param string $secret Your secret
* @param string|null $host Defaults to carapi.app and should be left null
* @param string $token Your token
* @param string $secret Your secret
* @param string|null $host Defaults to carapi.app and should be left null
* @param string $httpVersion Defaults to HTTP 1.1
* @param array $encoding Sets the accepts-encoding request header, default: []. To enable decoding
* set this option to ['gzip'] and ensure you have the gzip extension
* loaded.
*/
public function __construct(string $token, string $secret, ?string $host = null)
{
public function __construct(
string $token,
string $secret,
?string $host = null,
string $httpVersion = '1.1',
array $encoding = []
) {
$this->token = $token;
$this->secret = $secret;
$this->host = $host;
$this->httpVersion = $httpVersion;
$this->encoding = $encoding;
}

/**
Expand All @@ -29,6 +42,7 @@ public function __construct(string $token, string $secret, ?string $host = null)
* @param array $configs See constructor for required keys.
*
* @return self
* @throws CarApiException
*/
public static function build(array $configs): self
{
Expand All @@ -40,6 +54,8 @@ public static function build(array $configs): self
$configs['token'],
$configs['secret'],
$configs['host'] ?? null,
$configs['httpVersion'] ?? '1.1',
$configs['encoding'] ?? [],
);
}
}

0 comments on commit b7f0ee0

Please sign in to comment.