Skip to content

Typed input DTOs with attributes - #240

Open
tomaj wants to merge 1 commit into
masterfrom
feat/197-typed-input
Open

tomaj wants to merge 1 commit into
masterfrom
feat/197-typed-input

Conversation

@tomaj

@tomaj tomaj commented Nov 5, 2026 •

Copy link
Copy Markdown
Owner

Refs #197

Adds typed input DTOs as a second, equal way to declare handler input next to params(). TypedHandler reads a readonly DTO from handleDto(SomeInput $input) and turns its properties into InputParam objects, so validation, OpenAPI and the API console keep using the existing pipeline. BaseHandler::params() / handle(array $params) are unchanged.

final readonly class UserDetailInput
{
    public function __construct(
        #[Path] #[Range(min: 1)] public int $id,
        #[Header('X-Request-Id')] public ?string $requestId = null,
    ) {}
}

#[Get(1, 'users', '{id}/detail')]
final class UserDetailHandler extends TypedHandler
{
    public function handleDto(UserDetailInput $input): ResponseInterface { /* ... */ }
}

What's in it

  • Sources: #[Query], #[Path], #[Header], #[Body], #[File] on readonly promoted properties. Nullable or defaulted means optional.
  • Path templates: endpoint actions may contain {name} segments ({id}/detail). Static endpoints still win; templates are matched by the new ApiDecider::matchPath(), getApi() keeps its 3.x signature. ApiLink::link() fills {name} from the params of the same name.
  • New params usable from params() too: PathInputParam, HeaderInputParam, BodyInputParam (OpenAPI in: path / in: header).
  • Strict conversion for int, float, bool, backed enums, DateTimeImmutable (RFC 3339), list<T> and nested DTOs. JSON, form (bracket notation) and multipart bodies; errors carry paths like items[1].quantity, at most 100 per request.
  • Constraints Range, Length, Pattern, Email + ConstraintInterface; casters #[Cast] with DateFormat, UnixTimestamp, Split + CasterInterface.
  • FileUpload value object for #[File].
  • #[Consumes] restricts body media types; anything else is 415, answered after authorization and rate limiting.
  • DI extension compiles DTO metadata into the container (serialized, unpacked lazily per handler). Without the extension it is compiled once per process.
  • Docs (EN + SK), examples/typed-input in the examples CI matrix, typed GreetHandler in examples/attributes and examples/di-extension.

BC notes (4.0)

  • ErrorHandlerInterface::handleUnsupportedMediaType(string $detail) is new; custom error handlers must implement it. The bundled handlers do.
  • ParamType has new cases Path, Header, Body; InputParam has new public methods setOpenApiSchema(), getOpenApiSchema(), setContentTypes(), getContentTypes().
  • A custom presenter that calls ApiDecider::getApi() itself must call matchPath($method, $version, $package, $apiAction, $params) with the router values when getApi() finds no endpoint (or returns a template for its literal URL), to support URL templates.
  • A custom InputParam subclass whose $type is 'PATH', 'HEADER' or 'BODY' now behaves as the new param of that type.
  • params() handlers keep their existing (looser) conversion and OpenAPI output; snapshots of existing endpoints are unchanged.

Decisions

  1. DTO metadata is translated into existing InputParam objects, so there is one path for validation, OpenAPI and the console.
  2. Strict coercion only for typed DTOs (1a is not an int, typed strings must be valid UTF-8); params() behaviour is untouched.
  3. JSON is decoded without the associative flag, so {} and [] stay distinguishable.
  4. Upload errors other than "no file" are passed to the handler on FileUpload::$error, as with FileInputParam.
  5. OpenAPI form bodies use [] list names and deepObject encoding for objects; multipart lists the fields of an object one by one (address[street]), because OpenAPI applies encoding styles only to URL-encoded forms. A body with a list of objects (not describable in OpenAPI 3.0 form encoding) is advertised as JSON only, though the runtime still accepts the form.
  6. Pattern is PCRE; OpenAPI gets pattern only when the regex means the same in ECMA 262, otherwise x-pattern.
  7. #[Header('Accept')], Content-Type and Authorization are compile-time errors: OpenAPI ignores header parameters with these names, so they would be undocumented input.
  8. The JSON syntax error of a body is the same on every PHP version: the near location line:column suffix that PHP 8.6 adds is dropped.
  9. A route mask without <params> fills params from the query string; such a value is ignored, so ?params=detail cannot pick another endpoint.

