6

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.

Yahya Uddin
  • 26,997
  • 35
  • 140
  • 231

1 Answers1

8

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!

Yahya Uddin
  • 26,997
  • 35
  • 140
  • 231
  • 5
    `$params = $request->getQueryParams();` and then you can get a single value like this: `$my_param = $params['my_param'] ?? 'default';` – Rafael Beckel Mar 18 '18 at 15:51