Skip to content

Commit

Permalink
feat: allow passing uri to RequestFactory (#191)
Browse files Browse the repository at this point in the history
  • Loading branch information
simPod authored Feb 24, 2023
1 parent 732435d commit bd0fb26
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
20 changes: 19 additions & 1 deletion src/Client/Http/RequestFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Message\UriFactoryInterface;
use Psr\Http\Message\UriInterface;

use function http_build_query;
use function is_string;

use const PHP_QUERY_RFC3986;

Expand All @@ -17,6 +20,8 @@ final class RequestFactory
public function __construct(
private RequestFactoryInterface $requestFactory,
private StreamFactoryInterface $streamFactory,
private UriFactoryInterface|null $uriFactory = null,
private UriInterface|string $uri = '',
) {
}

Expand All @@ -29,7 +34,20 @@ public function prepareRequest(RequestOptions $requestOptions): RequestInterface
PHP_QUERY_RFC3986,
);

return $this->requestFactory->createRequest('POST', $query === '' ? '' : '?' . $query)
if ($this->uriFactory === null) {
return $this->requestFactory->createRequest('POST', $query === '' ? '' : '?' . $query)
->withBody($this->streamFactory->createStream($requestOptions->sql));
}

$uri = $this->uri;
if (is_string($uri)) {
$uri = $this->uriFactory->createUri($uri);
}

$uriQuery = $uri->getQuery();
$uri = $uri->withQuery($uriQuery . ($uriQuery !== '' && $query !== '' ? '&' : '') . $query);

return $this->requestFactory->createRequest('POST', $uri)
->withBody($this->streamFactory->createStream($requestOptions->sql));
}
}
12 changes: 10 additions & 2 deletions tests/Client/Http/RequestFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,12 @@ final class RequestFactoryTest extends TestCaseBase
public function testPrepareRequest(): void
{
$psr17Factory = new Psr17Factory();
$requestFactory = new RequestFactory($psr17Factory, $psr17Factory);
$requestFactory = new RequestFactory(
$psr17Factory,
$psr17Factory,
$psr17Factory,
'http://localhost:8123?format=JSON',
);

$request = $requestFactory->prepareRequest(new RequestOptions(
'SELECT 1',
Expand All @@ -24,7 +29,10 @@ public function testPrepareRequest(): void
));

self::assertSame('POST', $request->getMethod());
self::assertSame('?database=database&max_block_size=1', $request->getUri()->__toString());
self::assertSame(
'http://localhost:8123?format=JSON&database=database&max_block_size=1',
$request->getUri()->__toString(),
);
self::assertSame('SELECT 1', $request->getBody()->__toString());
}
}

0 comments on commit bd0fb26

Please sign in to comment.