Review log

  1. First pass: encoded %2F in a path value no longer routes to another endpoint; a literal {id} in a request no longer reaches a template; params() of plain handlers is no longer called an extra time per request; list<T> docblocks on inherited constructors resolve in the declaring class; list<Enum> params expose available values; header names are deduplicated case-insensitively; -00:00 offsets accepted; Range rejects INF/NAN; BodyInputParam from params() appears in OpenAPI and reads PUT forms; OpenAPI form/multipart schemas match what PHP parses; no trailing slash in templated package links. Cleanup: the hand-written container export/import layer replaced by serialize(); shared SourceAttribute interface; tests regrouped by topic; docs trimmed.
  2. Second pass: an exception while reading params (nested DTO constructor, caster) is answered after authorization; a URL template matching the whole path wins over a shorter static endpoint; typed params re-read the request every time (no stale state in workers or tests); ApiLink rejects '', . and .. path values. Tests added for mutation coverage.
  3. Third pass: the API console opens templated endpoints again; templates are matched from the router values (works with forward() and masks without v); overlapping or malformed templates and a PathInputParam without {name} fail at addApi(); createLink() fills templates; list<T> from a trait resolves in the trait; empty upload slots are dropped; a request without a body never gets 415 for optional body fields; truncated multipart is a 400; a field named body is refused; BodyInputParam shares the typed body parsing; files of constants used in attributes rebuild the container.
  4. Fourth pass (this round):
    • CI: the escaped CastString mutant in EndpointTemplate::fill() is gone (Strings::replace instead of preg_replace_callback plus a cast); the PHP 8.6 JSON error text is normalized (see decision 8).
    • Routing: ?params= from the query string no longer selects a template or bypasses the %2F guard; . and .. (also as %2E%2E) are no longer captured as path values, matching what ApiLink refuses.
    • Input: a POST body over post_max_size is a 400 Request body is too large instead of an empty form (post_max_size = 0 means no limit); BodyInputParam gives arrays for JSON objects, as params() handlers expect; HeaderInputParam('X_Request_Id') finds X-Request-Id; Split rejects invalid UTF-8 like other string fields; DateFormat with a format that cannot parse its own output ('c') fails at compile time instead of rejecting every request.
    • OpenAPI: multipart objects are listed as bracket fields (decision 5); a params() handler with BodyInputParam documents its 415; reserved header names are refused (decision 7).
    • Docs (EN and SK): BodyInputParam default media types and array values, multipart objects, reserved header names; UPGRADE-4.0.md says when params() handlers get 415 and that a custom 'PATH' param needs a {name} segment.
    • Not changed: a blank plain HeaderInputParam in the console is still sent empty, like other params() fields; non-empty-list<T> is read as list<T> as documented; +24:00 offsets and very large Unix timestamps are accepted. The one PHP 8.6 deprecation (NetteCacheStorage::NAMESPACE) and the 42 deprecations of the lowest-dependencies job come from master and are the same there.

Verification

  • PHPUnit: 1662 tests, 580063 assertions on PHP 8.4, 8.5 and 8.6 and with lowest dependencies (master: 1133 tests); 529 tests added, 8 of them in this round. PHP 8.6 reports 1 deprecation and lowest dependencies 42, the same as on master.
  • PHPStan, PHP_CodeSniffer, Rector dry-run, PHP syntax checks, CodeQL, docs build and all 17 example e2e jobs pass.
  • Infection on the changed lines: 2403 mutants, 2317 killed, 84 time outs, 2 syntax errors, 0 escaped; Mutation Code Coverage 100%, Covered Code MSI 100%.

@tomaj tomaj added this to the 4.0.0 milestone Nov 5, 2026
@tomaj tomaj self-assigned this Nov 5, 2026
@github-actions

github-actions Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
PR Preview Action v1.8.1

QR code for preview link

🚀 View preview at
https://tomaj.github.io/nette-api/pr-preview/pr-240/

Built to branch gh-pages at 2026-11-21 16:42 UTC.
Preview will be ready when the GitHub Pages deployment is complete.

@tomaj
tomaj force-pushed the feat/197-typed-input branch 3 times, most recently from 17e5f42 to 2fe3988 Compare November 5, 2026 20:09
@cursor
cursor Bot force-pushed the feat/197-typed-input branch 5 times, most recently from 2c60265 to fe84a3a Compare November 6, 2026 00:45
@tomaj
tomaj marked this pull request as ready for review November 6, 2026 01:06
@tomaj
tomaj force-pushed the feat/197-typed-input branch 8 times, most recently from 3ad84c4 to 9bfeea1 Compare November 14, 2026 14:22
@tomaj
tomaj force-pushed the feat/197-typed-input branch 3 times, most recently from 6ecf81b to b3a3fde Compare November 21, 2026 15:31
Typed input DTOs are a second, equal way to declare handler input next
to params(). TypedHandler reads a readonly DTO from handleDto() and turns
its #[Query], #[Path], #[Header], #[Body] and #[File] properties into
InputParam objects, so validation, OpenAPI and the API console keep
using the existing pipeline.

- URL templates with {name} segments, matched by ApiDecider::matchPath()
  after static endpoints; ApiLink and the console fill them
- PathInputParam, HeaderInputParam and BodyInputParam for params()
- strict conversion of int, float, bool, backed enums, DateTimeImmutable,
  list<T> and nested DTOs from JSON, form and multipart bodies
- constraints Range, Length, Pattern, Email; casters DateFormat,
  UnixTimestamp, Split; FileUpload for #[File]
- #[Consumes] and 415 Unsupported Media Type after authorization
- DTO metadata compiled into the DI container
- docs (EN and SK) and the typed-input example

Refs #197
@tomaj
tomaj force-pushed the feat/197-typed-input branch from b3a3fde to 7b72168 Compare November 21, 2026 16:41

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant