Methods41
Set the Accept header, replacing any previous one set via this method (addHeaders would add a duplicate instead).
function accept(string $accept): selfMerge $opts into the existing options (through merge), rather than replacing them wholesale like setOptions.
function addOptions(array $opts, bool $appendList = false): void| $opts | array | the options to merge in |
| $appendList = false | bool | if true, a list-valued option is appended to (rather than replaced by) the corresponding list in $opts -- see \MMO\core\arrays\merge for the exact semantics |
| returns | void | |
$t->setOptions(['a' => 1, 'tags' => ['x']]);
$t->addOptions(['b' => 2, 'tags' => ['y']]);
$t->getOptions(); // ['a' => 1, 'tags' => ['y'], 'b' => 2] -- 'tags' is replaced, not appended ($appendList=false)
Action must be taken immediately.
function alert(Stringable|string $message, array $context = []): voidExample: Entire website down, database unavailable, etc. This should
trigger the SMS alerts and wake you up.$this->alert('payment gateway unreachable for 5 minutes.');
Force-log a message at INFO level together with a full stack trace/memory snapshot (iLogLevel::BACKTRACE), bypassing the verbosity mask entirely (any non-zero verbosity is enough to trigger it).
function backtraces(string $message = ' -- TRACES -- ', array $context = []): void$this->backtraces('unexpected state reached in {method}.', ['method' => __METHOD__]);
Empty the options bag.
function clearOptions(): void$t->clearOptions(); // getOptions() === []
Release the current curl handle, if any (exec calls this itself once done).
function close(): voidCritical conditions. No-op if CRITICAL is currently filtered out by the verbosity mask.
function critical(Stringable|string $message, array $context = []): voidExample : Application component unavailable, unexpected exception.$this->critical('unexpected {exception}.', ['exception' => $e]);
Detailed debug information. No-op if DEBUG is currently filtered out by the verbosity mask.
function debug(Stringable|string $message, array $context = []): void$this->debug('set stream [{stream}].', ['stream' => $stream]);
Human-readable identifier used as the default {origin} in this instance's log messages.
function debugName(): stringOverride this in a class using the trait to show something more specific than the bare classname.Convert a raw curl_setopt-ready options array (CURLOPT_* constant => value) into a human-readable one ('CURLOPT_*' name => value, per OPTIONS_TEXT), additionally decoding CURLOPT_HTTPHEADER, CURLOPT_COOKIE, and CURLOPT_POSTFIELDS into associative arrays where possible.
static function DebugOptions(array $opts): array| $opts | array | NOTE: a CURLOPT_* constant not listed in OPTIONS_TEXT silently produces a ''-keyed entry (PHP raises an "Undefined array key" warning, not an error, and the lookup evaluates to null -> '' as an array key) rather than being reported or skipped. |
| returns | array | |
Curl::DebugOptions([CURLOPT_HTTPHEADER => ['X-Foo: bar']]); // ['CURLOPT_HTTPHEADER' => ['X-Foo' => 'bar']]
System is unusable. No-op if EMERGENCY is currently filtered out by the verbosity mask.
function emergency(Stringable|string $message, array $context = []): void$this->emergency('database connection lost.');
Runtime errors that do not require immediate action but should typically be logged and monitored.
function error(Stringable|string $message, array $context = []): voidNo-op if ERROR is currently filtered out by the verbosity mask.$this->error('failed to write [{file}].', ['file' => $filename]);
Execute a CURL request and return the response
function exec(string $url, array|string|null $post = null, array $opts = []): MMO\core\server\StreamResponseNOTE: If post is an array, add `Content-Type` header so the post parameters can be encoded the right way
NOTE: if no content type is defined, post data are encoded as `application/x-www-form-urlencoded`- See
setHeaders/setCookies/... and tWithOptions's generic option setters.
| $url | string | |
| $post = null | array | string | null | if non-null, sends a POST with this as the body (a string is sent as-is; an array is form-encoded per the NOTEs above). |
| $opts = [] | array | curl options, merged over (and taking priority over) the options already set via |
| returns | StreamResponse | the LAST response received (getResponses for the full chain when redirects were followed). |
| throws | | if called while a previous exec on this instance hasn't finished (close), or the request itself fails. |
$opts = [\CURLOPT_HTTPHEADER => ['Content-Type: application/json']]
Execute a curl request as HEAD (no body for response) -- the response's body ends up containing the raw header text instead (curl's CURLOPT_HEADER effect), since no actual body is fetched (CURLOPT_NOBODY).
function execHead(string $url, $post = null, array $opts = []): MMO\core\server\StreamResponseAutomatically follows up to 10 redirects.Same as exec, but throws if the response's status isn't a 2xx (iResponse::isOk).
function execOrThrow(string $url, array|string|null $post = null, array $opts = []): MMO\core\server\StreamResponseParse a curl ... shell command (e.g. copy-pasted from a browser's "Copy as cURL") into options usable with exec. Only recognizes a subset of curl's flags (the switch cases below); anything else is collected into the 4th return value instead of being silently dropped.
static function FromString(string $curl, bool $debug = false): array| $curl | string | |
| $debug = false | bool | if true, run the parsed options through DebugOptions (human-readable names/values) instead of returning raw curl_setopt-ready ones. |
| returns | array | [url, data (currently always null -- POST data is folded into $opts[CURLOPT_POSTFIELDS] instead), options, ignored arguments] |
Curl::FromString("curl 'https://example.com' -H 'X-Foo: bar' --data-raw '{\"a\":1}'");
// ['https://example.com', null, [CURLOPT_HTTPHEADER => ['X-Foo: bar'], CURLOPT_POSTFIELDS => '{"a":1}'], []]
function getCookies()| returns | | name => value, every cookie set by the server during the current/last exec. |
function getFollowRedirection(): ?boolfunction getOption(string $key, mixed $default = null): mixed$t->getOption('a', 'fallback'); // the current value of 'a', or 'fallback' if not set
function getOptions(): array| returns | array | every option currently set |
$t->getOptions(); // ['a' => 1, 'tags' => ['x']]
function getResponse(): ?MMO\core\server\StreamResponsefunction getResponses(): array| returns | array | every response from the current/last exec, in order (more than one when redirects were followed). |
function getUserAgent(): ?string| returns | null | string | the User-Agent that will be sent, or null if unset (curl's own default applies). |
function getVerbosity(): int| returns | int | the current verbosity, as a bitmask of iLogLevel::* constants |
$this->getVerbosity() === (iLogLevel::ERROR_PLUS); // true if only errors/critical/alert/emergency are enabled
CURLOPT_HEADERFUNCTION callback (set by exec) -- curl calls this once per response header line, accumulating them into $headers, extracting cookies into $cookies, and (once the blank line ending the header block arrives) creating the StreamResponse for getResponse/getResponses -- called once per response actually received, so a redirect chain (setFollowRedirection) produces one StreamResponse per hop.
function handleCurlHeader($handle, $header): int| $handle | | the curl handle. |
| $header | | one raw header line, including its trailing "\r\n". |
| returns | int | must return strlen($header) -- curl aborts the transfer if this doesn't match. |
Interesting events. No-op if INFO is currently filtered out by the verbosity mask.
function info(Stringable|string $message, array $context = []): voidExample: User logs in, SQL logs.$this->info('routing [{request}] ...', ['request' => $request]);
Logs with an arbitrary level.
function log($level, Stringable|string $message, array $context = []): voidNOTE: $level is filtered against the current [`setVerbosity()`](https://mmoframework.fr/documentation/mmo.core/php/server/Curl.md#curl-setverbosity): if the level is masked out, nothing is
logged/dispatched at all. Return type is `void` (not the dispatched Log) to satisfy \Psr\Log\LoggerInterface.$this->log(self::ERROR, 'disk usage at {percent}%.', ['percent' => 92]);
$this->log('error', $caughtException); //string levels are resolved through \MMO\core\debug\flags()
Normal but significant events. No-op if NOTICE is currently filtered out by the verbosity mask.
function notice(Stringable|string $message, array $context = []): void$this->notice('-- START -- ({mode}): {time}', ['mode' => MMO_MODE, 'time' => date('r')]);
Set filenames for the cookies
function setCookies(string $readFrom, ?string $writeTo = null): selffunction setFollowRedirection(bool $follow): self| $follow | bool | also toggles auto-updating the Referer header across redirects (CURLOPT_AUTOREFERER). |
| returns | self | |
Set (or, with a null $value, remove) a single option.
function setOption(string $key, mixed $value): void| $key | string | |
| $value | mixed | if null, the option is unset entirely rather than being set to null |
| returns | void | |
$t->setOption('a', 1);$t->setOption('a', null); // removes 'a' from getOptions()
Replace the whole options bag.
function setOptions(array $opts): void$t->setOptions(['a' => 1]);
function setReferer(?string $referer): self| $referer | null | string | the Referer header to send (null removes it). |
| returns | self | |
function setUserAgent(?string $value): self| $value | null | string | null removes it (falling back to curl's own default). |
| returns | self | |
Set the current verbosity mask, replacing whatever it was before.
function setVerbosity(string|int|null $verb = null): void| $verb = null | string | int | null | a bitmask of iLogLevel::* constants, or a level name/expression resolved through \MMO\core\debug\flags() (e.g. 'error+' for iLogLevel::ERROR_PLUS) |
| returns | void | |
$this->setVerbosity(iLogLevel::WARNING_PLUS); // only log warnings and above
$this->setVerbosity('all'); // log everything
Test whether a given level (or set of levels) is currently enabled by this instance's verbosity mask.
function testVerbosity(string|int $level): int| $level | string | int | a iLogLevel::* constant/bitmask, or a level name resolved through \MMO\core\debug\flags() |
| returns | int | the bits of $level that are currently enabled (0 if none of them are) |
$this->testVerbosity(self::DEBUG); // non-zero if debug-level logging is currently enabled
$this->testVerbosity('error'); // same, using the string form
Exceptional occurrences that are not errors. No-op if WARNING is currently filtered out by the verbosity mask.
function warning(Stringable|string $message, array $context = []): voidExample: Use of deprecated APIs, poor use of an API, undesirable things
that are not necessarily wrong.$this->warning('{count} logs were dropped.', ['count' => 3]);
function __construct()