From f7cfae98ea25e62620486c62f2177924ece0d8a8 Mon Sep 17 00:00:00 2001 From: Jerome Thayananthajothy Date: Sat, 19 Oct 2024 03:32:49 +0100 Subject: [PATCH] Add isAsync method --- docs/api/client-handler.md | 16 +++++++++++-- src/Fetch/Http/ClientHandler.php | 32 ++++++++++++++++---------- src/Fetch/Http/Response.php | 8 +++---- src/Fetch/Http/fetch.php | 4 ++-- src/Fetch/Interfaces/ClientHandler.php | 2 +- tests/Integration/HttpTest.php | 8 +++---- tests/Unit/ClientHandlerTest.php | 23 ++++++++++++++---- tests/Unit/FetchTest.php | 12 +++++----- 8 files changed, 70 insertions(+), 35 deletions(-) diff --git a/docs/api/client-handler.md b/docs/api/client-handler.md index 80fd68b..d545d2d 100644 --- a/docs/api/client-handler.md +++ b/docs/api/client-handler.md @@ -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. diff --git a/src/Fetch/Http/ClientHandler.php b/src/Fetch/Http/ClientHandler.php index 6ef8b66..35b20dd 100644 --- a/src/Fetch/Http/ClientHandler.php +++ b/src/Fetch/Http/ClientHandler.php @@ -4,16 +4,16 @@ 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 @@ protected function getFullUri(): string } // Concatenate base URI and URI ensuring no double slashes - return rtrim($baseUri, '/') . '/' . ltrim($uri, '/'); + return rtrim($baseUri, '/').'/'.ltrim($uri, '/'); } /** @@ -258,7 +258,7 @@ public function baseUri(string $baseUri): self */ public function withToken(string $token): self { - $this->options['headers']['Authorization'] = 'Bearer ' . $token; + $this->options['headers']['Authorization'] = 'Bearer '.$token; return $this; } @@ -328,11 +328,11 @@ public function retry(int $retries, int $delay = 100): self } /** - * 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 @@ public function options(string $uri): mixed { return $this->finalizeRequest('OPTIONS', $uri); } + + /** + * Indicate that the request is asynchronous. + */ + public function isAsync(): bool + { + return $this->isAsync; + } } diff --git a/src/Fetch/Http/Response.php b/src/Fetch/Http/Response.php index 1161aff..7187311 100644 --- a/src/Fetch/Http/Response.php +++ b/src/Fetch/Http/Response.php @@ -4,10 +4,10 @@ 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 @@ public function __construct( 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 @@ public function json(bool $assoc = true, bool $throwOnError = true) } 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. diff --git a/src/Fetch/Http/fetch.php b/src/Fetch/Http/fetch.php index e6791ba..783c874 100644 --- a/src/Fetch/Http/fetch.php +++ b/src/Fetch/Http/fetch.php @@ -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 @@ function fetch(?string $url = null, ?array $options = []): Response|ClientHandle // 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']); } diff --git a/src/Fetch/Interfaces/ClientHandler.php b/src/Fetch/Interfaces/ClientHandler.php index 0f8a498..97b5d46 100644 --- a/src/Fetch/Interfaces/ClientHandler.php +++ b/src/Fetch/Interfaces/ClientHandler.php @@ -4,8 +4,8 @@ namespace Fetch\Interfaces; -use Psr\Http\Client\ClientInterface; use GuzzleHttp\Cookie\CookieJarInterface; +use Psr\Http\Client\ClientInterface; interface ClientHandler { diff --git a/tests/Integration/HttpTest.php b/tests/Integration/HttpTest.php index b6f2a93..5aaf077 100644 --- a/tests/Integration/HttpTest.php +++ b/tests/Integration/HttpTest.php @@ -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 diff --git a/tests/Unit/ClientHandlerTest.php b/tests/Unit/ClientHandlerTest.php index 781c40c..1c2e451 100644 --- a/tests/Unit/ClientHandlerTest.php +++ b/tests/Unit/ClientHandlerTest.php @@ -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 @@ 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); +}); diff --git a/tests/Unit/FetchTest.php b/tests/Unit/FetchTest.php index 0221c7a..9d4de91 100644 --- a/tests/Unit/FetchTest.php +++ b/tests/Unit/FetchTest.php @@ -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 @@ $response = fetch('http://localhost', [ 'headers' => ['Authorization' => 'Bearer token'], - 'client' => $mockClient, + 'client' => $mockClient, ]); expect($response->text())->toBe('Headers checked'); @@ -105,7 +105,7 @@ }); $response = fetch('http://localhost', [ - 'query' => ['foo' => 'bar', 'baz' => 'qux'], + 'query' => ['foo' => 'bar', 'baz' => 'qux'], 'client' => $mockClient, ]); @@ -167,7 +167,7 @@ $response = fetch('http://localhost/users', [ 'method' => 'POST', - 'body' => json_encode(['name' => 'John']), + 'body' => json_encode(['name' => 'John']), 'client' => $mockClient, ]);