Class Response
Implements methods for HTTP responses.
All the following examples assume that $response is an
instance of this class.
Get header values
Header names are case-insensitive, but normalized to Title-Case when the response is parsed.
$val = $response->getHeaderLine('content-type');
Will read the Content-Type header. You can get all set headers using:
$response->getHeaders();
Get the response body
You can access the response body stream using:
$content = $response->getBody();
You can get the body string using:
$content = $response->getStringBody();
If your response body is in XML or JSON you can use special content type specific accessors to read the decoded data. JSON data will be returned as arrays, while XML data will be returned as SimpleXML nodes:
// Get as XML
$content = $response->getXml()
// Get as JSON
$content = $response->getJson()
If the response cannot be decoded, null will be returned.
Check the status code
You can access the response status code using:
$content = $response->getStatusCode();
Constants
-
stringMETHOD_DELETE ¶'DELETE'HTTP DELETE method
-
stringMETHOD_GET ¶'GET'HTTP GET method
-
stringMETHOD_HEAD ¶'HEAD'HTTP HEAD method
-
stringMETHOD_OPTIONS ¶'OPTIONS'HTTP OPTIONS method
-
stringMETHOD_PATCH ¶'PATCH'HTTP PATCH method
-
stringMETHOD_POST ¶'POST'HTTP POST method
-
stringMETHOD_PUT ¶'PUT'HTTP PUT method
-
stringMETHOD_TRACE ¶'TRACE'HTTP TRACE method
-
intSTATUS_ACCEPTED ¶202HTTP 202 code
-
intSTATUS_CREATED ¶201HTTP 201 code
-
intSTATUS_FOUND ¶302HTTP 302 code
-
intSTATUS_MOVED_PERMANENTLY ¶301HTTP 301 code
-
intSTATUS_NON_AUTHORITATIVE_INFORMATION ¶203HTTP 203 code
-
intSTATUS_NO_CONTENT ¶204HTTP 204 code
-
intSTATUS_OK ¶200HTTP 200 code
-
intSTATUS_PERMANENT_REDIRECT ¶308HTTP 308 code
-
intSTATUS_SEE_OTHER ¶303HTTP 303 code
-
intSTATUS_TEMPORARY_REDIRECT ¶307HTTP 307 code
Property Summary
-
$code protected
intThe status code of the response.
-
$cookies protected
Cake\Http\Cookie\CookieCollection|nullCookie Collection instance
-
$headerNames protected
array<non-empty-string, non-empty-string>Map of lowercased header name to the original name used to register the header.
-
$headers protected
array<non-empty-string, non-empty-list<string>>List of all registered headers, as original name => list of values.
-
$json protected
mixedCached decoded JSON data.
-
$jsonDecoded protected
boolWhether the response JSON has been decoded, including null and empty arrays.
-
$jsonError protected
JsonException|nullCached JSON decoding error for strict access after permissive access.
-
$protocol protected
stringThe HTTP protocol version.
-
$reasonPhrase protected
stringThe reason phrase for the status code
-
$stream protected
Psr\Http\Message\StreamInterfaceThe message body.
-
$xml protected
SimpleXMLElement|nullCached decoded XML data.
Method Summary
-
__construct() public
Constructor
-
assertHeaderName() protected
Validate a header name.
-
assertStatus() protected
Validate status line components before they reach an emitter.
-
buildCookieCollection() protected
Lazily build the CookieCollection and cookie objects from the response header
-
decodeGzipBody() protected
Uncompress a gzip response.
Validates the complete gzip container, including optional headers and the checksum.
-
filterHeaderValue() protected
Validate and normalize header values.
-
getBody() public
Gets the body of the message.
-
getCookie() public
Get the value of a single cookie.
-
getCookieCollection() public
Get the cookie collection from this response.
This method exposes the response's CookieCollection instance allowing you to interact with cookie objects directly.
-
getCookieData() public
Get the full data for a single cookie.
-
getCookies() public
Get the all cookie data.
-
getEncoding() public
Get the encoding if it was set.
-
getHeader() public
Retrieves a message header value by the given case-insensitive name.
-
getHeaderLine() public
Retrieves a comma-separated string of the values for a single header.
-
getHeaders() public
Retrieves all message headers.
-
getJson() public
Get the response body as JSON decoded data.
-
getJsonArray() public
Get the response body as a JSON decoded array.
JSON objects and arrays are returned as arrays. JSON null is returned as null.
-
getJsonAs() public
Decode JSON into an application type using a validating decoder.
-
getProtocolVersion() public
Retrieves the HTTP protocol version as a string.
-
getReasonPhrase() public
Gets the response reason phrase associated with the status code.
Because a reason phrase is not a required element in a response status line, the reason phrase value MAY be null. Implementations MAY choose to return the default RFC 7231 recommended reason phrase (or those listed in the IANA HTTP Status Code Registry) for the response's status code.
-
getStatusCode() public
Gets the response status code.
The status code is a 3-digit integer result code of the server's attempt to understand and satisfy the request.
-
getStringBody() public
Get the response body as string.
Non-seekable bodies are consumed from their current position. For live responses this waits until EOF and should not be used by monitoring.
-
getXml() public
Get the response body as XML decoded data.
-
hasHeader() public
Checks if a header exists by the given case-insensitive name.
-
isOk() public
Check if the response status code was in the 2xx/3xx range
-
isRedirect() public
Check if the response had a redirect status code.
-
isSuccess() public
Check if the response status code was in the 2xx range
-
parseHeaders() protected
Parses headers if necessary.
- Decodes the status code and reason phrase.
- Parses and normalizes header names and values.
-
removeHeader() protected
Remove a header from the current instance.
-
replaceHeader() protected
Replace a header on the current instance.
-
withAddedHeader() public
Return an instance with the specified header appended with the given value.
-
withBody() public
Replace the body and discard decoded values from the previous body.
-
withHeader() public
Return an instance with the provided header, replacing any existing values of any headers with the same case-insensitive name.
-
withProtocolVersion() public
Return an instance with the specified HTTP protocol version.
-
withStatus() public
Return an instance with the specified status code and, optionally, reason phrase.
If no reason phrase is specified, implementations MAY choose to default to the RFC 7231 or IANA recommended reason phrase for the response's status code.
This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the updated status and reason phrase.
-
withoutHeader() public
Return an instance without the specified header.
Method Detail
__construct() ¶ public
__construct(list<string> $headers = [], Psr\Http\Message\StreamInterface|string $body = '')
Constructor
Parameters
-
list<string>$headers optional Unparsed headers.
-
Psr\Http\Message\StreamInterface|string$body optional The response body. Stream bodies are used as-is.
assertHeaderName() ¶ protected
assertHeaderName(string $name): void
Validate a header name.
Parameters
-
string$name The header name.
Returns
voidThrows
InvalidArgumentExceptionWhen the name isn't a valid RFC 7230 token.
assertStatus() ¶ protected
assertStatus(int $code, string $reasonPhrase): void
Validate status line components before they reach an emitter.
Parameters
-
int$code HTTP status code.
-
string$reasonPhrase Optional reason phrase.
Returns
voidbuildCookieCollection() ¶ protected
buildCookieCollection(): Cake\Http\Cookie\CookieCollection
Lazily build the CookieCollection and cookie objects from the response header
Returns
Cake\Http\Cookie\CookieCollectiondecodeGzipBody() ¶ protected
decodeGzipBody(string $body): string
Uncompress a gzip response.
Validates the complete gzip container, including optional headers and the checksum.
Parameters
-
string$body Gzip encoded body.
Returns
stringThrows
Cake\Core\Exception\CakeExceptionWhen attempting to decode gzip content without gzdecode.
filterHeaderValue() ¶ protected
filterHeaderValue(mixed $values): non-empty-list<string>
Validate and normalize header values.
Parameters
-
mixed$values A header value or list of header values.
Returns
non-empty-list<string>Throws
InvalidArgumentExceptionWhen a value is invalid.
getBody() ¶ public
getBody(): Psr\Http\Message\StreamInterface
Gets the body of the message.
Returns
Psr\Http\Message\StreamInterfacegetCookie() ¶ public
getCookie(string $name): array|string|null
Get the value of a single cookie.
Parameters
-
string$name The name of the cookie value.
Returns
array|string|nullEither the cookie's value or null when the cookie is undefined.
getCookieCollection() ¶ public
getCookieCollection(): Cake\Http\Cookie\CookieCollection
Get the cookie collection from this response.
This method exposes the response's CookieCollection instance allowing you to interact with cookie objects directly.
Returns
Cake\Http\Cookie\CookieCollectiongetCookieData() ¶ public
getCookieData(string $name): array|null
Get the full data for a single cookie.
Parameters
-
string$name The name of the cookie value.
Returns
array|nullEither the cookie's data or null when the cookie is undefined.
getEncoding() ¶ public
getEncoding(): string|null
Get the encoding if it was set.
Returns
string|nullgetHeader() ¶ public
getHeader(string $name): list<string>
Retrieves a message header value by the given case-insensitive name.
Parameters
-
string$name Case-insensitive header name.
Returns
list<string>The header values, or an empty array if the header is not set.
getHeaderLine() ¶ public
getHeaderLine(string $name): string
Retrieves a comma-separated string of the values for a single header.
Parameters
-
string$name Case-insensitive header name.
Returns
stringThe header values joined by a comma, or an empty string if the header is not set.
getHeaders() ¶ public
getHeaders(): array<non-empty-string, non-empty-list<string>>
Retrieves all message headers.
Returns
array<non-empty-string, non-empty-list<string>>Header names mapped to their list of values.
getJson() ¶ public
getJson(): mixed
Get the response body as JSON decoded data.
Returns
mixedDecoded JSON, or null when the body is not valid JSON.
getJsonArray() ¶ public
getJsonArray(): array|null
Get the response body as a JSON decoded array.
JSON objects and arrays are returned as arrays. JSON null is returned as null.
Returns
array|nullThrows
JsonExceptionWhen the body is not valid JSON.
UnexpectedValueExceptionWhen the JSON value is neither an array nor null.
getJsonAs() ¶ public
getJsonAs(callable((array|null)): T $decoder): T
Decode JSON into an application type using a validating decoder.
Templates
T
Parameters
-
callable((array|null)): T$decoder Decoder responsible for validating the JSON value.
Returns
TThrows
JsonExceptionWhen the body is not valid JSON.
UnexpectedValueExceptionWhen the JSON value is neither an array nor null.
getProtocolVersion() ¶ public
getProtocolVersion(): string
Retrieves the HTTP protocol version as a string.
Returns
stringHTTP protocol version.
getReasonPhrase() ¶ public
getReasonPhrase(): string
Gets the response reason phrase associated with the status code.
Because a reason phrase is not a required element in a response status line, the reason phrase value MAY be null. Implementations MAY choose to return the default RFC 7231 recommended reason phrase (or those listed in the IANA HTTP Status Code Registry) for the response's status code.
Returns
stringThe current reason phrase.
getStatusCode() ¶ public
getStatusCode(): int
Gets the response status code.
The status code is a 3-digit integer result code of the server's attempt to understand and satisfy the request.
Returns
intThe status code.
getStringBody() ¶ public
getStringBody(): string
Get the response body as string.
Non-seekable bodies are consumed from their current position. For live responses this waits until EOF and should not be used by monitoring.
Returns
stringgetXml() ¶ public
getXml(): SimpleXMLElement|null
Get the response body as XML decoded data.
Returns
SimpleXMLElement|nullhasHeader() ¶ public
hasHeader(string $name): bool
Checks if a header exists by the given case-insensitive name.
Parameters
-
string$name Case-insensitive header name.
Returns
boolisOk() ¶ public
isOk(): bool
Check if the response status code was in the 2xx/3xx range
Returns
boolisRedirect() ¶ public
isRedirect(): bool
Check if the response had a redirect status code.
Returns
boolisSuccess() ¶ public
isSuccess(): bool
Check if the response status code was in the 2xx range
Returns
boolparseHeaders() ¶ protected
parseHeaders(list<string> $headers): void
Parses headers if necessary.
- Decodes the status code and reason phrase.
- Parses and normalizes header names and values.
Parameters
-
list<string>$headers Headers to parse.
Returns
voidremoveHeader() ¶ protected
removeHeader(string $name): void
Remove a header from the current instance.
Parameters
-
string$name Case-insensitive header name.
Returns
voidreplaceHeader() ¶ protected
replaceHeader(non-empty-string $name, non-empty-list<string> $value): void
Replace a header on the current instance.
Parameters
-
non-empty-string$name The header name.
-
non-empty-list<string>$value The filtered header values.
Returns
voidwithAddedHeader() ¶ public
withAddedHeader(string $name, string|string[] $value): static
Return an instance with the specified header appended with the given value.
Parameters
-
string$name Case-insensitive header name.
-
string|string[]$value Header value(s).
Returns
staticThrows
InvalidArgumentExceptionFor invalid header names or values.
withBody() ¶ public
withBody(StreamInterface $body): static
Replace the body and discard decoded values from the previous body.
Parameters
-
StreamInterface$body The new body.
Returns
staticwithHeader() ¶ public
withHeader(string $name, string|string[] $value): static
Return an instance with the provided header, replacing any existing values of any headers with the same case-insensitive name.
Parameters
-
string$name Case-insensitive header name.
-
string|string[]$value Header value(s).
Returns
staticThrows
InvalidArgumentExceptionFor invalid header names or values.
withProtocolVersion() ¶ public
withProtocolVersion(string $version): static
Return an instance with the specified HTTP protocol version.
Parameters
-
string$version HTTP protocol version.
Returns
staticThrows
InvalidArgumentExceptionFor unsupported protocol versions.
withStatus() ¶ public
withStatus(int $code, string $reasonPhrase = ''): static
Return an instance with the specified status code and, optionally, reason phrase.
If no reason phrase is specified, implementations MAY choose to default to the RFC 7231 or IANA recommended reason phrase for the response's status code.
This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the updated status and reason phrase.
Parameters
-
int$code The status code to set.
-
string$reasonPhrase optional The status reason phrase.
Returns
staticA copy of the current object with an updated status code.
withoutHeader() ¶ public
withoutHeader(string $name): static
Return an instance without the specified header.
Parameters
-
string$name Case-insensitive header name.
Returns
staticProperty Detail
$headerNames ¶ protected
Map of lowercased header name to the original name used to register the header.
Type
array<non-empty-string, non-empty-string>$headers ¶ protected
List of all registered headers, as original name => list of values.
Type
array<non-empty-string, non-empty-list<string>>$jsonDecoded ¶ protected
Whether the response JSON has been decoded, including null and empty arrays.
Type
bool$jsonError ¶ protected
Cached JSON decoding error for strict access after permissive access.
Type
JsonException|null