guzzle / psr7

PSR-7 HTTP message library
MIT License
7.88k stars 3 forks source link

Suggestion: withQueryValues #196

Closed dnyg closed 6 years ago

dnyg commented 6 years ago

Adding default query string(s) changed in Guzzle 6 and now requires adding middleware like

$handler->unshift(Middleware::mapRequest(function (RequestInterface $request) {
    return $request->withUri(Uri::withQueryValue($request->getUri(), 'key', 'secretKey'));
}));

When you need multiple default query strings you either have to do nested calls to ->withUri() (which becomes unmanageable at already 2 parameters), or create a loop/recursive function to generate an Uri to pass into withUri(). Something like

Nested

$handler->unshift(Middleware::mapRequest(function (RequestInterface $request) {
    return $request->withUri(Uri::withQueryValue(Uri::withQueryValue($request->getUri(), 'key1', 'value1'), 'key2', 'value2'));
}));

Loop

$handler->unshift(Middleware::mapRequest(function (RequestInterface $request) {
    $uri = $request->getUri();

    $defaults = [
        'key1' => 'value1',
        'key2' => 'value2'
    ];

    foreach ($defaults as $key => $value) {
        $uri = Uri::withQueryValue($uri, $key, $value);
    }

    return $request->withUri($uri);
}));

Feature Request: withQueryValues()

It would be nice if the GuzzleHttp\Psr7\Uri class had a withQueryValues(UriInterface $uri, $valueArray) function, so you could do something like

return $request->withUri(Uri::withQueryValues($request->getUri(), [
    'key1' => 'value1',
    'key2' => 'value2'
]);
dnyg commented 6 years ago

Any news about this? Am I free to submit a pull request?

Tobion commented 6 years ago

Adding default query string(s) changed in Guzzle 6

What exactly changed? How did you solve this before?

dnyg commented 6 years ago

In versions prior to Guzzle 6 you could do

$client = new \GuzzleHttp\Client([
    'base_uri' => 'https://example.com',
    'query' => [
        'key1' => 'value1',
        'key2' => 'value2'
    ]
]);

This is no longer supported (see https://github.com/guzzle/guzzle/issues/1138)

Tobion commented 6 years ago

I agree withQueryValues makes it simpler. I'd gladly see a PR.

timothymarois commented 5 years ago

In versions prior to Guzzle 6 you could do

$client = new \GuzzleHttp\Client([
    'base_uri' => 'https://example.com',
    'query' => [
        'key1' => 'value1',
        'key2' => 'value2'
    ]
]);

This is no longer supported (see guzzle/guzzle#1138)

Since this is no longer supported, it seems unclear how to accomplish default query params. Not sure why it had to be more complicated than adding default options.