Methods76
Merge $data into the current response's content -- in place if it's our own Response class (whose document can be mutated directly), or via a new immutable iResponse::withParsedBody instance otherwise (setResponse).
function addContent(ArrayAccess|array $data): voidfunction addMiddleware(callable $middleware, array $parameters = [], int $order = 0): self| $middleware | callable | function(Route $route): iResponse|array|\ArrayAccess|null -- an array/\ArrayAccess return is merged into the current response's content (addContent); an iResponse replaces it (setResponse); null/no return continues to the next middleware. |
| $parameters = [] | array | merged into the request's attributes (aRequest::withAttributes) right before this middleware runs. |
| $order = 0 | int | execution order -- LOWER runs first, HIGHER runs later; middlewares with the same $order run in the order they were added. |
| returns | self | |
$route->addMiddleware(fn (Route $r) => ['ok' => true], [], 0);
function addMiddlewareParameters(callable $middleware, array $params): selfAction 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__]);
What a query returns tells the values it filters or sorts on, so a request cannot use a hidden property (ArrayProperty::isHidden) that way: ?filters[passhash][$regex]=/^.2y/ would find a password's hash out one character at a time. Nor MongoDB's $where, $expr and $jsonSchema, which can read any property. (Named in ?fields=, a hidden property is simply left out: tArrayProperties::toArray)
function checkQueryPath(MMO\core\entities\Query $query, string $path): string| $query | Query | |
| $path | string | a path the request filters or sorts on (owner/passhash, or owner.passhash) |
| returns | string | $path |
| throws | | (400 Bad Request) if the request cannot use it |
$route->checkQueryPath($users->query(), 'passhash'); // throws: `@hidden`
Remove every registered middleware.
function clearMiddlewares(): selfRemove every registered middleware whose parameters don't have 'anonymous' => true set.
function clearNonAnonymousMiddleware(): voidfunction count(): int- See
Countable -- @return int the number of registered middlewares.
createAcceptResponse($document, $status, $reason, $headers)
Route.php:560Build a Response in whichever of html/json/plain-text format the client's Accept header prefers (negotiateMimeType), via Response::FromMime.
function createAcceptResponse(
MMO\core\documents\Document|array|null $document = null,
int $status = 200,
string $reason = '',
array $headers = []
): MMO\core\server\ResponseNOTE: per [`Response::FromMime`](https://mmoframework.fr/documentation/mmo.core/php/server/Response.md#response-frommime), $document must be null or an already-built Document if negotiation
resolves to 'text/html' -- there's no array-to-markup mapping, so a plain array $document throws eInvalid
whenever the client accepts html.Critical 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.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]);
static function FilterPaths(MMO\core\interfaces\iFilter $filter): Generator| $filter | iFilter | |
| returns | Generator | every path $filter reads: those of its conditions (in its groups too), and those they compare with ({#path}) |
iterator_to_array(Route::FilterPaths(Filter::From('(name = {#nickname}) | (age > 18)')), false); // ['name', 'nickname', 'age']
function get(string $key, mixed $default = null, int $where = -1): mixed| $key | string | |
| $default = null | mixed | returned if $key is found nowhere in $where. |
| $where = -1 | int | a IN_QUERY/IN_BODY/... bitmask of where to look, checked in this fixed order: attributes, query, body, headers, cookies, files (the first match wins). |
| returns | mixed | |
$route->get('page', 1, Route::IN_QUERY);
function getAttribute(string $key, mixed $default = null)| $key | string | |
| $default = null | mixed | |
| returns | | the request attribute $key, or $default if unset. |
function getAttributes(): array| returns | array | every request attribute. |
Retrieve HTTP Basic Auth credentials with the Authorization header of a request, or the parameters in the body. First index of the returned array is the username, second is the password (so list() will work). If the header does not exist, or is otherwise an invalid HTTP Basic header, and the body does not have the client_id/client_secret, return [null, null].
function getBasicAuthCredentials(bool $allowInBody = true): arrayfunction getCharset(): string| returns | string | the response's charset if one is set; otherwise the request's 'charset' attribute (setFormat), falling back to content negotiation (negotiateCharset) against ['utf-8', 'ISO-8859-1']. |
function getClassMiddleware(object $obj): arrayfunction getContentType(): ?string| returns | null | string | the response's Content-Type (media type only, no charset/params), or null if no response is set yet. |
function getController(): ?MMO\core\interfaces\iModulefunction getCurrentMiddleware(): ?callablefunction getErrorHandler(): ?callablefunction getExtension(): ?string| returns | null | string | the request URI's file extension (e.g. 'json' for '/api/users.json'). |
function getFormat(): string| returns | string | the response's format (file extension, e.g. 'json') if one is set; otherwise the request's 'format' attribute (setFormat), falling back to the URI's own extension, falling back to 'txt' for a ShellRequest or 'html' otherwise. |
function getMiddlewareParameters(callable $middleware): ?array| $middleware | callable | |
| returns | null | array | the middleware's current parameters, or null if $middleware isn't registered. |
function getMiddlewarePriority(callable $middleware): ?intfunction getMiddlewares(): array| returns | array | [middleware, parameters, order][], in the order they will actually run (addMiddleware's $order). |
function getRequest(): Psr\Http\Message\ServerRequestInterface| returns | ServerRequestInterface | the current request. |
function getRequestBody(): object|array|null| returns | object | array | null | the request's parsed body (ServerRequestInterface::getParsedBody). |
function getResponse(): ?MMO\core\interfaces\iResponseGet response's parsed body
function getResponseBody(): object|array| returns | object | array | |
| throws | | if no response has been set yet. |
function getUri(bool $unlock = false): Psr\Http\Message\UriInterface| $unlock = false | bool | forwarded to the request's own getUri(). |
| returns | UriInterface | the request's URI. |
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
function handle(?Psr\Http\Message\ServerRequestInterface $request = null): MMO\core\interfaces\iResponse- See
RequestHandlerInterface::handle Run every registered middleware in order (nextMiddleware/addMiddleware's $order), applying each one's parameters as request attributes before calling it, and folding its return value into the response (an array/\ArrayAccess is merged in via addContent, an iResponse replaces it via setResponse, and null/no return just continues) -- until none are left, or one of them calls stop.
| $request = null | null | ServerRequestInterface | if given, replaces the current request (setRequest) before running. |
| returns | iResponse | |
| throws | | if a middleware returns something other than an array/\ArrayAccess/iResponse/null. |
| throws | | if no middleware ever set a response. |
function has($key, int $where = -1): bool| $key | | |
| $where = -1 | int | a IN_QUERY/IN_BODY/... bitmask of where to look. |
| returns | bool | whether $key was found anywhere in $where. NOTE: internally builds a bitmask of every location $key was actually found in, but the declared bool return type coerces it down to a plain true/false (PHP's weak typing coerces any non-zero int to true) -- so which specific location(s) matched is computed but never actually observable by the caller. |
function hasAttribute(string $key): bool| $key | string | |
| returns | bool | whether the request attribute $key is set (and not null). |
function hasController(): boolfunction hasResponse(): boolInteresting 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]);
function isDelete(): bool| returns | bool | whether the current request's method is DELETE. |
function isGet(): bool| returns | bool | whether the current request's method is GET. |
function isHead(): bool| returns | bool | whether the current request's method is HEAD. |
function isPost(): bool| returns | bool | whether the current request's method is POST. |
function isPropagationStopped(): boolfunction isPut(): bool| returns | bool | whether the current request's method is PUT. |
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/Route.md#route-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()
Negotiates charset with the user's browser through the Accept-Charset HTTP header.
function negotiateCharset(array $supported, ?string $default = null): stringQuality factors in the Accept-Charset: header are supported, e.g.:
Accept-Language: en-UK;q=0.7, en-US;q=0.6, no, dk;q=0.8| $supported | array | a list of supported charset |
| $default = null | null | string | The default charset to use if none is found. |
| returns | string | The negotiated charset result or the supplied default. |
Negotiates language with the user's browser through the Accept-Language HTTP header or the user's host address. Language codes are generally in the form "ll" for a language spoken in only one country, or "ll-CC" for a language spoken in a particular country. For example, U.S. English is "en-US", while British English is "en-UK". Portugese as spoken in Portugal is "pt-PT", while Brazilian Portugese is "pt-BR".
function negotiateLanguage(array $supported, ?string $default = null): stringQuality factors in the Accept-Language: header are supported, e.g.:
Accept-Language: en-UK;q=0.7, en-US;q=0.6, no, dk;q=0.8| $supported | array | a list of supported languages |
| $default = null | null | string | The default language to use if none is found. |
| returns | string | The negotiated language result or the supplied default. |
Negotiates content type with the user's browser through the Accept HTTP header.
function negotiateMimeType(array $supported, ?string $default = null): stringQuality factors in the Accept: header are supported, e.g.:
Accept: application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8| $supported | array | a list of supported MIME types. |
| $default = null | null | string | The default type to use if no match. |
| returns | string | The negotiated MIME type result or the supplied default. |
function nextMiddleware(): ?array| returns | null | array | [middleware, parameters, order] for the next middleware to run (handle), or null once none are left. |
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')]);
redirect($redirectUri, $headers, $post, $status, $reason)
Route.php:575Stop the route with a redirect response (Response::Redirect).
function redirect(
string $redirectUri,
?array $headers = null,
?array $post = null,
int $status = 302,
string $reason = ''
): MMO\core\interfaces\iResponse| $redirectUri | string | |
| $headers = null | null | array | defaults to the current response's headers (if any), or [] otherwise. |
| $post = null | null | array | if not null, submits a form instead of using a Location header (Response::Redirect). |
| $status = 302 | int | |
| $reason = '' | string | |
| returns | iResponse | the redirect response (also set as this route's response and returned by handle). |
Remove every registered middleware bound to $obj -- i.e. every middleware added as an array-style callable [$obj, 'method']; a middleware added as a Closure or a plain function name is never matched (and matching one throws, since $obj can't be indexed) -- only use this on routes whose middlewares are all object methods.
function removeClassMiddleware(object $obj): selffunction removeMiddleware(callable $middleware): selffunction setAttribute(string $key, mixed $value): self| $key | string | |
| $value | mixed | a request attribute to set, or (if null) remove. |
| returns | self | |
function setController(MMO\core\interfaces\iModule $controller): static| $controller | iModule | stored as the 'controller' request attribute. |
| returns | static | |
Add an handler for errors
function setErrorHandler(?callable $handler): void| $handler | null | callable | function(\Throwable $exception, Route $route): iResponse |
| returns | void | |
Set the request's 'format'/'charset' attributes (getFormat/getCharset), and, if a response is already set, update its Content-Type header to match (makeContentTypeHeader).
function setFormat(string $format, string $charset = 'utf-8'): selffunction setMiddlewareOrder(callable $middleware, int $order): selffunction setMiddlewareParameters(callable $middleware, array $params): selffunction setRequest(Psr\Http\Message\ServerRequestInterface $request): self| $request | ServerRequestInterface | replaces the current request. |
| returns | self | |
function setResponse(?MMO\core\interfaces\iResponse $response): self| $response | null | iResponse | replaces the current response (null clears it). No-op if it's already the current response. |
| 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
Sort $middlewares in the reversed order nextMiddleware's array_pop expects (addMiddleware's $order: lower runs first).
protected function sortMiddlewares(): voidStop processing further middlewares (clearMiddlewares), optionally setting the final response first.
function stop(?MMO\core\interfaces\iResponse $response = null): ?MMO\core\interfaces\iResponse| $response = null | null | iResponse | if given, becomes the response (setResponse) before stopping. |
| returns | null | iResponse | the response after this call (whatever was set so far, possibly still null). |
Prevent any remaining listener in the current dispatch chain from being called.
function stopPropagation()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 withAttributes(array $attrs): self| $attrs | array | merged into the request's existing attributes. |
| returns | self | |
A cloned event starts fresh: propagation is never considered stopped on the clone, even if it was on the original instance.
function __clone()