Responses

The following are all methods you can use to set up your HTTP response.

statusCode

It sets the status code.

$builder
    ->when()
        ...
    ->then()
        ->statusCode(500);

headers

It sets the headers.

$builder
    ->when()
        ...
    ->then()
        ->headers([
            'Content-Type' => 'application/json'
        ]);

body

body(body: string): self

It sets the body.

$builder
    ->when()
        ...
    ->then()
        ->body('hello world');

When you set the body, it overwrites any other writing on the body. So, for instance, if you had used before the setJson the new body will be defined by the string you specify in the body method.

Since v1.1.0 the body method accepts a string as well as a callback.

body(body: mixed): self

You can also specify a callback to handle the body response. This is a suitable way to create dynamic responses. The function argument defines a callback using the PSR request interface. For instance, you can add an ID to the body and return the results as Json.

$builder
    ->when()
        ...
    ->then()
        ->body(function (RequestInterface $request) { 
            $stream = $request->getBody();
            $stream->rewind();

            $json = json_decode($stream->getContents(), true);
            $json['id'] = 'bb40819b-a06e-47cf-a22e-a9832e2f1e5d';

            return $json;
        });

Of course, for the above example is more suitable to use the setJson method. We've used this example to show you how flexible can be the body method.

Keep in mind if you're using the Guzzle client, the implementation for RequestInterface will be GuzzleHttp\Psr7\Request. You have to rewind the results to get the contents with this implementation.

$stream->rewind();

json

It sets the json response.

$builder
    ->when()
        ...
    ->then()
        ->json(['foo' => 'bar']);