Package · cast
API reference
Every public class of the package. with*() methods return a copy: the object they are called
on does not change.
| Class |
Namespace |
Cast |
Flytachi\Winter\Cast |
CastClient, Timeouts, RetryPolicy, Redirects |
…\Cast\Client |
CastRequest, CastResponse, CastStream, CastUri, Multipart, TransferInfo, TransferProgress |
…\Cast\Message |
CastMiddleware, AuthMiddleware, HeadersMiddleware, RefreshTokenMiddleware |
…\Cast\Middleware |
Transport, CurlTransport, MockTransport |
…\Cast\Transport |
CastFactory |
…\Cast\Factory |
| exceptions |
…\Cast\Exception — see Exceptions |
CastClient
final class CastClient implements Psr\Http\Client\ClientInterface
Creating
| Method |
Description |
__construct() |
a client with the default settings |
static create(): self |
the same, for chaining |
Configuration
| Method |
Description |
withBaseUrl(string|UriInterface $url) |
base URL; must be an absolute http(s) URL, otherwise InvalidArgumentException |
withHeader(string $name, string|array $value) |
a default header |
withHeaders(array $headers) |
several; same-name headers are replaced, the others stay |
withAddedHeader(string $name, string|array $value) |
add a value |
withoutHeader(string $name) |
remove |
withBearerToken(string $token) |
Authorization: Bearer … |
withBasicAuth(string $user, string $password) |
Authorization: Basic … |
withAccept(string ...$types) |
Accept |
withUserAgent(string $agent, bool $exact = false) |
the application’s agent; exact — without the library’s suffix |
withTimeouts(Timeouts $timeouts) |
all timeouts |
withTimeout(float $total, ?float $connect = null) |
attempt and connect |
withRetry(RetryPolicy $policy) |
retries |
withRedirects(Redirects $redirects) |
redirects |
withConcurrency(int $limit) |
sendAll() concurrency; 16 by default |
withMaxResponseSize(?int $bytes) |
the in-memory body limit; 10 MiB by default, null — no limit |
withThrowOnError(bool $throw = true) |
send() throws HttpException on 4xx/5xx |
withMiddleware(CastMiddleware|callable ...$middleware) |
add to the end of the chain |
withoutMiddleware(string $class) |
remove by class (and subclasses) |
withCurlOptions(array $options) |
custom cURL options; reserved ones — InvalidArgumentException |
withLogger(?LoggerInterface $logger) |
a PSR-3 logger |
withTransport(Transport $transport) |
another transport |
Reading
getBaseUrl(): ?CastUri, getHeaders(): array, getTimeouts(): Timeouts,
getRetryPolicy(): RetryPolicy, getRedirects(): Redirects, getMiddleware(): array.
Requests bound to the client
| Method |
Returns |
get(string|UriInterface $uri, array $query = []) |
CastRequest |
post(), put(), patch(), delete(), head(), options() — the same arguments |
CastRequest |
request(Method|string $method, string|UriInterface $uri) |
CastRequest |
Sending
| Method |
Description |
send(RequestInterface $request): CastResponse |
send; with withThrowOnError() throws on 4xx/5xx |
sendRequest(RequestInterface $request): CastResponse |
PSR-18; never throws on a status |
sendAll(iterable $requests, ?int $concurrency = null): array |
concurrently; responses under the requests’ keys; BatchException if some got no response |
CastRequest
final class CastRequest implements Psr\Http\Message\RequestInterface
Creating
| Method |
Description |
__construct(string $method, string|UriInterface $uri, array $headers = [], $body = null, string $version = '1.1') |
the body is a string, a stream or a resource |
static get($uri, array $query = []), post, put, patch, delete, head, options |
without a client |
static from(RequestInterface $request): self |
any PSR-7 request as a CastRequest |
PSR-7: withHeader(), withAddedHeader(), withoutHeader(), getHeader(),
getHeaderLine(), hasHeader(), getHeaders(). In addition:
| Method |
Description |
withHeaders(array $headers) |
several; same-name headers are replaced |
replaceHeaders(array $headers) |
replace all (Host is taken from the address again) |
withBearerToken(string $token), withBasicAuth($user, $password), withAccept(...$types) |
shortcuts |
withUserAgent(string $agent, bool $exact = false) |
this request’s agent |
Address
| Method |
Description |
withQuery(array $params) |
add or replace parameters; the rest stay as they are |
withQueryParam(string $name, mixed $value) |
one parameter |
withUri(UriInterface $uri, bool $preserveHost = false) |
PSR-7 |
Body
| Method |
Description |
withJsonBody(mixed $data, int $flags = 0) |
JSON; InvalidArgumentException if it cannot be encoded |
withFormBody(array $fields) |
application/x-www-form-urlencoded |
withMultipartBody(Multipart|array $parts) |
multipart/form-data |
withStringBody(string $body, ?string $contentType = null) |
a string |
withFileBody(string $path, ?string $contentType = null) |
a file, streamed |
withBody(StreamInterface $body) |
a PSR-7 stream |
Send settings
| Method |
Description |
withTimeout(float $total, ?float $connect = null) |
changes only these two; the client’s other timeouts stay |
withTimeouts(Timeouts $timeouts) |
replaces all of the client’s timeouts |
withRetry(RetryPolicy $policy), withoutRetry() |
retries |
withRedirects(Redirects $redirects) |
redirects |
withMaxResponseSize(?int $bytes) |
body limit |
withThrowOnError(bool $throw = true) |
an exception on 4xx/5xx |
sinkTo(string|resource|StreamInterface $target) |
write a successful body to a file, resource or stream |
onProgress(callable $callback) |
fn(TransferProgress $p) |
withCurlOptions(array $options) |
this request’s cURL options |
Sending
| Method |
Description |
send(): CastResponse |
through the client that created the request, or the facade’s client |
sendVia(ClientInterface $client): ResponseInterface |
through any PSR-18 client |
CastResponse
final class CastResponse implements Psr\Http\Message\ResponseInterface
| Method |
Description |
__construct(int $status = 200, array $headers = [], $body = null, string $version = '1.1', ?string $reason = null) |
|
static fromJson(mixed $data, int $status = 200, array $headers = []) |
a JSON response — for tests |
static fromString(string $body, int $status = 200, array $headers = []) |
a response with a string |
status(): ?HttpCode |
the status as the winter-base enum |
isSuccess(), isRedirect(), isClientError(), isServerError() |
2xx, 3xx, 4xx, 5xx |
header(string $name): ?string |
as one line; null if absent |
body(): string |
the whole body |
json(): ?array |
a JSON object or array; otherwise null |
jsonOrFail(): array |
the same or a CastException |
throw(): static |
HttpException on 4xx/5xx, otherwise the response itself |
info(): TransferInfo |
transfer details |
getRequest(): ?CastRequest |
the request of the last attempt |
isSunk(): bool |
the body was written to the sinkTo() target |
Timeouts
final readonly class Timeouts — properties connect, total, idle,
idleMinBytesPerSecond, deadline (seconds; null — off).
| Method |
Description |
static of(?float $total = 30.0, float $connect = 5.0) |
attempt and connect |
static forDownload(float $idle = 60.0, int $minBytesPerSecond = 1024, float $connect = 5.0) |
no total, with stall protection |
withConnect(float $seconds) |
|
withTotal(?float $seconds) |
|
withIdle(?float $seconds, int $minBytesPerSecond = 1) |
|
withDeadline(?float $seconds) |
the whole operation, retries included |
A zero or negative value is an InvalidArgumentException.
RetryPolicy
final readonly class RetryPolicy
| Method |
Description |
static none() |
no retries (the default) |
static exponential(int $attempts = 3, int $delayMs = 500) |
×2 per attempt, ±30 %, at most 30 s |
static fixed(int $attempts, int $delayMs) |
the same pause every time |
withMethods(Method|string ...$methods) |
which methods to retry |
withNonIdempotent() |
add POST and PATCH |
withStatuses(int ...$statuses) |
which statuses to retry |
withMaxDelay(int $ms) |
the pause cap |
respectRetryAfter(bool $respect = true) |
honour Retry-After |
enabled(): bool |
more than one attempt |
attempts is the total number of attempts, the first one included.
Redirects
final readonly class Redirects — properties max, allowDowngrade.
| Method |
Description |
static follow(int $max = 10, bool $allowDowngrade = false) |
follow |
static none() |
do not follow |
enabled(): bool |
|
Multipart
final readonly class Multipart
| Method |
Description |
static create() |
an empty body |
static fromArray(array $fields) |
strings are fields, CURLFile / CURLStringFile are files |
withField(string $name, string $value) |
a field |
withFile(string $name, string $path, ?string $filename = null, ?string $contentType = null) |
a file from disk |
withContent(string $name, string $content, string $filename, ?string $contentType = null) |
a string as a file |
withStream(string $name, StreamInterface $stream, string $filename, ?string $contentType = null) |
a stream as a file |
contentType(): string |
multipart/form-data; boundary=… |
toStream(): CastStream |
the body per RFC 7578 — for other clients |
CastStream
final class CastStream implements Psr\Http\Message\StreamInterface
| Method |
Description |
static fromString(string $content = '') |
in memory |
static fromFile(string $path, string $mode = 'r') |
a file |
static fromResource($resource) |
an open resource |
static temp(int $memoryLimit = 2 MiB) |
in memory up to the limit, then in a temporary file |
getPath(): ?string |
the path, if the stream is over a file |
CastUri
final class CastUri implements Psr\Http\Message\UriInterface
| Method |
Description |
static parse(string|UriInterface $uri) |
parse; InvalidArgumentException on an invalid address |
isAbsolute(): bool |
has a scheme and a host |
resolve(string|UriInterface $relative): self |
append a path to this address — the base URL rule |
withQueryParams(array $params): self |
add or replace parameters |
redacted(): string |
the address without the query and user:password@ — for logs |
TransferInfo
final readonly class TransferInfo — $response->info().
| Property |
Description |
totalTime, connectTime, startTransferTime |
seconds, last attempt |
effectiveUri |
the final address |
redirects |
number of redirects followed |
attempts |
number of attempts |
primaryIp |
the server’s IP |
downloadedBytes, uploadedBytes |
bytes |
protocol |
1.1 or 2 |
TransferProgress
final readonly class TransferProgress — the argument of the onProgress() function.
| Member |
Description |
downloaded, uploaded |
bytes received and sent |
downloadTotal, uploadTotal |
the expected size; null until known |
downloadPercent(): ?float, uploadPercent(): ?float |
percentages; null without a size |
Middleware
phpinterface CastMiddleware
{
/** @param callable(CastRequest): CastResponse $next */
public function process(CastRequest $request, callable $next): CastResponse;
}
| Class |
Creating |
AuthMiddleware |
::bearer(string|callable $token), ::basic(string $user, string $password), ::header(string $name, string|callable $value) |
HeadersMiddleware |
new HeadersMiddleware(array|callable $headers) |
RefreshTokenMiddleware |
new RefreshTokenMiddleware(callable $refresh, int $maxRetries = 1) |
Details are in Middleware.
Cast
final class Cast — a facade over the default client.
| Method |
Description |
get($uri, array $query = []) … options() |
a CastRequest bound to the default client |
send(RequestInterface $request): CastResponse |
|
sendAll(iterable $requests, ?int $concurrency = null): array |
|
client(): CastClient |
the default client; created on first use |
setClient(?CastClient $client): void |
replace it; null — back to the defaults |
Transport
phpinterface Transport
{
public function execute(CastRequest $request, TransferOptions $options): CastResponse;
}
CurlTransport — the default. CurlTransport::RESERVED lists the reserved cURL options with
a hint to the method that sets each one.
MockTransport — for tests: __construct(CastResponse|Throwable|callable ...$responses),
static fail(string $message = 'Connection refused', int $curlErrno = 7), append(...),
requests(), lastRequest(), remaining(). See Testing.
CastFactory
final class CastFactory — all four PSR-17 factories: RequestFactoryInterface,
ResponseFactoryInterface, StreamFactoryInterface, UriFactoryInterface.
php$factory = new CastFactory();
$sdk = new SomeVendorSdk(httpClient: $client, requestFactory: $factory, streamFactory: $factory);