Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the query parameters in a Guzzle/ Psr7 request

Tags:

guzzle

guzzle6

I am using Guzzle 6.

I am trying to mock a client and use it like so:

<?php

use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;

$mock_handler = new MockHandler([
    new Response(200, ['Content-Type' => 'application/json'], 'foo'),
]);

$history = [];
$history_middleware = Middleware::history($history);

$handler_stack = HandlerStack::create($mock_handler);
$handler_stack->push($history_middleware);

$mock_client = new Client(['handler' => $handler_stack]);

// Use mock client in some way
$mock_client->get("http://example.com", [
    'query' => [
        'bar' => '10',
        'hello' => '20'
    ],
]);
// ------

// get original request using history
$transaction = $history[0];
/** @var Request $request */
$request = $transaction['request'];

// How can I get the query parameters that was used in the request (i.e. bar)

My question is how can I get the query parameters used in the GuzzleHttp\Psr7\Request class?

The closest I managed to get is the following: $request->getUri()->getQuery(), but this just returns a string like so: bar=10&hello=20.

like image 465
Yahya Uddin Avatar asked Sep 28 '16 17:09

Yahya Uddin


1 Answers

I seem to have solved my problem.

I can simply do this:

parse_str($request->getUri()->getQuery(), $query);

and I now have an array of the query parameters.

Other solutions are welcome!

like image 171
Yahya Uddin Avatar answered Sep 17 '22 13:09

Yahya Uddin