Skip to content

Commit 9062751

Browse files
committed
api: improve url build to better handle query parameters
1 parent 842480a commit 9062751

File tree

3 files changed

+16
-9
lines changed

3 files changed

+16
-9
lines changed

composer.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
],
1414
"require": {
1515
"php": ">=8.1",
16+
"nyholm/append-query-string": "^1.0",
1617
"php-http/cache-plugin": "^2.0",
1718
"php-http/client-common": "^2.7",
1819
"php-http/discovery": "^1.20",

src/Api.php

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,8 @@ public function request(
6666
$headers = array_merge($this->headerDefaults, $headers);
6767
}
6868

69-
$uri = $this->buildUri($path, $query);
70-
$request = $this->createRequest($method, $uri, $headers, $body);
69+
$url = $this->buildUrl($path, $query);
70+
$request = $this->createRequest($method, $url, $headers, $body);
7171

7272
// pre request listener
7373
$request = $this->eventDispatcher->dispatch(new PreRequestEvent($request))->getRequest();
@@ -276,25 +276,26 @@ public function buildPath(string $path, array $parameters): string
276276
return $path;
277277
}
278278

279-
private function buildUri(string $path, array $query = []): string
279+
private function buildUrl(string $path, array $query = []): string
280280
{
281-
$uri = StringHelper::reduceDuplicateSlashes($this->baseUrl . $path);
281+
$appendQuery = http_build_query($query);
282282

283-
if (!empty($query)) {
284-
$uri = sprintf('%s?%s', $uri, http_build_query($query));
283+
if (StringHelper::isUrl($path)) {
284+
return append_query_string($path, $appendQuery, APPEND_QUERY_STRING_REPLACE_DUPLICATE);
285285
}
286286

287-
return $uri;
287+
$url = StringHelper::reduceDuplicateSlashes($this->baseUrl . $path);
288+
return append_query_string($url, $appendQuery, APPEND_QUERY_STRING_REPLACE_DUPLICATE);
288289
}
289290

290291
private function createRequest(
291292
string $method,
292-
string $uri,
293+
string $url,
293294
array $headers = [],
294295
string|StreamInterface $body = null
295296
): RequestInterface
296297
{
297-
$request = $this->clientBuilder->getRequestFactory()->createRequest($method, $uri);
298+
$request = $this->clientBuilder->getRequestFactory()->createRequest($method, $url);
298299

299300
foreach ($headers as $key => $value) {
300301
$request = $request->withHeader($key, $value);

src/Helper/StringHelper.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,9 @@ public static function reduceDuplicateSlashes(string $string): string
88
{
99
return preg_replace('#(^|[^:])//+#', '\\1/', $string);
1010
}
11+
12+
public static function isUrl(string $string): bool
13+
{
14+
return filter_var($string, FILTER_VALIDATE_URL) !== false;
15+
}
1116
}

0 commit comments

Comments
 (0)