Package · cast

Requests and responses

A request is built with a chain of calls and sent with send(). The response is a PSR-7 object with short methods for the usual reads.

Methods

php
$client->get('users', ['page' => 2]);      // the second argument is the query
$client->post('users');
$client->put('users/42');
$client->patch('users/42');
$client->delete('users/42');
$client->head('files/7');
$client->options('users');
$client->request(Method::PATCH, 'users/42');   // the Method enum from winter-base
$client->request('PURGE', 'cache/x');         // or any method as a string

Without a client, use the static methods CastRequest::get($url, $query) and so on, or the facade: Cast::get($url, $query).

Query

php
$client->get('search', ['q' => 'winter', 'tags' => ['php', 'http']])
  ->withQuery(['page' => 2])        // add or replace several
  ->withQueryParam('limit', 50);    // one

Parameters already in the address (search?sort=name) are kept as they are; only keys with the same names are replaced.

Headers

A request has the same set as the client: withHeader(), withHeaders() (adds), withAddedHeader(), withoutHeader(), withBearerToken(), withBasicAuth(), withAccept(), withUserAgent(). In addition, replaceHeaders([...]) replaces all headers at once.

A line break or NUL in a header name or value is refused (InvalidArgumentException): user input cannot inject a header of its own.

Body

Method What it sends
withJsonBody($data, $flags = 0) JSON, Content-Type: application/json
withFormBody([...]) application/x-www-form-urlencoded
withMultipartBody(Multipart|array) multipart/form-data — see Files
withStringBody($body, $contentType = null) a string as it is
withFileBody($path, $contentType = null) a file from disk, streamed
withBody(StreamInterface) any PSR-7 stream

Data that cannot be encoded as JSON (NAN, invalid UTF-8) gives an InvalidArgumentException right away, not an empty body on the server.

A body up to 1 MiB is sent from memory; a larger one, or one of unknown size, is streamed without being loaded whole.

Settings for one send

Each one replaces the client’s setting for this request only:

php
$client->get('report')
  ->withTimeout(120)                     // total; the client's connect and deadline stay
  ->withoutRetry()
  ->withMaxResponseSize(null)
  ->withThrowOnError()
  ->send();

The full list: withTimeout(), withTimeouts(), withRetry(), withoutRetry(), withRedirects(), withMaxResponseSize(), withThrowOnError(), withCurlOptions(), sinkTo(), onProgress().

Sending

Method Through what
$request->send() the client that created the request, or the facade’s client
$client->send($request) this client; accepts any PSR-7 request
$request->sendVia($psr18Client) any PSR-18 client

The response

php
$response = $client->get('users/42')->send();

$response->getStatusCode();     // 200
$response->status();            // HttpCode::OK — the winter-base enum
$response->isSuccess();         // 2xx; also isRedirect(), isClientError(), isServerError()

$response->header('ETag');      // as one line; null if there is no such header
$response->getHeader('Set-Cookie');   // PSR-7: a list of values

$response->body();              // the whole body as a string
$response->json();              // an array; null if empty, not JSON, or a JSON scalar
$response->jsonOrFail();        // an array or a CastException
$response->throw();             // an exception on 4xx/5xx, otherwise the response itself — for chains

json() deliberately never throws: a 204 or an HTML error page gives null. If you expect an object, use jsonOrFail().

Compressed responses

Cast asks for compression itself (Accept-Encoding) and decodes the response. After decoding, Content-Encoding and Content-Length would describe the bytes on the wire, not the body you get, so they are moved to X-Encoded-Content-Encoding and X-Encoded-Content-Length.

Transfer details

php
$info = $response->info();

$info->totalTime;        // seconds, the whole last attempt
$info->connectTime;
$info->startTransferTime;
$info->attempts;         // how many attempts there were
$info->redirects;        // how many redirects were followed
$info->effectiveUri;     // the final address after redirects
$info->primaryIp;
$info->protocol;         // "1.1" or "2"
$info->downloadedBytes;
$info->uploadedBytes;

$response->getRequest() is the request of the last attempt, exactly as it was sent.