Skip to content

Commit

Permalink
Add isAsync method
Browse files Browse the repository at this point in the history
  • Loading branch information
Thavarshan committed Oct 19, 2024
1 parent 2515e76 commit f7cfae9
Show file tree
Hide file tree
Showing 8 changed files with 70 additions and 35 deletions.
16 changes: 14 additions & 2 deletions docs/api/client-handler.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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.
32 changes: 20 additions & 12 deletions src/Fetch/Http/ClientHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand All @@ -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,
];
Expand Down Expand Up @@ -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, '/');
}

/**
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
}
}
8 changes: 4 additions & 4 deletions src/Fetch/Http/Response.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand All @@ -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);

Expand All @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions src/Fetch/Http/fetch.php
Original file line number Diff line number Diff line change
Expand Up @@ -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')) {
Expand All @@ -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']);
}

Expand Down
2 changes: 1 addition & 1 deletion src/Fetch/Interfaces/ClientHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@

namespace Fetch\Interfaces;

use Psr\Http\Client\ClientInterface;
use GuzzleHttp\Cookie\CookieJarInterface;
use Psr\Http\Client\ClientInterface;

interface ClientHandler
{
Expand Down
8 changes: 4 additions & 4 deletions tests/Integration/HttpTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
23 changes: 19 additions & 4 deletions tests/Unit/ClientHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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);
});
12 changes: 6 additions & 6 deletions tests/Unit/FetchTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -85,7 +85,7 @@

$response = fetch('http://localhost', [
'headers' => ['Authorization' => 'Bearer token'],
'client' => $mockClient,
'client' => $mockClient,
]);

expect($response->text())->toBe('Headers checked');
Expand All @@ -105,7 +105,7 @@
});

$response = fetch('http://localhost', [
'query' => ['foo' => 'bar', 'baz' => 'qux'],
'query' => ['foo' => 'bar', 'baz' => 'qux'],
'client' => $mockClient,
]);

Expand Down Expand Up @@ -167,7 +167,7 @@

$response = fetch('http://localhost/users', [
'method' => 'POST',
'body' => json_encode(['name' => 'John']),
'body' => json_encode(['name' => 'John']),
'client' => $mockClient,
]);

Expand Down

0 comments on commit f7cfae9

Please sign in to comment.