HttpClientResponse
Raxos\Http\Client\HttpClientResponse
Wraps a PSR-7 response returned by HttpClient with convenient accessors. It is immutable and implements Raxos\Contract\DebuggableInterface.
readonly class HttpClientResponse implements DebuggableInterfaceProperties
The wrapper parses three pieces of the response up front as public readonly properties: protocolVersion, responseCode (an HttpResponseCode) and responseText.
Methods
public function body(): stringReturns the raw response body.
public function json(bool $associative = true): array|stdClassParses the response body as JSON. Returns an array by default, or a stdClass when associative is false. Throws JsonException on invalid JSON.
public function stream(): StreamInterfaceReturns the response body as a PSR-7 stream.
public function header(string $name, bool $single = true): string|arrayReturns one response header. With single set to true it returns the combined header line; with false it returns every value as an array.
public function headers(bool $single = true): arrayReturns all response headers.
public function hasHeader(string $name): boolReturns true when the response contains the given header.
public function success(): boolReturns true for status codes 200 to 299.
public function failed(): boolReturns true for any status code outside 200 to 299.
public function clientError(): boolReturns true for status codes 400 to 499.
public function serverError(): boolReturns true for status codes 500 to 599.
Example
<?php
declare(strict_types=1);
use Raxos\Http\Client\HttpClient;
$client = new HttpClient(baseUrl: 'https://api.example.com');
$response = $client->get('/users');
if ($response->success()) {
$users = $response->json();
} elseif ($response->clientError()) {
// 4xx: bad request, unauthorized, not found, ...
} elseif ($response->serverError()) {
// 5xx: the upstream service failed
}