Skip to content

Typed input DTOs with attributes - #240

Open
tomaj wants to merge 5 commits into
masterfrom
feat/197-typed-input
Open

tomaj wants to merge 5 commits 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.

Key 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/multipart bodies use [] list names and deepObject encoding; 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.

Final review pass

Fixes: 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. 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.

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(), checked once instead of per request; createLink() fills templates; list<T> from a trait resolves in the trait; empty upload slots are dropped; a #[File] next to a list of objects stays in OpenAPI; 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 (400/415 on a bad body); files of constants used in attributes rebuild the container.

Cleanup: the hand-written container export/import layer (~400 lines) replaced by serialize(); shared SourceAttribute interface; dead defensive code removed; tests regrouped by topic instead of by review round; docs trimmed of implementation trivia.

🤖 Generated with Claude Code

https://claude.ai/code/session_012jrra6bHr2Jmk7hfEjoKsr

@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-15 18:03 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
TypedHandler reads handleDto() and turns a readonly DTO into InputParam objects, with strict conversion, nested JSON, form and multipart validation, constraints, casters and OpenAPI path and header parameters.
@tomaj
tomaj force-pushed the feat/197-typed-input branch from 9bfeea1 to 72354b3 Compare November 14, 2026 16:03
tomaj and others added 4 commits November 15, 2026 10:16
Fixes:
- Decode path segments one by one, so %2F stays inside a path value
- Skip URL templates in the static lookup and stop calling params() of plain handlers on every request
- ApiLink fills {name} from params; no trailing slash for a templated package
- Keep RequestInput unbooted after a 415; BodyInputParam reads PUT forms and HTTP_CONTENT_TYPE
- Resolve list<T> docblocks in the declaring class of an inherited constructor or caster
- list<Enum> available values, case-insensitive duplicate headers, -00:00 offsets, float list defaults
- OpenAPI form/multipart bodies use [] list names and deepObject encoding; a list of objects is JSON only
- BodyInputParam without a schema appears in OpenAPI; Range rejects INF and NAN

Cleanup:
- Replace the hand-written container export/import with serialize(), unpacked lazily per handler
- Shared SourceAttribute interface, dead defensive code removed
- Tests grouped by topic instead of by review round
- Docs trimmed of implementation details and aligned with the code (EN and SK)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012jrra6bHr2Jmk7hfEjoKsr
- Answer an exception thrown while reading params (nested DTO constructor, caster) through the error handler after authorization instead of letting it escape
- A URL template that matches the whole path wins over a shorter static endpoint when the URL has segments after the action
- Parse the request on every read of a typed handler's params, so tests and workers need no RequestInput::reset()
- ApiLink rejects '', '.' and '..' path values; the console refuses dot segments
- Check path names of typed handlers from compiled metadata and build MappedInputParam schemas lazily
- Docs: accuracy fixes (setContentTypes, #[Consumes] with files, compile-time vs addApi checks), Slovak terminology, BC list in CHANGELOG

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012jrra6bHr2Jmk7hfEjoKsr
Add tests for the new behaviour and drop operations without an observable
effect (redundant array_values/array_intersect, unused error values, the
MappedInputParam schema cache), so Infection on the changed lines is back
at 100% MSI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012jrra6bHr2Jmk7hfEjoKsr
Routing: the API console opens templated endpoints again, templates are
matched from the router values (forward, masks without "v"), template
configuration is checked once at addApi(), createLink() fills templates,
one shared {name} substitution for links and the console.

Input: list<T> from traits resolves in the trait, empty upload slots are
dropped, a file next to a list of objects stays in OpenAPI, no 415 for a
request without a body, truncated multipart is a 400, a field named body
is refused, BodyInputParam shares the typed body parsing, constant files
are container dependencies, dead code removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012jrra6bHr2Jmk7hfEjoKsr

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