Add isAsync method

This commit is contained in:
Jerome Thayananthajothy 2024-10-19 03:32:49 +01:00
parent 2515e76f8d
commit f7cfae98ea
8 changed files with 70 additions and 35 deletions

View File

@ -158,10 +158,12 @@ Configures retry logic for failed requests.
### **`async()`**
```php
public function async(): self
public function async(?bool $async = true): self
```
Marks the request as asynchronous.
Enables asynchronous requests.
- **`$async`**: `true` to enable asynchronous requests.
**Returns**: The `ClientHandler` instance for chaining.
@ -298,3 +300,13 @@ Sends an `OPTIONS` request.
- **`$uri`**: The URI for the request.
**Returns**: The response for synchronous requests, or `AsyncHelper` for async requests.
### **`isAsync()`**
```php
public function isAsync(): bool
```
Checks if the request is asynchronous.
**Returns**: `true` if the request is asynchronous, `false` otherwise.

View File

@ -4,16 +4,16 @@ declare(strict_types=1);
namespace Fetch\Http;
use RuntimeException;
use Matrix\AsyncHelper;
use InvalidArgumentException;
use Fetch\Interfaces\ClientHandler as ClientHandlerInterface;
use Fetch\Interfaces\Response as ResponseInterface;
use GuzzleHttp\Client as SyncClient;
use Psr\Http\Client\ClientInterface;
use GuzzleHttp\Cookie\CookieJarInterface;
use GuzzleHttp\Exception\RequestException;
use Fetch\Interfaces\Response as ResponseInterface;
use InvalidArgumentException;
use Matrix\AsyncHelper;
use Matrix\Interfaces\AsyncHelper as AsyncHelperInterface;
use Fetch\Interfaces\ClientHandler as ClientHandlerInterface;
use Psr\Http\Client\ClientInterface;
use RuntimeException;
class ClientHandler implements ClientHandlerInterface
{
@ -36,7 +36,7 @@ class ClientHandler implements ClientHandlerInterface
* Default options for the request.
*/
protected static array $defaultOptions = [
'method' => 'GET',
'method' => 'GET',
'headers' => [],
'timeout' => self::DEFAULT_TIMEOUT,
];
@ -196,7 +196,7 @@ class ClientHandler implements ClientHandlerInterface
}
// Concatenate base URI and URI ensuring no double slashes
return rtrim($baseUri, '/') . '/' . ltrim($uri, '/');
return rtrim($baseUri, '/').'/'.ltrim($uri, '/');
}
/**
@ -258,7 +258,7 @@ class ClientHandler implements ClientHandlerInterface
*/
public function withToken(string $token): self
{
$this->options['headers']['Authorization'] = 'Bearer ' . $token;
$this->options['headers']['Authorization'] = 'Bearer '.$token;
return $this;
}
@ -328,11 +328,11 @@ class ClientHandler implements ClientHandlerInterface
}
/**
* Set the request to be asynchronous.
* Set the request to be asynchronous or not.
*/
public function async(): self
public function async(?bool $async = true): self
{
$this->isAsync = true;
$this->isAsync = $async;
return $this;
}
@ -444,4 +444,12 @@ class ClientHandler implements ClientHandlerInterface
{
return $this->finalizeRequest('OPTIONS', $uri);
}
/**
* Indicate that the request is asynchronous.
*/
public function isAsync(): bool
{
return $this->isAsync;
}
}

View File

@ -4,10 +4,10 @@ declare(strict_types=1);
namespace Fetch\Http;
use RuntimeException;
use GuzzleHttp\Psr7\Response as BaseResponse;
use Fetch\Interfaces\Response as ResponseInterface;
use GuzzleHttp\Psr7\Response as BaseResponse;
use Psr\Http\Message\ResponseInterface as PsrResponseInterface;
use RuntimeException;
class Response extends BaseResponse implements ResponseInterface
{
@ -24,7 +24,7 @@ class Response extends BaseResponse implements ResponseInterface
array $headers = [],
string $body = '',
string $version = '1.1',
string $reason = null
?string $reason = null
) {
parent::__construct($status, $headers, $body, $version, $reason);
@ -48,7 +48,7 @@ class Response extends BaseResponse implements ResponseInterface
}
if ($throwOnError) {
throw new RuntimeException('Failed to decode JSON: ' . json_last_error_msg());
throw new RuntimeException('Failed to decode JSON: '.json_last_error_msg());
}
return null; // or return an empty array/object depending on your needs.

