Skip to main content

Responses

Create a response​

use Dirthara\Http\Response;
use Dirthara\Http\StatusCode;
use Dirthara\Http\Factory\StreamFactory;

$response = new Response(
StatusCode::Ok,
new StreamFactory()->createStream('<h1>Hello</h1>'),
['Content-Type' => 'text/html; charset=utf-8'],
);
ParameterTypeDefaultMeaning
statusCodeint|StatusCodeThe status code.
bodyStreamInterfaceThe response body.
headersarray<string, string|string[]>[]Headers by name.
protocolVersionstring'1.1'The HTTP protocol version.
reasonPhrasestring''The reason phrase. Empty means the registered phrase for the code.

The response factory creates a response with an empty body.

Status code and reason phrase​

getStatusCode() returns the code as an int, and getReasonPhrase() returns the reason phrase. withStatus($code, $reasonPhrase = '') changes both, and accepts a StatusCode case or an int.

use Dirthara\Http\StatusCode;

$notFound = $response->withStatus(StatusCode::NotFound);
$custom = $response->withStatus(StatusCode::NotFound, 'No Such User');
$unregistered = $response->withStatus(299);

The reason phrases are 'Not Found', 'No Such User', and ''.

Reason phrase givenResult
None, or ''The registered phrase for the code, or '' for a code that is not registered.
Any other stringThat string.

Because an empty phrase always resolves to the registered one, changing only the code also replaces a custom phrase: withStatus(404) after a custom 'No Such User' gives 'Not Found'.

Validation​

InputRuleException
Status codeFrom 100 to 599. A StatusCode case is always valid.InvalidResponseException::invalidStatusCode()
Reason phraseNo control characters other than a horizontal tab, so no line breaks.InvalidResponseException::invalidReasonPhrase()

A code does not have to be registered: 299 is accepted and gets an empty reason phrase.