View File

@ -2,8 +2,8 @@
declare(strict_types=1);
use Fetch\Http\Response;
use Fetch\Http\ClientHandler;
use Fetch\Http\Response;
use GuzzleHttp\Exception\RequestException;
if (! function_exists('fetch')) {
@ -29,7 +29,7 @@ if (! function_exists('fetch')) {
// Handle baseUri if provided
if (isset($options['base_uri'])) {
$url = rtrim($options['base_uri'], '/') . '/' . ltrim($url, '/');
$url = rtrim($options['base_uri'], '/').'/'.ltrim($url, '/');
unset($options['base_uri']);
}

View File

@ -4,8 +4,8 @@ declare(strict_types=1);
namespace Fetch\Interfaces;
use Psr\Http\Client\ClientInterface;
use GuzzleHttp\Cookie\CookieJarInterface;
use Psr\Http\Client\ClientInterface;
interface ClientHandler
{

View File

@ -2,12 +2,12 @@
declare(strict_types=1);
use GuzzleHttp\Client;
use Fetch\Http\Response;
use Mockery\MockInterface;
use GuzzleHttp\Psr7\Request;
use Fetch\Http\ClientHandler;
use Fetch\Http\Response;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Request;
use Mockery\MockInterface;
beforeEach(function () {
\Mockery::close(); // Reset Mockery before each test

View File

@ -2,12 +2,12 @@
declare(strict_types=1);
use GuzzleHttp\Client;
use Fetch\Http\Response;
use Mockery\MockInterface;
use GuzzleHttp\Psr7\Request;
use Fetch\Http\ClientHandler;
use Fetch\Http\Response;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Request;
use Mockery\MockInterface;
beforeEach(function () {
\Mockery::close(); // Reset Mockery before each test
@ -235,3 +235,18 @@ test('retries an asynchronous request on failure', function () {
throw $e; // Fail the test if an exception is caught
});
});
test('checks if the request is asynchronous', function () {
$clientHandler = new ClientHandler;
// Initially, the request should not be asynchronous
expect($clientHandler->isAsync())->toBe(false);
// Simulate setting the request to asynchronous
$clientHandler->async();
expect($clientHandler->isAsync())->toBe(true);
// Simulate setting the request back to synchronous
$clientHandler->async(false);
expect($clientHandler->isAsync())->toBe(false);
});

View File

@ -2,11 +2,11 @@
declare(strict_types=1);
use GuzzleHttp\Client;
use Fetch\Http\Response;
use Mockery\MockInterface;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Request;
use Mockery\MockInterface;
beforeEach(function () {
\Mockery::close(); // Reset Mockery before each test
@ -85,7 +85,7 @@ test('fetch sends headers with a GET request', function () {
$response = fetch('http://localhost', [
'headers' => ['Authorization' => 'Bearer token'],
'client' => $mockClient,
'client' => $mockClient,
]);
expect($response->text())->toBe('Headers checked');
@ -105,7 +105,7 @@ test('fetch appends query parameters to the GET request', function () {
});
$response = fetch('http://localhost', [
'query' => ['foo' => 'bar', 'baz' => 'qux'],
'query' => ['foo' => 'bar', 'baz' => 'qux'],
'client' => $mockClient,
]);
@ -167,7 +167,7 @@ test('fetch makes a POST request with body data', function () {
$response = fetch('http://localhost/users', [
'method' => 'POST',
'body' => json_encode(['name' => 'John']),
'body' => json_encode(['name' => 'John']),
'client' => $mockClient,
]);