From 72354b3be1f1bcfc8bd2d25f7a1e068a094aed69 Mon Sep 17 00:00:00 2001 From: Tomas Majer Date: Sat, 14 Nov 2026 17:03:29 +0100 Subject: [PATCH 1/5] Add typed input DTOs with attributes 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. --- .github/workflows/examples.yml | 2 +- CHANGELOG.md | 15 +- README.md | 43 +- UPGRADE-4.0.md | 21 +- composer.json | 5 +- docs/.vitepress/config.mts | 2 +- docs/api/reference.md | 25 +- docs/examples/attributes.md | 12 + docs/examples/di-extension.md | 12 + docs/examples/index.md | 3 +- docs/examples/typed-input.md | 54 + docs/faq.md | 10 +- docs/guide/api-decider.md | 8 +- docs/guide/architecture.md | 2 +- docs/guide/attributes.md | 37 +- docs/guide/console.md | 14 + docs/guide/di-extension.md | 4 +- docs/guide/errors.md | 3 +- docs/guide/getting-started.md | 47 +- docs/guide/handlers.md | 64 +- docs/guide/input-styles.md | 472 +++++++ docs/guide/layers.md | 4 +- docs/guide/links.md | 13 +- docs/guide/openapi.md | 2 +- docs/guide/outputs.md | 2 +- docs/guide/params.md | 24 + docs/guide/presenter.md | 4 +- docs/guide/problem-details.md | 1 + docs/guide/typed-input-body.md | 164 +++ docs/guide/typed-input-conversion.md | 182 +++ docs/guide/typed-input.md | 290 ++++ docs/index.md | 35 +- docs/site-nav.ts | 12 +- docs/sk/api/reference.md | 25 +- docs/sk/examples/attributes.md | 12 + docs/sk/examples/di-extension.md | 12 + docs/sk/examples/index.md | 3 +- docs/sk/examples/typed-input.md | 54 + docs/sk/faq.md | 10 +- docs/sk/guide/api-decider.md | 8 +- docs/sk/guide/architecture.md | 2 +- docs/sk/guide/attributes.md | 37 +- docs/sk/guide/console.md | 14 + docs/sk/guide/di-extension.md | 4 +- docs/sk/guide/errors.md | 3 +- docs/sk/guide/getting-started.md | 47 +- docs/sk/guide/handlers.md | 64 +- docs/sk/guide/input-styles.md | 472 +++++++ docs/sk/guide/layers.md | 6 +- docs/sk/guide/links.md | 13 +- docs/sk/guide/openapi.md | 2 +- docs/sk/guide/outputs.md | 2 +- docs/sk/guide/params.md | 24 + docs/sk/guide/presenter.md | 4 +- docs/sk/guide/problem-details.md | 3 +- docs/sk/guide/typed-input-body.md | 164 +++ docs/sk/guide/typed-input-conversion.md | 182 +++ docs/sk/guide/typed-input.md | 290 ++++ docs/sk/index.md | 35 +- examples/attributes/README.md | 3 + examples/attributes/app/Api/GreetHandler.php | 22 + examples/attributes/app/Api/GreetInput.php | 19 + examples/attributes/e2e.sh | 10 + examples/di-extension/README.md | 3 + .../di-extension/app/Api/GreetHandler.php | 18 + examples/di-extension/app/Api/GreetInput.php | 19 + examples/di-extension/config/common.neon | 2 + examples/di-extension/e2e.sh | 10 + .../logging-errors/app/AppErrorHandler.php | 5 + examples/typed-input/README.md | 28 + .../app/Api/AvatarUploadHandler.php | 29 + .../app/Api/CreateOrderHandler.php | 25 + .../app/Api/Input/AddressInput.php | 22 + .../typed-input/app/Api/Input/AvatarInput.php | 22 + .../app/Api/Input/CreateOrderInput.php | 25 + .../typed-input/app/Api/Input/ItemInput.php | 20 + .../app/Api/Input/ListUsersInput.php | 20 + .../app/Api/Input/UserDetailInput.php | 21 + .../typed-input/app/Api/Input/UserStatus.php | 11 + .../typed-input/app/Api/ListUsersHandler.php | 23 + .../typed-input/app/Api/UserDetailHandler.php | 23 + examples/typed-input/app/Bootstrap.php | 21 + examples/typed-input/app/RouterFactory.php | 18 + examples/typed-input/composer.json | 15 + examples/typed-input/config/common.neon | 16 + examples/typed-input/e2e.sh | 70 + examples/typed-input/public/index.php | 10 + rector.php | 2 + src/ApiDecider.php | 112 +- .../BearerTokenAuthorization.php | 6 +- src/DI/EndpointDefinition.php | 5 +- src/DI/NetteApiExtension.php | 70 + src/Error/DefaultErrorHandler.php | 6 + src/Error/ErrorHandlerInterface.php | 5 + src/Error/NegotiatingErrorHandler.php | 6 + src/Error/ProblemDetailsErrorHandler.php | 8 + src/Handlers/TypedHandler.php | 39 + src/Input/Body.php | 22 + src/Input/Cast.php | 23 + src/Input/CastException.php | 12 + src/Input/CasterInterface.php | 14 + src/Input/Consumes.php | 22 + src/Input/ConversionFailed.php | 12 + src/Input/DateFormat.php | 55 + src/Input/DtoCompiler.php | 1178 +++++++++++++++++ src/Input/DtoMapper.php | 406 ++++++ src/Input/DtoMetadata.php | 133 ++ src/Input/DtoMetadataRegistry.php | 73 + src/Input/EndpointTemplate.php | 195 +++ src/Input/Field.php | 327 +++++ src/Input/File.php | 22 + src/Input/FileUpload.php | 34 + src/Input/Header.php | 23 + src/Input/MediaTypes.php | 30 + src/Input/MissingValue.php | 12 + src/Input/OpenApiCasterInterface.php | 17 + src/Input/Path.php | 23 + src/Input/Query.php | 22 + src/Input/RequestInput.php | 332 +++++ src/Input/ScalarCoercer.php | 175 +++ src/Input/SchemaBuilder.php | 154 +++ src/Input/Source.php | 17 + src/Input/Split.php | 40 + src/Input/TypeName.php | 131 ++ src/Input/UnixTimestamp.php | 32 + src/Input/UnsupportedMediaTypeException.php | 38 + src/Input/ValueExport.php | 58 + src/Link/ApiLink.php | 43 +- src/Misc/ConsoleRequest.php | 165 ++- src/OpenApi/ParameterBuilder.php | 29 +- src/OpenApi/RequestBodyBuilder.php | 51 + src/OpenApi/ResponseBuilder.php | 42 + src/Params/BodyInputParam.php | 51 + src/Params/HeaderBag.php | 48 + src/Params/HeaderInputParam.php | 22 + src/Params/InputParam.php | 49 +- src/Params/MappedInputParam.php | 87 ++ src/Params/ParamType.php | 3 + src/Params/ParamsProcessor.php | 8 + src/Params/PathInputParam.php | 32 + src/Params/PathValues.php | 37 + src/Presenters/ApiPresenter.php | 82 +- src/Validation/ConstraintContext.php | 43 + src/Validation/ConstraintInterface.php | 15 + src/Validation/Email.php | 22 + src/Validation/Length.php | 61 + src/Validation/Pattern.php | 79 ++ src/Validation/Range.php | 58 + src/ValidationResult/FieldErrors.php | 41 + .../BearerTokenAuthorizationTest.php | 32 + tests/DI/TypedBad/BadHandler.php | 19 + tests/DI/TypedBad/BadInput.php | 16 + tests/DI/TypedInputExtensionTest.php | 62 + tests/Error/UnsupportedMediaTypeTest.php | 57 + tests/Input/BehaviorPinTest.php | 827 ++++++++++++ tests/Input/CasterTest.php | 68 + tests/Input/CompilerBranchTest.php | 1122 ++++++++++++++++ tests/Input/ConstraintTest.php | 121 ++ tests/Input/DtoCompilerTest.php | 454 +++++++ tests/Input/DtoHandlerTest.php | 340 +++++ tests/Input/EndpointTemplateTest.php | 75 ++ tests/Input/EscapeTest.php | 350 +++++ tests/Input/FileUploadTest.php | 380 ++++++ .../Fixtures/Dependency/DependencyCaster.php | 15 + .../Dependency/DependencyConstraint.php | 17 + .../Fixtures/Dependency/DependencyEnum.php | 10 + .../Fixtures/Dependency/DependencyHandler.php | 17 + .../Fixtures/Dependency/DependencyInput.php | 10 + .../Dependency/DependencyItemEnum.php | 10 + .../Dependency/DependencyNestedTrait.php | 13 + .../Dependency/DependencyParentInput.php | 22 + .../Dependency/DependencyParentTrait.php | 13 + .../Fixtures/Dependency/DependencyTrait.php | 15 + tests/Input/Fixtures/Handlers.php | 332 +++++ tests/Input/Fixtures/ImportScope.php | 31 + tests/Input/Fixtures/ImportScopeTrait.php | 9 + tests/Input/Fixtures/SecondScope.php | 18 + tests/Input/Fixtures/Separate/NoteHandler.php | 17 + tests/Input/Fixtures/Separate/NoteInput.php | 14 + tests/Input/Fixtures/create-order-export.json | 265 ++++ tests/Input/ReviewContractTest.php | 790 +++++++++++ tests/Input/Round10Test.php | 319 +++++ tests/Input/Round11Test.php | 1042 +++++++++++++++ tests/Input/Round12Test.php | 656 +++++++++ tests/Input/Round13Test.php | 409 ++++++ tests/Input/ScalarCoercerTest.php | 135 ++ tests/Input/TypeNameTest.php | 125 ++ tests/Misc/ConsoleRequestTest.php | 353 +++++ tests/OpenApi/ParameterBuilderTest.php | 10 + tests/OpenApi/TypedInputOpenApiTest.php | 99 ++ .../OpenApi/snapshots/typed-create-order.json | 125 ++ .../OpenApi/snapshots/typed-user-detail.json | 42 + tests/Params/ParamTypeTest.php | 10 +- tests/Params/PathHeaderBodyParamTest.php | 85 ++ .../Presenters/ApiPresenterIpDetectorTest.php | 5 +- .../Presenters/ApiPresenterRateLimitTest.php | 5 + .../ApiPresenterUnsupportedMediaTypeTest.php | 174 +++ tests/TypedEndpointMatchTest.php | 123 ++ 198 files changed, 17689 insertions(+), 138 deletions(-) create mode 100644 docs/examples/typed-input.md create mode 100644 docs/guide/input-styles.md create mode 100644 docs/guide/typed-input-body.md create mode 100644 docs/guide/typed-input-conversion.md create mode 100644 docs/guide/typed-input.md create mode 100644 docs/sk/examples/typed-input.md create mode 100644 docs/sk/guide/input-styles.md create mode 100644 docs/sk/guide/typed-input-body.md create mode 100644 docs/sk/guide/typed-input-conversion.md create mode 100644 docs/sk/guide/typed-input.md create mode 100644 examples/attributes/app/Api/GreetHandler.php create mode 100644 examples/attributes/app/Api/GreetInput.php create mode 100644 examples/di-extension/app/Api/GreetHandler.php create mode 100644 examples/di-extension/app/Api/GreetInput.php create mode 100644 examples/typed-input/README.md create mode 100644 examples/typed-input/app/Api/AvatarUploadHandler.php create mode 100644 examples/typed-input/app/Api/CreateOrderHandler.php create mode 100644 examples/typed-input/app/Api/Input/AddressInput.php create mode 100644 examples/typed-input/app/Api/Input/AvatarInput.php create mode 100644 examples/typed-input/app/Api/Input/CreateOrderInput.php create mode 100644 examples/typed-input/app/Api/Input/ItemInput.php create mode 100644 examples/typed-input/app/Api/Input/ListUsersInput.php create mode 100644 examples/typed-input/app/Api/Input/UserDetailInput.php create mode 100644 examples/typed-input/app/Api/Input/UserStatus.php create mode 100644 examples/typed-input/app/Api/ListUsersHandler.php create mode 100644 examples/typed-input/app/Api/UserDetailHandler.php create mode 100644 examples/typed-input/app/Bootstrap.php create mode 100644 examples/typed-input/app/RouterFactory.php create mode 100644 examples/typed-input/composer.json create mode 100644 examples/typed-input/config/common.neon create mode 100755 examples/typed-input/e2e.sh create mode 100644 examples/typed-input/public/index.php create mode 100644 src/Handlers/TypedHandler.php create mode 100644 src/Input/Body.php create mode 100644 src/Input/Cast.php create mode 100644 src/Input/CastException.php create mode 100644 src/Input/CasterInterface.php create mode 100644 src/Input/Consumes.php create mode 100644 src/Input/ConversionFailed.php create mode 100644 src/Input/DateFormat.php create mode 100644 src/Input/DtoCompiler.php create mode 100644 src/Input/DtoMapper.php create mode 100644 src/Input/DtoMetadata.php create mode 100644 src/Input/DtoMetadataRegistry.php create mode 100644 src/Input/EndpointTemplate.php create mode 100644 src/Input/Field.php create mode 100644 src/Input/File.php create mode 100644 src/Input/FileUpload.php create mode 100644 src/Input/Header.php create mode 100644 src/Input/MediaTypes.php create mode 100644 src/Input/MissingValue.php create mode 100644 src/Input/OpenApiCasterInterface.php create mode 100644 src/Input/Path.php create mode 100644 src/Input/Query.php create mode 100644 src/Input/RequestInput.php create mode 100644 src/Input/ScalarCoercer.php create mode 100644 src/Input/SchemaBuilder.php create mode 100644 src/Input/Source.php create mode 100644 src/Input/Split.php create mode 100644 src/Input/TypeName.php create mode 100644 src/Input/UnixTimestamp.php create mode 100644 src/Input/UnsupportedMediaTypeException.php create mode 100644 src/Input/ValueExport.php create mode 100644 src/Params/BodyInputParam.php create mode 100644 src/Params/HeaderBag.php create mode 100644 src/Params/HeaderInputParam.php create mode 100644 src/Params/MappedInputParam.php create mode 100644 src/Params/PathInputParam.php create mode 100644 src/Params/PathValues.php create mode 100644 src/Validation/ConstraintContext.php create mode 100644 src/Validation/ConstraintInterface.php create mode 100644 src/Validation/Email.php create mode 100644 src/Validation/Length.php create mode 100644 src/Validation/Pattern.php create mode 100644 src/Validation/Range.php create mode 100644 src/ValidationResult/FieldErrors.php create mode 100644 tests/DI/TypedBad/BadHandler.php create mode 100644 tests/DI/TypedBad/BadInput.php create mode 100644 tests/DI/TypedInputExtensionTest.php create mode 100644 tests/Error/UnsupportedMediaTypeTest.php create mode 100644 tests/Input/BehaviorPinTest.php create mode 100644 tests/Input/CasterTest.php create mode 100644 tests/Input/CompilerBranchTest.php create mode 100644 tests/Input/ConstraintTest.php create mode 100644 tests/Input/DtoCompilerTest.php create mode 100644 tests/Input/DtoHandlerTest.php create mode 100644 tests/Input/EndpointTemplateTest.php create mode 100644 tests/Input/EscapeTest.php create mode 100644 tests/Input/FileUploadTest.php create mode 100644 tests/Input/Fixtures/Dependency/DependencyCaster.php create mode 100644 tests/Input/Fixtures/Dependency/DependencyConstraint.php create mode 100644 tests/Input/Fixtures/Dependency/DependencyEnum.php create mode 100644 tests/Input/Fixtures/Dependency/DependencyHandler.php create mode 100644 tests/Input/Fixtures/Dependency/DependencyInput.php create mode 100644 tests/Input/Fixtures/Dependency/DependencyItemEnum.php create mode 100644 tests/Input/Fixtures/Dependency/DependencyNestedTrait.php create mode 100644 tests/Input/Fixtures/Dependency/DependencyParentInput.php create mode 100644 tests/Input/Fixtures/Dependency/DependencyParentTrait.php create mode 100644 tests/Input/Fixtures/Dependency/DependencyTrait.php create mode 100644 tests/Input/Fixtures/Handlers.php create mode 100644 tests/Input/Fixtures/ImportScope.php create mode 100644 tests/Input/Fixtures/ImportScopeTrait.php create mode 100644 tests/Input/Fixtures/SecondScope.php create mode 100644 tests/Input/Fixtures/Separate/NoteHandler.php create mode 100644 tests/Input/Fixtures/Separate/NoteInput.php create mode 100644 tests/Input/Fixtures/create-order-export.json create mode 100644 tests/Input/ReviewContractTest.php create mode 100644 tests/Input/Round10Test.php create mode 100644 tests/Input/Round11Test.php create mode 100644 tests/Input/Round12Test.php create mode 100644 tests/Input/Round13Test.php create mode 100644 tests/Input/ScalarCoercerTest.php create mode 100644 tests/Input/TypeNameTest.php create mode 100644 tests/OpenApi/TypedInputOpenApiTest.php create mode 100644 tests/OpenApi/snapshots/typed-create-order.json create mode 100644 tests/OpenApi/snapshots/typed-user-detail.json create mode 100644 tests/Params/PathHeaderBodyParamTest.php create mode 100644 tests/Presenters/ApiPresenterUnsupportedMediaTypeTest.php create mode 100644 tests/TypedEndpointMatchTest.php diff --git a/.github/workflows/examples.yml b/.github/workflows/examples.yml index 9f0270522..c187188ee 100644 --- a/.github/workflows/examples.yml +++ b/.github/workflows/examples.yml @@ -15,7 +15,7 @@ jobs: strategy: fail-fast: false matrix: - example: [ hello-world, params-validation, auth, cors, openapi-console, logging-errors, custom-authorization, json-body, file-upload, pagination, versions, rate-limit, testing, problem-details, di-extension, attributes ] + example: [ hello-world, params-validation, auth, cors, openapi-console, logging-errors, custom-authorization, json-body, file-upload, pagination, versions, rate-limit, testing, problem-details, di-extension, attributes, typed-input ] name: Example ${{ matrix.example }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 0329ae48d..e1697ba3a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ Updates should follow the [Keep a CHANGELOG](http://keepachangelog.com/) princip Planned for 4.0, developed on `master`. 3.x is maintained on the `3.x` branch. ### Added -* Custom error message for token authorization +* Custom error message for token authorization (#242) ### Changed (BC breaks) * Renamed the unsafe CORS mode `'auto'` (any website can make credentialed requests) to `'reflect-unsafe'` (`CorsMode::ReflectUnsafe`) with the same behaviour plus `Vary: Origin, Referer`: `setCorsHeader('auto')` throws and `api: cors: mode: auto` fails the compilation, both with the allowlist to use instead and the new name (#186). @@ -30,6 +30,7 @@ Planned for 4.0, developed on `master`. 3.x is maintained on the `3.x` branch. * Classes not meant for extension are `final`: `Api`, `ApiHolder`, `EndpointIdentifier`, `NoAuthorization`, `NoRateLimit`, `RateLimitResponse`, `IpDetector`, `StaticIpDetector`, `StaticTokenRepository`, `ConsoleRequest`, `ConsoleResponse`, `OpenApiTransform`, `ParamsProcessor`, `InputValidator`, `JsonSchemaValidator`, `ValidationResult`, `DebuggerConfigurator`, `EnvConfigurator`, `QueryConfigurator`. See `UPGRADE-4.0.md`. * `TextApiResponse` throws `InvalidArgumentException` for arrays and non-`Stringable` objects instead of outputting `Array` with a warning (arrays) or failing with an `Error` (objects); non-string values in validation messages, IP headers, console fields and OpenAPI examples are converted to strings instead of raising warnings or `TypeError`. * `Error\ErrorHandlerInterface` methods return `ResponseInterface` instead of `JsonApiResponse`, and the interface has two new methods, `handleNotFound(EndpointInterface)` and `handleRateLimit(RateLimitResponse)`. Own implementations must add them (#196). +* `Error\ErrorHandlerInterface` has a new method `handleUnsupportedMediaType(string $detail)` for the `415` of typed handlers. Own implementations must add it (#197). * `ApiPresenter` builds the `404` for an unknown endpoint and the `429` for a reached rate limit (without an own error response) through the error handler. `DefaultErrorHandler` sends the same bodies as before, except that a `429` without a known retry time says only `Too many requests.` instead of `Retry after seconds.` (#196). * `Handlers\DefaultHandler` is `final`. `ApiPresenter` does not call its `handle()`, so a subclass could no longer change the `404`; do it in `ErrorHandlerInterface::handleNotFound()` (#196). * Request logs are masked by default (#187): `ApiPresenter` replaces secret header values (`Authorization`, `Proxy-Authorization`, `Cookie`, `Set-Cookie`, `X-Api-Key`, names containing `token`, `secret` or `key`, `X-Auth-*`), secret query parameters in the logged URI (`api_key`, `token`, `access_token`, `password`, `signature`, `code`, ...) and the names used by the API key authentications with `***` before `ApiLoggerInterface::log()`. The DI extension's `logging: maskHeaders` defaults to `true`. Opt out with `setMaskedLogHeaders([])` / `setMaskedLogQueryParams([])` or `maskHeaders: false` / `maskQueryParams: false`. See `UPGRADE-4.0.md`. @@ -59,6 +60,18 @@ Planned for 4.0, developed on `master`. 3.x is maintained on the `3.x` branch. * Rate limiting (#195): `FixedWindowLimiter`, `SlidingWindowLimiter` and `TokenBucketLimiter` behind `RateLimit\RateLimiterInterface`, combined by `RateLimiterChain`; keys by IP, identity, endpoint or a combination (`Key\RateLimitKeyInterface`); storages in memory, in the Nette cache (atomic on one server through a file lock in `%tempDir%`, waiting at most 3 seconds) or in Redis with one atomic Lua script that keeps the whole state of a counter in one hash with one expiration (`Storage\RedisStorage` with ext-redis or Predis, keys `prefix{policy:key}` for Redis Cluster); own algorithms (`Algorithm\RateLimitAlgorithmInterface`, with `RedisScriptAlgorithmInterface` for Redis) and own storages (`Storage\RateLimitStorageInterface`, `KeyValueStorage`). `ApiPresenter` checks the limits before the authorization and, for identity keys, after it. A failing storage lets the request pass and logs a warning. Time comes from a `Psr\Clock\ClockInterface`. Intervals are from 1 second to 366 days. `IpKey` hashes values longer than an IP and other keys longer than 200 characters are hashed, the memory storage drops expired counters as it grows, and all algorithms keep the newest window or time of servers with skewed clocks. When the logger fails, the warning goes to `error_log`. Limits are at most 1 000 000 000, policy and `rateLimits` names are ASCII, the parts of a list key are escaped, and the presenter escapes policy names of own limiters in the headers. A list of policies stops at the first rejection, so rejected requests do not use up a shared quota. The `ip` key counts an IPv6 client per `/64`. `api: rateLimiting: logger` sets the logger of the warnings. `Authorization\AuthorizationIdentityInterface` gives a limit keyed by `identity` the caller; the token authorizations and `BasicAuthentication` implement it. An authorization that returns no identity after a successful `authorized()` is logged once per process and policy. `ApiDecider::addApi()` without the 4th argument throws a `LogicException` naming the services when the container has more autowired `RateLimitInterface` services, instead of using none. A failing API logger after the handler only goes to the Tracy log, the response of the handler is sent. * DI extension: named policies in `api: rateLimits` (`{algorithm, limit, interval, key, name}`), `api: rateLimiting` (`storage`, `redis`, `prefix`, `clock`), lists of policies and inline limits on endpoints and in `api: defaults`, `rateLimit: false`; inline limits always keep counters per endpoint (also with `name`), two named policies with the same `name` and an inline `name` equal to a named policy fail the compilation; `#[RateLimit]` takes a list or `limit`, `interval`, `algorithm`, `key` and `name` (#195). * `examples/rate-limit` uses the built-in policies; `examples/auth`, `examples/di-extension` and `examples/attributes` no longer ship an own `FileRateLimit` (#195). +* Typed input DTOs (#197, #240): `Handlers\TypedHandler` reads `handleDto(SomeInput $input)` and turns a readonly DTO into `InputParam` objects at container compile time (or once per process without the extension). It is an equal second way to declare input next to `params()` with `handle(array $params)`, which is unchanged. + * Sources: `#[Query]`, `#[Path]`, `#[Header]`, `#[Body]` and `#[File]`; nullable or defaulted properties are optional. `PathInputParam`, `HeaderInputParam` and `BodyInputParam` are also usable from `params()`. + * Endpoint actions can have `{name}` segments, for example `#[Get(1, 'users', '{id}/detail')]`. `ApiDecider::getApi()` keeps its four arguments; the new `ApiDecider::matchPath()` finds the endpoint of a URL template, and `ApiPresenter` calls it when `getApi()` finds no static endpoint. + * Strict conversion of int, float, bool, backed enums, `DateTimeImmutable` (RFC 3339) and `list`. `#[Cast]` with `CasterInterface` replaces the conversion of one property; `DateFormat`, `UnixTimestamp` and `Split` are built in. The constraints are `Range`, `Length`, `Pattern` (complete match, `$` matches only at the very end) and `Email`, and `ConstraintInterface` adds your own. + * Nested objects and lists are validated for JSON, form and multipart and reported as `items[1].quantity` in the existing error envelope and in Problem Details. A request reports at most 100 errors in total, however deeply lists are nested; when something was left unchecked, the key `body` says so. + * `#[Consumes]` limits body media types; any other one, including a body that arrives without a content type, is `415` and OpenAPI lists it. A DTO with a required file advertises only `multipart/form-data`; a JSON request to it gets a `400` that says files need `multipart/form-data`. `#[File]` is read only on the input DTO of the handler. + * OpenAPI: `in: path` and `in: header` parameters, `nullable` only on body properties, query lists as `name[]`, file properties only under `multipart/form-data`. + * The API console sends path values into the URL (`ApiLink::link()` keeps its signature and still decides the URL), header values as headers and body values as JSON, a URL-encoded form or multipart, as the handler's content types ask. Blank typed fields, blank optional text fields and blank list slots are not sent, and a blank path value is explained instead of called. + * JSON bodies must be UTF-8 (`utf-8`, `utf8` and `us-ascii` are accepted); a request that names another charset is a `400`. A multipart body sent with `PUT` or `PATCH`, and a URL-encoded form with more fields than `max_input_vars`, get a `400` that says why. `BearerTokenAuthorization` also reads `REDIRECT_HTTP_AUTHORIZATION`. `ApiPresenter::run()` also resets the path values. + * A `string` from a query, form, header or path value must be valid UTF-8 (a `400` `Value must be valid UTF-8` otherwise); `params()` handlers are unchanged. OpenAPI gets `pattern` only for a `#[Pattern]` that means the same in ECMA 262, and the PCRE pattern as `x-pattern` otherwise. + * The DI cache is rebuilt when a DTO, its parent class, a trait it uses, a caster, a constraint or an enum changes. + * Documentation: [typed input](https://tomaj.github.io/nette-api/guide/typed-input), body and conversion pages, [params() and DTO side by side](https://tomaj.github.io/nette-api/guide/input-styles) and `examples/typed-input`; `examples/attributes` and `examples/di-extension` have a typed endpoint next to the `params()` ones. ### Changed * Dev tools: PHPUnit ^12 || ^13, PHPStan ^2.1 (level max, no baseline), Rector ^2.2, PHP_CodeSniffer ^4.0, Infection; `symfony/yaml` ^7.4.12 || ^8.0.12. diff --git a/README.md b/README.md index 583ac6a4a..dfa04a108 100644 --- a/README.md +++ b/README.md @@ -56,9 +56,16 @@ services: For new projects we recommend [RFC 9457 Problem Details](https://tomaj.github.io/nette-api/guide/problem-details) errors: register `Tomaj\NetteApi\Error\ProblemDetailsErrorHandler` as `apiErrorHandler`. `DefaultErrorHandler` stays the default, so existing clients that read `message` keep working. -Write the handler: +Write the handler. There are two equal ways to declare its input; pick the one that fits the endpoint, and mix them freely in one API. + +With a list of params, the handler gets an array: ```php +use Tomaj\NetteApi\Handlers\BaseHandler; +use Tomaj\NetteApi\Params\GetInputParam; +use Tomaj\NetteApi\Response\JsonApiResponse; +use Tomaj\NetteApi\Response\ResponseInterface; + final class HelloHandler extends BaseHandler { public function params(): array @@ -75,6 +82,34 @@ final class HelloHandler extends BaseHandler } ``` +With a typed DTO (since 4.0), the handler gets a validated object: + +```php +use Tomaj\NetteApi\Handlers\TypedHandler; +use Tomaj\NetteApi\Input\Query; +use Tomaj\NetteApi\Response\JsonApiResponse; +use Tomaj\NetteApi\Response\ResponseInterface; + +final readonly class HelloInput +{ + public function __construct( + #[Query] + public string $name = 'world', + ) { + } +} + +final class HelloHandler extends TypedHandler +{ + public function handleDto(HelloInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['message' => 'Hello ' . $input->name . '!']); + } +} +``` + +Both go through the same validation pipeline, OpenAPI and web console; a typed DTO converts values more strictly than `params()`. See [Handlers](https://tomaj.github.io/nette-api/guide/handlers) and [Typed input (DTO)](https://tomaj.github.io/nette-api/guide/typed-input). + ```bash curl http://localhost:8000/api/v1/hello?name=Nette # {"message":"Hello Nette!"} @@ -101,7 +136,7 @@ Or put `#[Get(1, 'hello')]` on the handler class and let the extension find it w | --- | --- | | How a request is processed | [Architecture](https://tomaj.github.io/nette-api/guide/architecture) | | What each layer does: ApiDecider, presenter, authorization, params, handler, outputs | [Layers](https://tomaj.github.io/nette-api/guide/layers), [ApiDecider](https://tomaj.github.io/nette-api/guide/api-decider), [ApiPresenter pipeline](https://tomaj.github.io/nette-api/guide/presenter) | -| Handlers, params and outputs | [Handlers](https://tomaj.github.io/nette-api/guide/handlers), [Params](https://tomaj.github.io/nette-api/guide/params), [Outputs](https://tomaj.github.io/nette-api/guide/outputs) | +| Handlers, params, typed input DTOs and outputs | [Handlers](https://tomaj.github.io/nette-api/guide/handlers), [Params](https://tomaj.github.io/nette-api/guide/params), [Typed input (DTO)](https://tomaj.github.io/nette-api/guide/typed-input), [Outputs](https://tomaj.github.io/nette-api/guide/outputs) | | Bearer tokens, API keys, HTTP Basic, IP restrictions | [Authorization](https://tomaj.github.io/nette-api/guide/authorization) | | Rate limits, CORS, logging, errors | [Rate limiting](https://tomaj.github.io/nette-api/guide/rate-limit), [CORS](https://tomaj.github.io/nette-api/guide/cors), [Logging](https://tomaj.github.io/nette-api/guide/logging), [Error handling](https://tomaj.github.io/nette-api/guide/errors) | | OpenAPI, web console, `{apiLink}` | [OpenAPI](https://tomaj.github.io/nette-api/guide/openapi), [Web console](https://tomaj.github.io/nette-api/guide/console), [Links and versions](https://tomaj.github.io/nette-api/guide/links) | @@ -117,8 +152,8 @@ Or put `#[Get(1, 'hello')]` on the handler class and let the extension find it w ## Examples -Sixteen runnable projects in [`examples/`](examples/), each with an `e2e.sh` test that CI runs against the current code: -[hello world](examples/hello-world), [params and validation](examples/params-validation), [authorization and rate limit](examples/auth), [CORS](examples/cors), [OpenAPI and console](examples/openapi-console), [logging and errors](examples/logging-errors), [Problem Details](examples/problem-details), [DI extension](examples/di-extension), [attribute endpoints](examples/attributes), [custom authorization](examples/custom-authorization), [JSON and raw body](examples/json-body), [file upload](examples/file-upload), [pagination](examples/pagination), [API versions](examples/versions), [rate limit](examples/rate-limit), [testing](examples/testing). +Seventeen runnable projects in [`examples/`](examples/), each with an `e2e.sh` test that CI runs against the current code: +[hello world](examples/hello-world), [params and validation](examples/params-validation), [authorization and rate limit](examples/auth), [CORS](examples/cors), [OpenAPI and console](examples/openapi-console), [logging and errors](examples/logging-errors), [Problem Details](examples/problem-details), [DI extension](examples/di-extension), [attribute endpoints](examples/attributes), [custom authorization](examples/custom-authorization), [JSON and raw body](examples/json-body), [file upload](examples/file-upload), [typed input DTOs](examples/typed-input), [pagination](examples/pagination), [API versions](examples/versions), [rate limit](examples/rate-limit), [testing](examples/testing). ## Upgrading diff --git a/UPGRADE-4.0.md b/UPGRADE-4.0.md index c97ec049b..4ddf4822c 100644 --- a/UPGRADE-4.0.md +++ b/UPGRADE-4.0.md @@ -74,6 +74,20 @@ new BearerTokenAuthorization(new StaticBearerTokenRepository(['token' => '*']), new BearerTokenAuthorization(new StaticTokenRepository(['token' => '*']), $ipDetector); ``` +## Error handlers answer 415 + +`ErrorHandlerInterface` has `handleUnsupportedMediaType(string $detail): ResponseInterface`. A typed handler sends 415 when the body content type is missing or not one of the types it accepts. `DefaultErrorHandler` uses the message `unsupported media type` and adds the detail only when error details are on. `ProblemDetailsErrorHandler` uses status 415, title `Unsupported Media Type` and type `unsupported-media-type`. An own error handler has to implement the method. `params()` handlers are not affected. + +## Typed input does not change params() + +`TypedHandler` is an additional way to declare input. Handlers that stay on `BaseHandler::params()` and `handle(array $params)` keep their conversion, validation and OpenAPI output. `PathInputParam` and `HeaderInputParam` are new classes; existing parameter classes are unchanged. A path segment is written in the endpoint action or package, for example `#[Get(1, 'users', '{id}/detail')]`. The usual route `/api/v/[/][/]` already delivers `users/42/detail`. + +## ApiDecider::getApi() and ApiLink::link() keep their signatures + +`ApiDecider::getApi(string $method, string $version, string $package, ?string $apiAction = null)` is unchanged, so a subclass that overrides it needs no change. Endpoints with `{name}` segments are found by the new `ApiDecider::matchPath()`, which `ApiPresenter` calls when `getApi()` returns no static endpoint. An own presenter that should serve URL templates calls `matchPath()` the same way. + +`ApiLink::link(EndpointInterface $endpoint, $params = [])` is unchanged too. A link for an endpoint with `{name}` segments keeps them literal (the OpenAPI path template). The API console puts typed path values into those segments after `link()` returned the URL, so a subclass that overrides `link()` (for example to add a prefix) still decides the URL of every endpoint. `BearerTokenAuthorization` also reads `REDIRECT_HTTP_AUTHORIZATION`, which Apache with CGI or FastCGI sets after a rewrite. + ## Stricter types * Every file declares `strict_types=1`. @@ -125,7 +139,7 @@ Overriding methods are marked with `#[\Override]`. ## Error handlers -`ErrorHandlerInterface` methods return `ResponseInterface` instead of `JsonApiResponse`, and the interface has two new methods. An own implementation must add them; a wrapper can delegate to `DefaultErrorHandler`: +`ErrorHandlerInterface` methods return `ResponseInterface` instead of `JsonApiResponse`, and the interface has three new methods compared with 3.x: `handleNotFound()` and `handleRateLimit()` (#196), and `handleUnsupportedMediaType(string $detail)` for the `415` of typed handlers (#197, see "Error handlers answer 415" above). An own implementation must add them; a wrapper can delegate to `DefaultErrorHandler`: ```php use Tomaj\NetteApi\EndpointInterface; @@ -141,6 +155,11 @@ public function handleRateLimit(RateLimitResponse $rateLimit): ResponseInterface { return $this->inner->handleRateLimit($rateLimit); } + +public function handleUnsupportedMediaType(string $detail): ResponseInterface +{ + return $this->inner->handleUnsupportedMediaType($detail); +} ``` Returning `JsonApiResponse` from the old methods still satisfies the interface. Code that calls an error handler and needs `JsonApiResponse` methods such as `getPayload()` must check the type. diff --git a/composer.json b/composer.json index 92b7310d8..d3ff22309 100644 --- a/composer.json +++ b/composer.json @@ -55,7 +55,10 @@ "autoload-dev": { "psr-4": { "Tomaj\\NetteApi\\Test\\": "tests" - } + }, + "classmap": [ + "tests/Input/Fixtures/Handlers.php" + ] }, "scripts": { "test": "phpunit", diff --git a/docs/.vitepress/config.mts b/docs/.vitepress/config.mts index c2ae59c18..1c5bd6666 100644 --- a/docs/.vitepress/config.mts +++ b/docs/.vitepress/config.mts @@ -29,7 +29,7 @@ export default defineConfig({ lastUpdated: true, markdown: { - languageAlias: { latte: 'html', neon: 'yaml' }, + languageAlias: { latte: 'html', neon: 'yaml', openapi: 'yaml' }, }, sitemap: { diff --git a/docs/api/reference.md b/docs/api/reference.md index 8007ec58f..979f147ee 100644 --- a/docs/api/reference.md +++ b/docs/api/reference.md @@ -1,6 +1,6 @@ --- title: Reference -description: Every public class and interface of Nette API 3.x by namespace, with a one line description and a link to the guide page. +description: The public classes and interfaces of Nette API by namespace, with a one line description and a link to the guide page. --- # Reference @@ -11,7 +11,7 @@ All classes live under `Tomaj\NetteApi`. | Class | What it does | Guide | | --- | --- | --- | -| `ApiDecider` | registry of endpoints: `addApi()`, `getApi()`, `getApis()`, `enableGlobalPreflight()` | [Architecture](/guide/architecture) | +| `ApiDecider` | registry of endpoints: `addApi()`, `getApi()`, `matchPath()`, `getApis()`, `enableGlobalPreflight()` | [Architecture](/guide/architecture) | | `Api` | one registered endpoint: endpoint, handler, authorization, rate limit | [Architecture](/guide/architecture) | | `ApiHolder` | used inside `ApiDecider`: how it stores an endpoint before its handler is created; the handler can still be a class or service name | [ApiDecider](/guide/api-decider#three-ways-to-pass-a-handler) | | `EndpointIdentifier` / `EndpointInterface` | method, version, package, action | [Handlers](/guide/handlers#registering-a-handler) | @@ -25,7 +25,7 @@ All classes live under `Tomaj\NetteApi`. | Class | What it does | Guide | | --- | --- | --- | -| `Handlers\ApiHandlerInterface`, `BaseHandler` | your endpoints | [Handlers](/guide/handlers) | +| `Handlers\ApiHandlerInterface`, `BaseHandler`, `TypedHandler` | your endpoints; `TypedHandler` takes a DTO | [Handlers](/guide/handlers), [Typed input](/guide/typed-input) | | `Handlers\OpenApiHandler` | OpenAPI 3.0 document | [OpenAPI](/guide/openapi) | | `Handlers\ApiListingHandler` | JSON list of the endpoints in its own version | [Handlers](/guide/handlers#handlers-that-ship-with-the-library) | | `Handlers\AlwaysOkHandler`, `EchoHandler` | health check and test endpoints | [Handlers](/guide/handlers#handlers-that-ship-with-the-library) | @@ -36,11 +36,26 @@ All classes live under `Tomaj\NetteApi`. | Class | What it does | Guide | | --- | --- | --- | -| `Params\GetInputParam`, `PostInputParam`, `PutInputParam`, `CookieInputParam`, `FileInputParam`, `RawInputParam`, `JsonInputParam` | one input each | [Params](/guide/params) | +| `Params\GetInputParam`, `PostInputParam`, `PutInputParam`, `PathInputParam`, `HeaderInputParam`, `BodyInputParam`, `CookieInputParam`, `FileInputParam`, `RawInputParam`, `JsonInputParam` | one input each | [Params](/guide/params) | | `Params\InputParam`, `ParamInterface`, `ParamsProcessor` | the base class and the processing | [Params](/guide/params) | | `Validation\InputValidator`, `JsonSchemaValidator`, `InputType` (enum) | value checks | [Params](/guide/params#types) | | `ValidationResult\ValidationResult(Interface)` | the result of a check | [Params](/guide/params) | +## Typed input (4.0.0) + +| Class | What it does | Guide | +| --- | --- | --- | +| `Input\Query`, `Path`, `Header`, `Body`, `File` | attributes that say where a DTO property is read from | [Typed input](/guide/typed-input#source-attributes) | +| `Input\Consumes`, `Input\FileUpload` | restricts the accepted body media types; the typed upload value | [Body, files and content types](/guide/typed-input-body) | +| `Input\Cast`, `CasterInterface`, `OpenApiCasterInterface`, `CastException` | a custom conversion of one property | [Conversion](/guide/typed-input-conversion#custom-conversions-with-cast) | +| `Input\DateFormat`, `UnixTimestamp`, `Split` | built-in casters | [Conversion](/guide/typed-input-conversion#built-in-casters-and-a-czech-date) | +| `Validation\Range`, `Length`, `Pattern`, `Email` | built-in constraints | [Constraints](/guide/typed-input-conversion#constraints) | +| `Validation\ConstraintInterface`, `ConstraintContext` | your own constraints | [Custom constraints](/guide/typed-input-conversion#custom-constraints) | +| `Params\MappedInputParam` | the `InputParam` generated for one DTO property | [Typed input](/guide/typed-input) | +| `Input\RequestInput`, `Params\PathValues` | request state of a typed handler, reset in long-running workers | [Long-running workers](/guide/typed-input#long-running-workers) | + +The other classes of the `Input` namespace are the machinery behind these (compiler, mapper, metadata, schema and conversion helpers). They are not listed and are not meant to be extended or called directly. + ## Responses and outputs | Class | What it does | Guide | @@ -69,7 +84,7 @@ All classes live under `Tomaj\NetteApi`. | Class | What it does | Guide | | --- | --- | --- | | `Logger\ApiLoggerInterface` | request log | [Logging](/guide/logging) | -| `Link\ApiLink`, `ApiLinkExtension`, `ApiLinkNode` | URLs and the `{apiLink}` tag | [Links](/guide/links) | +| `Link\ApiLink` (`link()`), `ApiLinkExtension`, `ApiLinkNode` | URLs and the `{apiLink}` tag | [Links](/guide/links) | | `Component\ApiListingControl`, `ApiConsoleControl`, `ApiConsoleFormFactoryInterface`, `DefaultApiConsoleFormFactory` | web console | [Web console](/guide/console) | | `Misc\ConsoleRequest`, `ConsoleResponse` | the console's cURL request | [Web console](/guide/console) | | `Misc\CorsOriginAllowlist` | internal (`@internal`), used by `setCorsAllowedOrigins()`; may change in 4.0 | [CORS](/guide/cors#allowed-origins) | diff --git a/docs/examples/attributes.md b/docs/examples/attributes.md index e58b36d00..258074ff8 100644 --- a/docs/examples/attributes.md +++ b/docs/examples/attributes.md @@ -44,6 +44,18 @@ The attributes and `api: discovery:` are new in 4.0.0. <<< @/../examples/attributes/app/Api/UsersListHandler.php +## A typed input DTO + +`GreetHandler` is a `TypedHandler`: the same `#[Get]` and `#[Authorization]` attributes, with its input in `GreetInput` instead of `params()`. + +::: code-group + +<<< @/../examples/attributes/app/Api/GreetHandler.php + +<<< @/../examples/attributes/app/Api/GreetInput.php + +::: + ## An endpoint with an action <<< @/../examples/attributes/app/Api/UserDetailHandler.php diff --git a/docs/examples/di-extension.md b/docs/examples/di-extension.md index 7792b28de..28e433335 100644 --- a/docs/examples/di-extension.md +++ b/docs/examples/di-extension.md @@ -36,6 +36,18 @@ A users API configured only in the `api:` section of `config/common.neon`, with <<< @/../examples/di-extension/app/Api/UsersListHandler.php +## A typed input DTO + +`GreetHandler` is a `TypedHandler` registered in `endpoints:` like the others; its input is the `GreetInput` DTO instead of `params()`. + +::: code-group + +<<< @/../examples/di-extension/app/Api/GreetHandler.php + +<<< @/../examples/di-extension/app/Api/GreetInput.php + +::: + ## The bootstrap <<< @/../examples/di-extension/app/Bootstrap.php diff --git a/docs/examples/index.md b/docs/examples/index.md index e41d3365c..7b7038d21 100644 --- a/docs/examples/index.md +++ b/docs/examples/index.md @@ -1,6 +1,6 @@ --- title: Examples -description: 'Sixteen runnable Nette API projects tested in CI: params, JSON body, uploads, pagination, authorization, rate limit, CORS, versions, OpenAPI, logging, testing, DI extension, attribute endpoints.' +description: 'Seventeen runnable Nette API projects tested in CI: params, typed input, JSON body, uploads, pagination, authorization, rate limit, CORS, versions, OpenAPI, logging, testing, DI extension, attribute endpoints.' --- # Examples @@ -33,6 +33,7 @@ To run an example against your local checkout, as CI does, use `examples/ci/exam { title: 'Custom authorization', text: 'Your own ApiAuthorizationInterface with roles, the user in the handler, token or API key.', link: '/examples/custom-authorization' }, { title: 'JSON and raw body', text: 'A JSON body checked by a schema, and a CSV body.', link: '/examples/json-body' }, { title: 'File upload', text: 'One file and many files, size and real type checked.', link: '/examples/file-upload' }, + { title: 'Typed input', text: 'A readonly DTO for query, path, header, JSON or form and a file (needs 4.0.0).', link: '/examples/typed-input' }, { title: 'Pagination', text: 'Typed page params, allowed values, links, an output for every code.', link: '/examples/pagination' }, { title: 'API versions', text: 'v1 and v2 of one endpoint, deprecation headers, OpenAPI per version.', link: '/examples/versions' }, { title: 'Rate limit', text: 'A default per IP, a quota per API key, #[RateLimit] and an endpoint without a limit.', link: '/examples/rate-limit' }, diff --git a/docs/examples/typed-input.md b/docs/examples/typed-input.md new file mode 100644 index 000000000..a39b9f414 --- /dev/null +++ b/docs/examples/typed-input.md @@ -0,0 +1,54 @@ +--- +title: 'Example: typed input' +description: 'Runnable Nette API example: a readonly DTO with query, path, header, JSON or form body and a file upload.' +--- + +# Example: typed input + +Four handlers extend `TypedHandler`. The DTO on `handleDto()` is the request contract: `#[Query]`, `#[Path]`, `#[Header]`, `#[Body]` and `#[File]`. The same order endpoint accepts JSON and a URL-encoded form. See [Typed input](/guide/typed-input). + + + +::: tip Since 4.0.0 +Typed handlers, path and header parameters and `#[Consumes]` are new in 4.0.0. +::: + +| Request | Status | What it shows | +| --- | --- | --- | +| `GET /api/v1/users/list` | `200` | `page` defaults to `1`, `status` is null | +| `GET /api/v1/users/list?page=2&status=active` | `200` | integer and backed enum | +| `GET /api/v1/users/list?page=1a` | `400` | `1a` is not an integer | +| `GET /api/v1/users/42/detail` with `X-Request-Id` | `200` | path id and header | +| `POST /api/v1/orders` JSON | `201` | nested DTO and `list` | +| `POST /api/v1/orders` form | `201` | the same DTO, bracket names | +| `POST /api/v1/orders` invalid body | `400` | `items[1].quantity` | +| `POST /api/v1/orders` `text/csv` | `415` | content type outside the default pair | +| `POST /api/v1/orders` postal code `81101` plus a newline | `400` | `$` in the pattern ends the string | +| `POST /api/v1/avatar` multipart | `201` | `FileUpload` | +| `GET /api/v1/openapi` | `200` | path parameter and both body content types | + +## A query DTO + +<<< @/../examples/typed-input/app/Api/Input/ListUsersInput.php + +<<< @/../examples/typed-input/app/Api/ListUsersHandler.php + +## A path and header DTO + +<<< @/../examples/typed-input/app/Api/Input/UserDetailInput.php + +<<< @/../examples/typed-input/app/Api/UserDetailHandler.php + +## A file upload + +<<< @/../examples/typed-input/app/Api/Input/AvatarInput.php + +<<< @/../examples/typed-input/app/Api/AvatarUploadHandler.php + +## Registration + +The path endpoint is `#[Get(1, 'users', '{id}/detail')]`. The route is the usual one, with an optional third segment: + +<<< @/../examples/typed-input/app/RouterFactory.php + +<<< @/../examples/typed-input/config/common.neon diff --git a/docs/faq.md b/docs/faq.md index 989a2f61d..2e78e5108 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -33,6 +33,14 @@ The presenter returns before the logger in 3.x. See [Logging](/guide/logging#wha Yes, in a new project: RFC 9457 errors have one machine-readable shape. They are not the default, because existing clients read `message`. See [Problem Details](/guide/problem-details). +## Should I use params() or a typed DTO? + +Either: they are two equal ways to declare the input of a handler, and one API can mix them. See [Typed input (DTO)](/guide/typed-input) for what differs and [params() and DTO side by side](/guide/input-styles) for the same endpoints in both styles. + +## Why does my typed endpoint answer 415? + +The body has a content type the handler does not accept, or none at all. By default a DTO with body fields accepts JSON and a URL-encoded form, and `#[Consumes]` changes that. See [body, files and content types](/guide/typed-input-body). + ## Can I configure the API without a list of addApi() calls? Yes, since 4.0.0 with the [DI extension](/guide/di-extension): one `api:` neon section with the endpoints, authorizations, rate limits, CORS and the error format, checked when the container is compiled. @@ -55,4 +63,4 @@ Follow the [upgrade guide](/upgrade) and the [changelog](/changelog). ## Is there a complete project I can run? -Yes, 13 of them, tested in CI: see [Examples](/examples/). +Yes, 17 of them, tested in CI: see [Examples](/examples/). diff --git a/docs/guide/api-decider.md b/docs/guide/api-decider.md index 89948dab1..626d98ef2 100644 --- a/docs/guide/api-decider.md +++ b/docs/guide/api-decider.md @@ -41,7 +41,7 @@ The 4th argument is the rate limit, `null` means none. Left out, an autowired `R | method | `'GET'` | compared upper case | | version | `1`, `'1.1'` | stored as a string, must not contain `/` | | package | `'users'` | the first path segment after the version | -| apiAction | `'detail'` or `null` | optional second segment | +| apiAction | `'detail'`, `'{id}/detail'` or `null` | optional second segment; `{name}` makes it a URL template, see below | `getUrl()` returns `v1/users/detail`, which [OpenAPI](/guide/openapi) and the console use. @@ -55,6 +55,12 @@ The 4th argument is the rate limit, `null` means none. Left out, an autowired `R 4. sets the endpoint on the handler, so `getEndpoint()` and `createLink()` work; 5. with no match returns `DefaultHandler` and `NoAuthorization`, which answer `404 Unknown api endpoint` through the error handler's `handleNotFound()`. +`getApi()` keeps its four arguments, so a subclass that overrides it keeps working, and it finds only endpoints with a static URL. + +### Endpoints with {name} segments + +An endpoint whose action has `{name}` segments, such as `users/{id}/detail`, needs the path of the request. `ApiPresenter` calls `getApi()` first, and when that finds nothing it calls `matchPath($method, $version, $package, $apiAction, $path)`. A static endpoint therefore always wins. `matchPath()` compares the path with every template of the method and version, stores the matched values for the `#[Path]` properties and returns the `Api`, or `null` when no template matches. When two templates match one path it throws a `LogicException` that lists them, so make a static segment differ. A global preflight also answers `OPTIONS` for a path that matches a template. How to register and route one is in [Typed input](/guide/typed-input#path-values-and-url-templates). + `GET /api/v1/users` and `POST /api/v1/users` are two endpoints with two handlers. A version that is not registered, such as `/api/v3/users`, is a `404`, as the [versions example](/examples/versions) tests. ## Three ways to pass a handler diff --git a/docs/guide/architecture.md b/docs/guide/architecture.md index 241b774ed..9ed7385c3 100644 --- a/docs/guide/architecture.md +++ b/docs/guide/architecture.md @@ -16,7 +16,7 @@ Every API request goes to one presenter, `Tomaj\NetteApi\Presenters\ApiPresenter | Presenter | `ApiPresenter` | Runs every step below. It is `final`. | | Endpoint list | `ApiDecider` | `addApi()` registers endpoints, `getApi()` finds the one for a request. | | Endpoint | `EndpointIdentifier` | Method, version, package and optional action. | -| Handler | `ApiHandlerInterface`, usually `BaseHandler` | Declares params and outputs, does the work. | +| Handler | `ApiHandlerInterface`, usually `BaseHandler` or `TypedHandler` | Declares params (or a typed input DTO) and outputs, does the work. | | Authorization | `ApiAuthorizationInterface` | Says whether the request may run. | | Rate limit | `RateLimiterInterface` | Optional, per endpoint. | | Errors | `ErrorHandlerInterface`, `DefaultErrorHandler` | Turns failures into JSON responses. | diff --git a/docs/guide/attributes.md b/docs/guide/attributes.md index 870ee04ab..8903cb045 100644 --- a/docs/guide/attributes.md +++ b/docs/guide/attributes.md @@ -11,7 +11,9 @@ The attributes in `Tomaj\NetteApi\Attribute` are new in 4.0.0. They need the [DI With attributes you write the URL of an endpoint right on the handler class. There is no endpoint list in neon to keep in sync with the code: -```php [app/Api/UsersListHandler.php] +::: code-group + +```php [params()] namespace App\Api; use Tomaj\NetteApi\Attribute\Get; @@ -29,7 +31,37 @@ final class UsersListHandler extends BaseHandler } ``` -`#[Get(1, 'users')]` means `GET /api/v1/users`. The neon config only says where the handlers are: +```php [Typed DTO] +namespace App\Api; + +use Tomaj\NetteApi\Attribute\Get; +use Tomaj\NetteApi\Handlers\TypedHandler; +use Tomaj\NetteApi\Input\Query; +use Tomaj\NetteApi\Response\JsonApiResponse; +use Tomaj\NetteApi\Response\ResponseInterface; + +final readonly class UsersListInput +{ + public function __construct( + #[Query] + public int $page = 1, + ) { + } +} + +#[Get(1, 'users')] +final class UsersListHandler extends TypedHandler +{ + public function handleDto(UsersListInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['users' => [], 'page' => $input->page]); + } +} +``` + +::: + +`#[Get(1, 'users')]` means `GET /api/v1/users`. The attributes work the same on a `BaseHandler` and on a `TypedHandler`; `examples/attributes` has both. The neon config only says where the handlers are: ```yaml [config/api.neon] extensions: @@ -48,6 +80,7 @@ When Nette compiles the container, the extension finds every class in `app/Api` | --- | --- | | `#[Get(1, 'users')]` | `GET /api/v1/users` | | `#[Get(1, 'users', 'detail')]` | `GET /api/v1/users/detail` | +| `#[Get(1, 'users', '{id}/detail')]` | `GET /api/v1/users/{id}/detail`, the `id` is read by a `#[Path]` property, see [Typed input](/guide/typed-input#path-values-and-url-templates) | | `#[Post(1, 'users')]` | `POST /api/v1/users` | | `#[Put(1, 'users', 'update')]` | `PUT /api/v1/users/update` | | `#[Patch(1, 'users')]` | `PATCH /api/v1/users` | diff --git a/docs/guide/console.md b/docs/guide/console.md index 3a2ac4fc3..d97d7d2f5 100644 --- a/docs/guide/console.md +++ b/docs/guide/console.md @@ -30,6 +30,20 @@ The `default` view (`default.latte`) renders the endpoint list. Clicking an endp The form has one field per param, a field for the token or API key (or user and password for Basic), and a timeout. Write your own `ApiConsoleFormFactoryInterface` to change it. +## What the console sends + +The console builds the request from the params of the handler, whether they come from `params()` or from a typed DTO, so there is no DTO-specific mode. + +| Param source | Sent as | +| --- | --- | +| query | the query string | +| path value | URL-encoded into the `{name}` segment of the URL | +| header value | a request header | +| body field | the first media type the handler reads that the console can build: JSON, a URL-encoded form or multipart | +| file | a multipart upload; with a file attached the body fields go in the same multipart request | + +In a JSON body each value keeps its declared type, and a nested object field takes JSON text, for example `{}` for an empty object. A list field has one input per item, and an item that is an object takes JSON text. A typed field that is left blank is not sent (an empty string would never be a valid number, date, choice, object or list item), so an unused list slot is skipped. A blank optional text field is not sent either, so the server uses its default; a required text field is sent as an empty string, so that its length and pattern constraints can be tried. An empty header is never sent. A blank path value is not sent at all: the console shows `The path value 'id' is empty. Fill it in and send the request again.` instead of calling a URL with an empty segment. A number that JSON cannot hold, such as `1e999` or an integer beyond the 64-bit range, is sent as text, so the server answers with its normal `400`. + ## FAQ ### Why does the form submit fail with a CSRF error? diff --git a/docs/guide/di-extension.md b/docs/guide/di-extension.md index af34f6930..49214bf32 100644 --- a/docs/guide/di-extension.md +++ b/docs/guide/di-extension.md @@ -50,7 +50,7 @@ Each item of `api.endpoints` is one endpoint: | `method` | yes | HTTP method, `GET`, `post`, ... (case does not matter) | | `version` | yes | `1`, `2`, `'2.1'` without the `v`; the URL is `/api/v{version}/...`. Write a version with a dot in quotes, neon reads `2.10` as the number `2.1` | | `package` | yes | the first part of the URL after the version, without a slash | -| `action` | no | the second part, `/api/v1/users/detail` has the action `detail`, without a slash | +| `action` | no | the second part, `/api/v1/users/detail` has the action `detail`, without a slash; `'{id}/detail'` (quoted) is a URL template, see [Typed input](/guide/typed-input#path-values-and-url-templates) | | `handler` | yes | the handler, see below | | `authorization` | no | who may call it, see [Authorization](#authorization-and-rate-limits) | | `rateLimit` | no | how often, see [Authorization](#authorization-and-rate-limits) | @@ -62,6 +62,8 @@ api: - {method: GET, version: 1, package: users, handler: App\Api\UsersListHandler} # GET /api/v1/users/detail?id=5 - {method: GET, version: 1, package: users, action: detail, handler: App\Api\UserDetailHandler} + # GET /api/v1/users/5/detail, the id is read by a #[Path] property + - {method: GET, version: 1, package: users, action: '{id}/detail', handler: App\Api\UserDetailByPathHandler} # POST /api/v1/users - {method: POST, version: 1, package: users, handler: App\Api\UserCreateHandler} # GET /api/v2.1/users diff --git a/docs/guide/errors.md b/docs/guide/errors.md index 75d7c8068..7297bc22b 100644 --- a/docs/guide/errors.md +++ b/docs/guide/errors.md @@ -18,11 +18,12 @@ description: How Nette API turns exceptions, wrong input, failed authorization a | `handleAuthorizationException(Throwable, array $params)` | `authorized()` threw | `500 Internal server error`, logs to Tracy | | `handleNotFound(EndpointInterface)` | no endpoint matches the URL | `404 Unknown api endpoint` | | `handleRateLimit(RateLimitResponse)` | the rate limit is reached and has no own response | `429 Too many requests.`, plus `Retry after N seconds.` when the time is known | +| `handleUnsupportedMediaType(string $detail)` | a typed handler gets a body of a content type it does not accept | `415 unsupported media type`, with the accepted types in `detail` only when error details are on | All of them return a `ResponseInterface`; `DefaultErrorHandler` returns a `JsonApiResponse` with `status: error` and `message`. ::: tip Since 4.0.0 -`handleNotFound()` and `handleRateLimit()` are new, so `404` and `429` can be changed in one place. The methods return `ResponseInterface` instead of `JsonApiResponse`. `handleAuthorizationException()` no longer sends the exception message unless error details are on. See the [upgrade guide](/upgrade). +`handleNotFound()`, `handleRateLimit()` and `handleUnsupportedMediaType()` are new, so `404`, `429` and `415` can be changed in one place. The methods return `ResponseInterface` instead of `JsonApiResponse`. `handleAuthorizationException()` no longer sends the exception message unless error details are on. See the [upgrade guide](/upgrade). ::: For new projects we recommend RFC 9457 `application/problem+json` errors with `ProblemDetailsErrorHandler`, see [Problem Details](/guide/problem-details). `DefaultErrorHandler` stays the default so that clients reading `message` keep working. diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.md index 5e3447b03..b60845f63 100644 --- a/docs/guide/getting-started.md +++ b/docs/guide/getting-started.md @@ -109,9 +109,11 @@ Then load the file in `app/Bootstrap.php`: ## 4. Write the handler -Create `app/Api/HelloHandler.php`: +Create `app/Api/HelloHandler.php`. A handler declares its input in one of two equal ways: a list of params in `params()`, or a typed DTO read by `handleDto()`. Both go through the same validation pipeline and give the same OpenAPI and web console, and one API can mix them. A typed DTO converts values more strictly than `params()`. -```php [app/Api/HelloHandler.php] +::: code-group + +```php [params()] 'Hello ' . $input->name . '!']); + } +} +``` + +::: + +With `params()`, `handle()` gets the validated params as an array. With a typed DTO, `handleDto()` gets a validated `HelloInput` object. Both return a response. [Handlers](/guide/handlers) explains the other methods and [Typed input (DTO)](/guide/typed-input) the DTO attributes. ## 5. Call it diff --git a/docs/guide/handlers.md b/docs/guide/handlers.md index 989b95445..67abc8564 100644 --- a/docs/guide/handlers.md +++ b/docs/guide/handlers.md @@ -5,7 +5,12 @@ description: Write Nette API handlers - extend BaseHandler, declare params(), ou # Handlers -A handler is the code of one endpoint. It implements `Tomaj\NetteApi\Handlers\ApiHandlerInterface`; in practice you extend `BaseHandler` and write `handle()`. +A handler is the code of one endpoint. It implements `Tomaj\NetteApi\Handlers\ApiHandlerInterface`; in practice you extend one of two equal base classes, depending on how you want to declare the input: + +- `BaseHandler`: list the input in `params()` and read it as an array in `handle(array $params)`. +- `TypedHandler`: describe the input as a readonly DTO with `#[Query]`, `#[Path]`, `#[Header]`, `#[Body]` and `#[File]` and read it as an object in `handleDto(SomeInput $input)`. See [Typed input (DTO)](/guide/typed-input). + +Both end up as the same `InputParam` objects, so the validation pipeline, error responses, OpenAPI and the web console are shared. Only the conversion differs: a typed DTO converts strictly (`?page=1a` is a `400`), while `params()` keeps its looser conversion, see [Input params](/guide/params#types). One API can mix both. @@ -13,17 +18,19 @@ A handler is the code of one endpoint. It implements `Tomaj\NetteApi\Handlers\Ap | Method | Default in BaseHandler | Used by | | --- | --- | --- | -| `handle(array $params): ResponseInterface` | abstract, you write it | ApiPresenter | -| `params(): array` | `[]` | validation, OpenAPI, console | +| `handle(array $params): ResponseInterface` | abstract, you write it; `TypedHandler` implements it and calls `handleDto()` | ApiPresenter | +| `params(): array` | `[]`; `TypedHandler` builds it from the DTO | validation, OpenAPI, console | | `outputs(): array` | `[]` | output check, OpenAPI | | `summary(): string` | `''` | OpenAPI, console | | `description(): string` | `''` | OpenAPI, console | | `tags(): array` | `[]` | OpenAPI | | `deprecated(): bool` | `false` | OpenAPI | -`handle()` gets the values of the params keyed by their names. It returns a response such as `JsonApiResponse`, see [Outputs and responses](/guide/outputs). +`handle()` gets the values of the params keyed by their names; `handleDto()` gets the DTO. It returns a response such as `JsonApiResponse`, see [Outputs and responses](/guide/outputs). + +::: code-group -```php +```php [params()] users->find($input->id); + if ($user === null) { + return new JsonApiResponse(404, ['status' => 'error', 'message' => 'User not found']); + } + return new JsonApiResponse(200, ['id' => $user->id, 'name' => $user->name]); + } +} +``` + +::: + `BaseHandler` has a constructor with an optional Fractal `ScopeFactoryInterface`. When your handler has its own constructor, call `parent::__construct()`. ## Registering a handler diff --git a/docs/guide/input-styles.md b/docs/guide/input-styles.md new file mode 100644 index 000000000..70c442408 --- /dev/null +++ b/docs/guide/input-styles.md @@ -0,0 +1,472 @@ +--- +title: params() and DTO side by side +description: 'The same endpoints declared with params() and with a typed DTO in Nette API: seven pairs that show how to rewrite a handler from one style to the other.' +--- + +# params() and DTO side by side + +`params()` with `handle(array $params)` and `TypedHandler` with a DTO are two equal ways to write handlers in one application. Neither disables the other. Registration, authorization, outputs, rate limits, OpenAPI and the console are shared. [Typed input (DTO)](/guide/typed-input) compares the two styles, and [Input params](/guide/params) documents the first. + +## Rewriting between styles + +The following pairs show the same request contract in both styles, so you can rewrite a handler from either style to the other when it suits that endpoint. Framework imports are omitted where they are unchanged; application constructor dependencies and response creation remain in the handler. You can rewrite one endpoint, leave every other handler unchanged and rewrite the next one when it is convenient. There is no application-wide switch. + +### 1. Simple GET: optional/defaulted query params and an enum + +With `params()`, the handler declares each query parameter, casts the values and maps the status string to an enum. `UserStatus::options()` stands for an application helper that returns the allowed values: + +```php +final class ListUsersHandler extends BaseHandler +{ + public function __construct(private UserRepository $users) + { + parent::__construct(); + } + + public function params(): array + { + return [ + (new GetInputParam('page', InputType::INTEGER)) + ->setDefault(1) + ->setDescription('Page number'), + (new GetInputParam('limit', InputType::INTEGER))->setDefault(20), + (new GetInputParam('status', InputType::STRING)) + ->setAvailableValues(UserStatus::options()), + ]; + } + + public function handle(array $params): ResponseInterface + { + $page = (int) $params['page']; + $limit = (int) $params['limit']; + $status = $params['status'] === null + ? null + : UserStatus::from($params['status']); + + if ($page < 1 || $limit < 1 || $limit > 100) { + return new JsonApiResponse(400, ['status' => 'error']); + } + + return new JsonApiResponse(200, $this->users->findPage($page, $limit, $status)); + } +} +``` + +With a DTO, defaults, optionality and allowed enum values live in the class. `Range` replaces the manual bounds check and `handleDto()` receives values ready to use: + +```php +final readonly class ListUsersInput +{ + public function __construct( + #[Query(description: 'Page number')] + #[Range(min: 1)] + public int $page = 1, + + #[Query] + #[Range(min: 1, max: 100)] + public int $limit = 20, + + #[Query] + public ?UserStatus $status = null, + ) { + } +} + +final class ListUsersHandler extends TypedHandler +{ + public function __construct(private UserRepository $users) + { + parent::__construct(); + } + + public function handleDto(ListUsersInput $input): ResponseInterface + { + return new JsonApiResponse(200, $this->users->findPage( + $input->page, + $input->limit, + $input->status, + )); + } +} +``` + +This also demonstrates the general rule for optional and defaulted values: `?UserStatus $status = null` is optional and becomes `null`; `int $limit = 20` is optional and becomes `20` when omitted. A required value would be non-nullable and have no default, for example `#[Query] public string $search`. + +### 2. GET: a path id and a request header + +With `params()`, the endpoint URL contains `users/{id}/detail` and `params()` declares `PathInputParam` and `HeaderInputParam`: + +```php +final class UserDetailHandler extends BaseHandler +{ + public function params(): array + { + return [ + (new PathInputParam('id', InputType::INTEGER))->setRequired(), + new HeaderInputParam('X-Request-Id', InputType::STRING), + ]; + } + + public function handle(array $params): ResponseInterface + { + $id = (int) $params['id']; + $requestId = $params['X-Request-Id']; + + return $this->userDetail($id, $requestId); + } +} +``` + +With a DTO, `Path` and `Header` keep the external names while the handler uses meaningful typed properties: + +```php +final readonly class UserDetailInput +{ + public function __construct( + #[Path] + #[Range(min: 1)] + public int $id, + + #[Header('X-Request-Id')] + public ?string $requestId = null, + ) { + } +} + +final class UserDetailHandler extends TypedHandler +{ + public function handleDto(UserDetailInput $input): ResponseInterface + { + return $this->userDetail($input->id, $input->requestId); + } +} +``` + +The endpoint registration and URL do not change. The DTO declaration still emits `id` as a required path parameter and `X-Request-Id` as an optional header in OpenAPI. + +### 3. POST JSON: a nested object and an array + +With `params()`, a `JsonInputParam` contains a handwritten schema. The handler reads nested arrays and constructs its own values: + +```php +final class CreateOrderHandler extends BaseHandler +{ + public function params(): array + { + return [ + (new JsonInputParam('body', <<<'JSON' + { + "type": "object", + "required": ["customerEmail", "address", "items"], + "properties": { + "customerEmail": {"type": "string", "format": "email"}, + "address": { + "type": "object", + "required": ["street", "postalCode"], + "properties": { + "street": {"type": "string"}, + "postalCode": {"type": "string", "pattern": "^[0-9]{5}$"} + } + }, + "items": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "required": ["sku", "quantity"], + "properties": { + "sku": {"type": "string"}, + "quantity": {"type": "integer", "minimum": 1} + } + } + } + } + } + JSON))->setRequired(), + ]; + } + + public function handle(array $params): ResponseInterface + { + $body = $params['body']; + $items = array_map( + fn (array $item) => new OrderItem($item['sku'], (int) $item['quantity']), + $body['items'], + ); + + return $this->orders->create( + $body['customerEmail'], + new Address($body['address']['street'], $body['address']['postalCode']), + $items, + ); + } +} +``` + +With a DTO, the nested structure is expressed once as classes. No JSON schema is needed for runtime validation: + +```php +final readonly class AddressInput +{ + public function __construct( + #[Body] public string $street, + #[Body] #[Pattern('/^[0-9]{5}$/')] public string $postalCode, + ) { + } +} + +final readonly class OrderItemInput +{ + public function __construct( + #[Body] public string $sku, + #[Body] #[Range(min: 1)] public int $quantity, + ) { + } +} + +final readonly class CreateOrderInput +{ + /** @param list $items */ + public function __construct( + #[Body] #[Email] public string $customerEmail, + #[Body] public AddressInput $address, + #[Body] #[Length(min: 1)] public array $items, + ) { + } +} + +final class CreateOrderHandler extends TypedHandler +{ + public function handleDto(CreateOrderInput $input): ResponseInterface + { + $items = array_map( + fn (OrderItemInput $item) => new OrderItem($item->sku, $item->quantity), + $input->items, + ); + + return $this->orders->create( + $input->customerEmail, + new Address($input->address->street, $input->address->postalCode), + $items, + ); + } +} +``` + +`list` is important: it tells both the mapper and OpenAPI what an array item contains. A failure in the second quantity is reported under `items[1].quantity`. + +### 4. Form POST + +With `params()`, `PostInputParam` objects describe a URL-encoded login form: + +```php +final class LoginHandler extends BaseHandler +{ + public function params(): array + { + return [ + (new PostInputParam('email', InputType::STRING))->setRequired(), + (new PostInputParam('password', InputType::STRING))->setRequired(), + (new PostInputParam('remember', InputType::BOOLEAN))->setDefault(false), + ]; + } + + public function handle(array $params): ResponseInterface + { + return $this->sessions->login( + (string) $params['email'], + (string) $params['password'], + (bool) $params['remember'], + ); + } +} +``` + +With a DTO, `Body` means a body field regardless of whether the request is JSON or form-encoded. The `max` bound is the only length rule here, because a minimum would start rejecting existing short passwords at login: + +```php +final readonly class LoginInput +{ + public function __construct( + #[Body] #[Email] public string $email, + #[Body] #[Length(max: 200)] public string $password, + #[Body] public bool $remember = false, + ) { + } +} + +final class LoginHandler extends TypedHandler +{ + public function handleDto(LoginInput $input): ResponseInterface + { + return $this->sessions->login($input->email, $input->password, $input->remember); + } +} +``` + +The form still sends `email=ada%40example.com&password=...&remember=1`. The DTO mapper rejects unknown boolean strings rather than treating every non-empty string as `true`. + +### 5. File upload + +With `params()`, the handler receives the raw upload entry and validates its upload error and size: + +```php +final class AvatarUploadHandler extends BaseHandler +{ + public function params(): array + { + return [ + (new PostInputParam('displayName', InputType::STRING))->setRequired(), + (new FileInputParam('avatar'))->setRequired(), + ]; + } + + public function handle(array $params): ResponseInterface + { + $avatar = $params['avatar']; + if ($avatar['error'] !== UPLOAD_ERR_OK || $avatar['size'] > 100_000) { + return new JsonApiResponse(400, ['status' => 'error']); + } + + return $this->avatars->store((string) $params['displayName'], $avatar['tmp_name']); + } +} +``` + +With a DTO, `FileUpload` gives typed access to the same metadata. Application checks for real file type and storage remain explicit: + +```php +final readonly class AvatarUploadInput +{ + public function __construct( + #[Body] #[Length(min: 1, max: 80)] public string $displayName, + #[File] public FileUpload $avatar, + ) { + } +} + +final class AvatarUploadHandler extends TypedHandler +{ + public function handleDto(AvatarUploadInput $input): ResponseInterface + { + $avatar = $input->avatar; + if ($avatar->error !== UPLOAD_ERR_OK || $avatar->size > 100_000) { + return new JsonApiResponse(400, ['status' => 'error']); + } + + return $this->avatars->store($input->displayName, $avatar->temporaryPath); + } +} +``` + +The multipart field names remain `displayName` and `avatar`. Neither style replaces application security checks or PHP upload limits. + +### 6. Custom validation + +With `params()`, validation that depends on several values lives in `handle()`: + +```php +final class ScheduleHandler extends BaseHandler +{ + public function params(): array + { + return [ + (new JsonInputParam('body', $this->scheduleSchema()))->setRequired(), + ]; + } + + public function handle(array $params): ResponseInterface + { + $startsAt = new DateTimeImmutable($params['body']['startsAt']); + $endsAt = new DateTimeImmutable($params['body']['endsAt']); + if ($endsAt <= $startsAt) { + return new JsonApiResponse(400, [ + 'status' => 'error', + 'message' => 'wrong input', + 'detail' => ['endsAt' => ['End must be later than start']], + ]); + } + + return $this->schedule->create($startsAt, $endsAt); + } +} +``` + +With a DTO, simple conversion and RFC 3339 parsing are declarative. A custom constraint owns the cross-field rule, keeping the transport response consistent: + +```php +#[Attribute(Attribute::TARGET_PROPERTY)] +final readonly class LaterThan implements ConstraintInterface +{ + public function __construct(private string $otherProperty) + { + } + + public function validate(mixed $value, ConstraintContext $context): ?string + { + $other = $context->value($this->otherProperty); + if ($value instanceof DateTimeImmutable && $other instanceof DateTimeImmutable && $value <= $other) { + return sprintf('Must be later than %s', $this->otherProperty); + } + + return null; + } +} + +final readonly class ScheduleInput +{ + public function __construct( + #[Body] public DateTimeImmutable $startsAt, + #[Body] #[LaterThan('startsAt')] public DateTimeImmutable $endsAt, + ) { + } +} + +final class ScheduleHandler extends TypedHandler +{ + public function handleDto(ScheduleInput $input): ResponseInterface + { + return $this->schedule->create($input->startsAt, $input->endsAt); + } +} +``` + +`ConstraintContext::value()` reads sibling values in the same DTO, so cross-property constraints do not have to inspect the HTTP request. Business rules that need a database still belong in application services; a constraint should remain a deterministic request-contract check. + +### 7. Both styles in one application + +An endpoint may depend on the looser `InputType::INTEGER` conversion of `params()`, on a custom `InputParam`, or on manual parsing of an unusual content type. `params()` is the right style for it: + +```php +final class ReportHandler extends BaseHandler +{ + public function params(): array + { + return [new GetInputParam('offset', InputType::INTEGER)]; + } + + public function handle(array $params): ResponseInterface + { + // This endpoint intentionally uses the looser params() conversion. + return $this->reports->generate($params['offset']); + } +} +``` + +Its neighboring `ListReportsHandler` can extend `TypedHandler`. Mixing the styles is supported without any limit; the choice is about ergonomics for each endpoint. + +### Checklist for rewriting a handler to a DTO + +1. **Capture the current contract:** save endpoint tests and the current OpenAPI operation, including defaults and error behavior. +2. **Create a readonly DTO:** one promoted property per query, path, header, body or file input. +3. **Preserve external names:** use explicit attribute names such as `#[Header('X-Request-Id')]` where the property name differs. +4. **Match requiredness:** non-nullable without a default means required; nullable or defaulted means optional. +5. **Replace manual declarations:** use backed enums for allowed values and the built-in constraints where they match existing checks. +6. **Handle nested data:** create a nested DTO and add `list` PHPDoc for DTO arrays. +7. **Move only contract validation:** keep database lookups and business rules in services or the handler; use custom constraints for deterministic input rules. +8. **Switch the base class:** replace `handle(array $params)` with `handleDto(Input $input)` and remove manual casts/array lookups. +9. **Compare behavior:** run success and failure requests, inspect field paths, compare OpenAPI and check the console form and upload behavior. +10. **Review compatibility:** call out the stricter conversion in your changelog. Keep `params()` for the endpoint if its current behavior must remain. + +Rewriting a DTO to `params()` goes the same way in reverse: declare one `InputParam` per property with the same name, required flag, default and allowed values, move the constraints into the handler or a custom `InputParam`, and compare the OpenAPI operation again. + diff --git a/docs/guide/layers.md b/docs/guide/layers.md index 34e208a21..47daae7ec 100644 --- a/docs/guide/layers.md +++ b/docs/guide/layers.md @@ -23,7 +23,8 @@ One request that passes, one without a token and one with wrong input: | Params | `InputParam`, `ParamsProcessor` | Reads and validates input; errors wait for authorization | | | Authorization | `ApiAuthorizationInterface` | Decides who may call | `401` | | Param errors | `ErrorHandlerInterface::handleInputParams()` | Reports invalid input | `400` | -| Handler | `ApiHandlerInterface`, `BaseHandler` | Your logic, returns a response | any code | +| Media type | `ErrorHandlerInterface::handleUnsupportedMediaType()` | Rejects a body the typed handler does not accept, after authorization | `415` | +| Handler | `ApiHandlerInterface`, `BaseHandler`, `TypedHandler` | Your logic, returns a response | any code | | Outputs | `OutputInterface`, `ConfiguratorInterface` | Checks the response against its schema | `500` | | Errors | `ErrorHandlerInterface` | Turns failures into JSON | | | Logger | `ApiLoggerInterface` | Records handled requests | | @@ -113,6 +114,7 @@ public function handle(array $params): ResponseInterface | `handleSchema()` | the output did not match | `500` | | `handleAuthorization()` | `authorized()` returned false | `401` with the message | | `handleAuthorizationException()` | `authorized()` threw | `500` with the exception message | +| `handleUnsupportedMediaType()` | a typed handler got a body of another content type | `415` | See [Error handling](/guide/errors). diff --git a/docs/guide/links.md b/docs/guide/links.md index 3ad617662..438f47ce9 100644 --- a/docs/guide/links.md +++ b/docs/guide/links.md @@ -15,7 +15,18 @@ $url = $apiLink->link(new EndpointIdentifier('GET', 1, 'users', 'detail'), ['id' It needs a route to `Api:Api:default` with `version`, `package` and `apiAction` parameters, as in [Getting started](/guide/getting-started). -Inside a handler extending `BaseHandler`, call `$this->createLink($params)` for a link to the handler's own endpoint. It needs Nette's `LinkGenerator` first, otherwise it throws `Nette\InvalidStateException`. Add a `setup` line to the handler service: +For an endpoint whose URL has `{name}` segments, such as `{id}/detail`, `link()` keeps the segments literal, which is the OpenAPI path template. Replace a segment with the URL-encoded value yourself: + +```php +$url = $apiLink->link(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), ['limit' => 5]); +// https://example.com/api/v1/users/{id}/detail?limit=5 +$url = str_replace('{id}', rawurlencode('42'), $url); +// https://example.com/api/v1/users/42/detail?limit=5 +``` + +The API console does the same with the values typed into the path inputs, after `link()` has built the URL, so a subclass that overrides `link()` still decides the URL of every endpoint. + +Inside a handler extending `BaseHandler` or `TypedHandler`, call `$this->createLink($params)` for a link to the handler's own endpoint. It needs Nette's `LinkGenerator` first, otherwise it throws `Nette\InvalidStateException`. Add a `setup` line to the handler service: ```yaml services: diff --git a/docs/guide/openapi.md b/docs/guide/openapi.md index e88a0f16a..7328a9be0 100644 --- a/docs/guide/openapi.md +++ b/docs/guide/openapi.md @@ -56,7 +56,7 @@ The document is created by small builders in `Tomaj\NetteApi\OpenApi`, each resp |---|---| | `SpecBuilder` | whole document: info, servers, components, paths (filters APIs by version) | | `PathBuilder` | paths and operations (summary, tags, parameters, request body, security, responses) | -| `ParameterBuilder` | query and cookie parameters | +| `ParameterBuilder` | query, cookie, path and header parameters; path and header come from [typed input](/guide/typed-input) | | `RequestBodyBuilder` | JSON, raw, form and multipart request bodies | | `ResponseBuilder` | error responses and their schemas, responses from handler outputs | | `SecuritySchemeBuilder` | security schemes and requirements from authorizations (override `createScheme()`) | diff --git a/docs/guide/outputs.md b/docs/guide/outputs.md index 624c37bfa..6de78a67d 100644 --- a/docs/guide/outputs.md +++ b/docs/guide/outputs.md @@ -88,4 +88,4 @@ If the endpoint has outputs, a `404` you return must match one too, or validatio ### Can I use Fractal transformers? -Yes. `BaseHandler` creates a Fractal `Manager`, available as `$this->getFractal()`, and accepts an optional `ScopeFactoryInterface` in the constructor. See [Handlers](/guide/handlers#the-methods). +Yes. `BaseHandler` (and so `TypedHandler`) creates a Fractal `Manager`, available as `$this->getFractal()`, and accepts an optional `ScopeFactoryInterface` in the constructor. See [Handlers](/guide/handlers#the-methods). diff --git a/docs/guide/params.md b/docs/guide/params.md index d90866374..14ebbbab0 100644 --- a/docs/guide/params.md +++ b/docs/guide/params.md @@ -7,6 +7,8 @@ description: Declare and validate input in Nette API - GET, POST, PUT, cookie, f `params()` returns the inputs of the endpoint. `ApiPresenter` reads and validates all of them before `handle()` runs, and `handle()` gets the values keyed by name. +Input can be declared in two equal ways: with `params()`, as described on this page, or as properties of a typed DTO read by `TypedHandler::handleDto()`. Both produce these `InputParam` objects and share validation, OpenAPI and the console. [Typed input (DTO)](/guide/typed-input) helps you choose, and [params() and DTO side by side](/guide/input-styles) shows the same endpoints in both styles. + ## Param classes @@ -16,6 +18,9 @@ description: Declare and validate input in Nette API - GET, POST, PUT, cookie, f | `GetInputParam` | query string | supports types and `setMulti()` | | `PostInputParam` | form body, `$_POST` | supports types and `setMulti()` | | `PutInputParam` | form-encoded body of any method | no type conversion, but a type is still checked: `INTEGER` rejects even `"12"`, so use `STRING` or no type | +| `PathInputParam` | a named `{placeholder}` in the endpoint URL | always required, see [below](#path-header-and-body-params) | +| `HeaderInputParam` | HTTP header, case-insensitive | see [below](#path-header-and-body-params) | +| `BodyInputParam` | one field of a JSON, form or multipart body | see [below](#path-header-and-body-params) | | `CookieInputParam` | cookie | no type conversion, but a type is still checked: `INTEGER` rejects even `"12"`, so use `STRING` or no type | | `FileInputParam` | uploaded file, `$_FILES` | `setMulti()` for several files | | `RawInputParam` | the whole request body as a string | `setMulti()` throws | @@ -56,6 +61,25 @@ All params share a fluent API: In 3.x `?limit=abc` with `INTEGER` is not an error: the value is converted to `null` before validation, so an optional param passes and a required one answers `Field is required`. Always handle `null` in `handle()`. The [params example](/examples/params-validation) tests this. ::: +## Path, header and body params + +`PathInputParam` reads a value from the endpoint URL. Declare the placeholder in the endpoint action with `{name}`, for example `users/{id}/detail`, as described in [Typed input](/guide/typed-input#path-values-and-url-templates). The param is always required and its OpenAPI placeholder has the same name. `HeaderInputParam` reads a request header, case-insensitively. `BodyInputParam` reads one field of a JSON object, a URL-encoded form or a multipart body, and `setContentTypes()` lists the media types it accepts. A typed DTO generates the same three classes from `#[Path]`, `#[Header]` and `#[Body]`, and `params()` can declare them directly: + +```php +public function params(): array +{ + return [ + (new PathInputParam('id', InputType::INTEGER))->setRequired(), + new HeaderInputParam('X-Request-Id', InputType::STRING), + (new BodyInputParam('email', InputType::STRING)) + ->setRequired() + ->setContentTypes(['application/json', 'application/x-www-form-urlencoded']), + ]; +} +``` + +OpenAPI emits them as `in: path`, `in: header` and as fields of the `requestBody`. + ## JSON body `JsonInputParam` takes a JSON schema as a string and validates the decoded body against it: diff --git a/docs/guide/presenter.md b/docs/guide/presenter.md index 177dd5fa3..e24a978be 100644 --- a/docs/guide/presenter.md +++ b/docs/guide/presenter.md @@ -12,11 +12,11 @@ description: 'The exact order of steps in Nette API ApiPresenter::run(), from CO | Step | Code | Exit | | --- | --- | --- | | 1. CORS headers | `sendCorsHeaders()` | | -| 2. Endpoint | `$this->apiDecider->getApi(...)` | `404` through `DefaultHandler` and `handleNotFound()` | +| 2. Endpoint | `$this->apiDecider->getApi(...)`, then `matchPath(...)` for `{name}` URLs | `404` through `DefaultHandler` and `handleNotFound()` | | 3. Rate limit | `checkRateLimit($rateLimit)` | `429`, not logged | | 4. Read params | `new ParamsProcessor($handler->params())` | | | 5. Authorization | `checkAuth($authorization, $params)` | `401` or `500`, not logged | -| 6. Param errors | `errorHandler->handleInputParams()` | `400`, not logged | +| 6. Param errors | `errorHandler->handleUnsupportedMediaType()`, `errorHandler->handleInputParams()` | `415` of a typed handler, logged; `400`, not logged | | 7. Handler | `$handler->handle($params)` | exception: `500` | | 8. Output check | `$output->validate($response)` | no match: `500` | | 9. Logger | `logRequest()` | | diff --git a/docs/guide/problem-details.md b/docs/guide/problem-details.md index 815bc8f44..c7f3d07f7 100644 --- a/docs/guide/problem-details.md +++ b/docs/guide/problem-details.md @@ -44,6 +44,7 @@ Keep only one error handler service: with two, Nette DI cannot autowire `ErrorHa | `authorized()` is false, `handleAuthorization()` | `401` | `unauthorized` | `getErrorMessage()` | | | unknown endpoint, `handleNotFound()` | `404` | `not-found` | `Unknown api endpoint` | | | rate limit reached, `handleRateLimit()` | `429` | `rate-limited` | `Too many requests.`, plus `Retry after N seconds.` when known | `limit`, `retryAfter` when known | +| body content type not accepted, `handleUnsupportedMediaType()` | `415` | `unsupported-media-type` | the received type and the accepted types | | | exception in the handler, `handle()` | `500` | `internal-error` | the message, only with error details on | | | exception in `authorized()`, `handleAuthorizationException()` | `500` | `internal-error` | the message, only with error details on | | | output does not match, `handleSchema()` | `500` | `invalid-output` | none | `outputErrors`, only with error details on | diff --git a/docs/guide/typed-input-body.md b/docs/guide/typed-input-body.md new file mode 100644 index 000000000..c0b56df0d --- /dev/null +++ b/docs/guide/typed-input-body.md @@ -0,0 +1,164 @@ +--- +title: 'Typed input: body, files and content types' +description: 'Body fields of a typed DTO in Nette API: nested objects and lists, JSON, form and multipart content types, Consumes, 415 and file uploads.' +--- + +# Typed input: body, files and content types + +This page covers the body fields of a typed DTO: nested objects and lists, the JSON, form and multipart content types, `#[Consumes]` and file uploads. The basics are in [Typed input (DTO)](/guide/typed-input). + +## POST with a nested DTO and an array + +```php +final readonly class AddressInput +{ + public function __construct( + #[Body] + #[Length(min: 1, max: 120)] + public string $street, + + #[Body] + #[Pattern('/^[0-9]{5}$/')] + public string $postalCode, + ) { + } +} + +final readonly class ItemInput +{ + public function __construct( + #[Body] + public string $sku, + + #[Body] + #[Range(min: 1)] + public int $quantity, + ) { + } +} + +final readonly class CreateOrderInput +{ + /** @param list $items */ + public function __construct( + #[Body] + #[Email] + public string $customerEmail, + + #[Body] + public AddressInput $address, + + #[Body] + #[Length(min: 1, max: 50)] + public array $items, + + #[Body] + public ?DateTimeImmutable $deliveryAt = null, + ) { + } +} +``` + +JSON request body: + +```json +{ + "customerEmail": "ada@example.com", + "address": {"street": "Main 1", "postalCode": "81101"}, + "items": [ + {"sku": "BOOK-1", "quantity": 2}, + {"sku": "PEN-2", "quantity": 1} + ], + "deliveryAt": "2026-11-06T14:30:00+01:00" +} +``` + +The DTO mapper creates `AddressInput` and both `ItemInput` objects recursively. `list` is required PHPDoc for an array of DTOs; `list`, `list`, `list` and `list` are supported for scalar arrays. The usual spellings are read: `list`, `non-empty-list`, `T[]`, with `|null` or a leading `?` (nullability comes from the PHP type), and `@phpstan-param` or `@psalm-param` instead of `@param`. A description after the type is fine (`@var list Names of the things`). An item is one non-nullable type, so `list` and `list` are compile-time errors; use an item DTO. Associative arrays, unions other than nullable types, `mixed`, `object` and untyped arrays are rejected when the container is compiled, not halfway through a request. A list default is checked item by item at the same time, so `@param list` with the default `['x']` does not compile. + +The same DTO works with URL-encoded form fields, and with multipart fields when it has a `#[File]` property or `#[Consumes('multipart/form-data')]`. Nested fields use PHP bracket notation, such as `address[street]` and `items[0][sku]`; `deliveryAt` keeps the same RFC 3339 string. Body parsing depends on the content type, not on a JSON schema. + +## Body content types + +A `TypedHandler` with body fields accepts both **`application/json`** and **`application/x-www-form-urlencoded`** by default. If its DTO contains a `#[File]` property, the defaults are **`application/json`** and **`multipart/form-data`**: multipart replaces URL-encoded form, because URL-encoded form cannot carry files, and files are uploaded together with the body fields. The content type is matched without parameters, so `application/json; charset=utf-8` is accepted. JSON is always read as UTF-8: another `charset`, such as `application/json; charset=ISO-8859-1`, is a `400` instead of being decoded wrongly (`utf-8`, its common spelling `utf8` and `us-ascii` are accepted). A body that arrives without any `Content-Type` is a `415` even when every field is optional, because it would otherwise be dropped silently. + +OpenAPI advertises the same choices in `requestBody.content`: JSON and URL-encoded form, or JSON and multipart when a file is present. When a file is required, only multipart is advertised, because a JSON request could only be answered with `400`. File properties appear only in the `multipart/form-data` schema, because JSON cannot carry a file. A JSON request to a DTO with a required file gets `400` with the file field as the path and the message `File is required and can only be uploaded as multipart/form-data, but the request is application/json`. Body fields are `TYPE_BODY` params and files are `TYPE_FILE` params; there is still only one validation and mapping path. + +### Restrict accepted types with Consumes + +Use the class-level `#[Consumes]` attribute when an endpoint deliberately supports only one representation. It accepts one or more media types: + +```php +#[Consumes('application/json')] +final class CreateOrderHandler extends TypedHandler +{ + public function handleDto(CreateOrderInput $input): ResponseInterface + { + // JSON only + } +} +``` + +```php +#[Consumes('application/json', 'application/x-www-form-urlencoded')] +final class ImportHandler extends TypedHandler +{ + // Explicitly the same two types as the default for a DTO without files. +} +``` + +An upload-only endpoint uses `#[Consumes('multipart/form-data')]`. Restricting to a form type without `multipart/form-data` means that the endpoint cannot receive files; declaring an impossible combination, such as a required `#[File]` with JSON-only consumption, is a container-compilation error. + +A request with another content type is rejected before mapping with **415 Unsupported Media Type**. The 415 is sent after the authorization and the rate limits, so a client without access gets `401` instead, and it is logged by `ApiLoggerInterface` like a handled request. With error details enabled, the message states both the received type and the exact accepted types, for example: + +```json +{ + "status": "error", + "message": "unsupported media type", + "detail": "Content-Type 'text/csv' is not supported for this endpoint. Use one of: application/json, application/x-www-form-urlencoded." +} +``` + +An absent body content type on a request that requires a body receives the same actionable 415 rather than a later null-property error. With Problem Details enabled, status 415 and the same message are used in that format, and its `detail` always names the accepted types. The default envelope hides `detail` when error details are disabled, as it does for field errors. + +### JSON, form and multipart differences + +| Concern | JSON | URL-encoded form / multipart | +| --- | --- | --- | +| Nested DTOs | objects: `{"address":{"street":"Main 1"}}` | bracket names: `address[street]=Main+1` | +| Lists of DTOs | arrays: `"items":[{"sku":"BOOK-1"}]` | indexed names: `items[0][sku]=BOOK-1` | +| Native scalar types | numbers and booleans remain JSON numbers/booleans | values arrive as strings and go through the same strict scalar conversion | +| Null | explicit `null` is allowed only for a nullable property | there is no null literal: omit the field to use null or its default | +| Empty string | an actual string, not null | an actual string, not null | +| Object vs list | `{}` is an object, including when its properties are missing. `[]` is a list and is rejected wherever an object is required, including an empty list. A JSON object is rejected where a list is required | bracket names build an object (`address[street]`); indexed names build a list (`items[0]`) | +| Files | not supported | `multipart/form-data` only | + +For example, JSON `"quantity": 2` stays an integer, while form `quantity=2` becomes an integer only after the complete string passes strict conversion. Neither accepts `2pcs`. JSON `false` and form `remember=0` are valid booleans; an arbitrary non-empty form string is not silently `true`. + +For an optional form value, omit `deliveryAt` instead of sending `deliveryAt=null` or an empty value. A multipart file cannot be replaced with a JSON base64 string; an application needing base64 uploads can keep `BaseHandler` and parse its own raw body. + +PHP reads multipart bodies only for `POST`. A `multipart/form-data` body sent with `PUT` or `PATCH` is not parsed by PHP, so the endpoint answers `400` with `multipart/form-data is only parsed by PHP for POST requests, but this one is PUT. Send it with POST, or use application/json`. Send uploads and multipart forms with `POST`. A URL-encoded form with more fields than PHP's `max_input_vars` (1000 by default) is a `400` `Too many form fields`, for `POST` as well as for `PUT` and `PATCH`. PHP cuts a multipart `POST` that has more fields before the application sees it, and that cannot be told from a complete one: raise `max_input_vars` or send JSON for such forms. + +## Forms and cookie-authenticated endpoints + +A URL-encoded form is a "simple" cross-site request: a page on any website can submit it to your API together with the visitor's cookies and without a CORS preflight, which a JSON body cannot do. A DTO with body fields accepts a form by default, so an endpoint authenticated only by a session cookie, or by the address of the client, can be reached by such a cross-site form. Restrict it to JSON with `#[Consumes('application/json')]` and keep `SameSite` on the cookie. Endpoints authenticated by a bearer token or an API key header are not affected, because a browser form cannot set those headers. + + +## File upload + +```php +final readonly class AvatarInput +{ + public function __construct( + #[Body] + #[Length(min: 1, max: 80)] + public string $displayName, + + #[File(description: 'PNG or JPEG image')] + public FileUpload $avatar, + ) { + } +} +``` + +`FileUpload` is the library's typed upload value object. It exposes the original name, client content type, temporary path, size and upload error; it does not trust the client content type or move the file automatically. `?FileUpload` means an optional upload and `list` accepts several files in one field. Check the upload error, size and real type before storing it, exactly as with `FileInputParam`. Upload errors such as `UPLOAD_ERR_INI_SIZE` are not turned into validation errors; the `FileUpload` carries them in `error`. Only a missing file is: no entry, or `UPLOAD_ERR_NO_FILE` with an empty name, and for `list` every slot being `UPLOAD_ERR_NO_FILE`. Upload requests must use `POST`, see above. `#[File]` belongs on the input DTO of the handler; a `#[File]` inside a nested DTO or a list of DTOs is a compile-time error, because PHP keeps nested uploads in a separate `$_FILES` tree and body fields must never be read as upload metadata. + diff --git a/docs/guide/typed-input-conversion.md b/docs/guide/typed-input-conversion.md new file mode 100644 index 000000000..e186c0e77 --- /dev/null +++ b/docs/guide/typed-input-conversion.md @@ -0,0 +1,182 @@ +--- +title: 'Typed input: conversion, casts and constraints' +description: 'How a typed DTO in Nette API converts values strictly, runs custom casters and validates with Range, Length, Pattern, Email and custom constraints.' +--- + +# Typed input: conversion, casts and constraints + +This page covers what happens to a value between the request and the DTO property: strict conversion, `#[Cast]` and the constraint attributes. The basics are in [Typed input (DTO)](/guide/typed-input). + +## Strict conversion + +Typed input never relies on PHP's loose scalar casts. + +| Target | Accepted input | +| --- | --- | +| `string` | a string that is valid UTF-8; a query, form, header or path value with other bytes is a `400` `Value must be valid UTF-8` | +| `int` | an integer, or a string matching an optional sign and digits only, within PHP integer range | +| `float` | an integer/float, or a complete decimal or scientific numeric string; NaN and infinity are rejected | +| `bool` | boolean `true`/`false`, integer `1`/`0`, string `'true'`/`'false'`/`'1'`/`'0'` (case-insensitive) | +| backed enum | exactly one of its backing values; int-backed enums use the integer conversion rules | +| `DateTimeImmutable` | an RFC 3339 string with date, time and explicit offset, for example `2026-11-06T14:30:00+01:00` (`T` and `Z` may be lowercase; a leap second such as `23:59:60` is rejected, because PHP cannot represent it) | +| `array` | a list whose items each satisfy the PHPDoc item type | + +A string must be valid UTF-8, so that it can be put into a JSON response: `?q=%E9` (a Latin-1 byte) is a `400` `Value must be valid UTF-8` on the field, not a value whose `Length` or `Pattern` gives a misleading message. A JSON body is decoded as UTF-8 anyway. This is the typed input only; a handler with `params()` keeps accepting any bytes, as before, because changing it would reject requests that work today. + +`?page=1a` for an integer is a `400`, never `1` or `null`. Whitespace is not trimmed implicitly and unknown strings do not become `false`. JSON numbers and booleans retain their types, so a whole number written as a float, `1.0` or `1e2`, is not an integer: a client that serialises whole numbers as floats must send `1` for an integer property. Application normalization belongs in the handler or in a custom constraint, not in surprising global casts. + +A query list uses the PHP bracket form `ids[]=3&ids[]=4`, and OpenAPI names the parameter `ids[]` so generated clients send that form. A comma-separated value uses `Split` instead. Form bodies support PHP bracket names; other nested form encodings are not decoded. A query can carry only scalars, enums and lists of them: a nested DTO or a `list` behind `#[Query]` is a compile-time error, because OpenAPI cannot describe PHP bracket nesting for a generated client. Read nested objects from the body with `#[Body]`. + +DTO mapping supports only the five sources above; an input from another source uses `params()` with a custom `InputParam`. + +## Constraints + +Constraint attributes are in `Tomaj\NetteApi\Validation` and can be combined on one property. They run after successful conversion on the converted value; a constraint on a list validates its length, not its scalar items. + +| Attribute | Applies to | Meaning | +| --- | --- | --- | +| `#[Range(min: 1, max: 100)]` | `int`, `float` | inclusive numeric bounds; either bound may be omitted | +| `#[Length(min: 1, max: 80)]` | `string`, `array` | Unicode character count or list item count; either bound may be omitted; a list over `max` is rejected before its items are mapped | +| `#[Pattern('/^[A-Z]+$/')]` | `string` | complete PCRE match, `$` matches only at the very end because the `D` modifier is added (`/^[0-9]{5}$/` rejects `81101` followed by a newline); an invalid pattern is a compile-time error; the pattern is PCRE, not JavaScript, and it is always checked with PCRE; OpenAPI `pattern` is ECMA 262, so it gets `pattern` only when the expression means the same there, and the whole PCRE pattern (delimiters and flags included) otherwise as the extension `x-pattern`; that plain subset is ASCII literals, escaped punctuation, `\n`, `\r`, `\t`, classes of literals and ranges (also with `\-`), groups, lookahead, alternation, anchors and quantifiers, with no flag other than `u` and `D`, and `\d`, `\w` and `\b` only without `u`, because PCRE reads them as Unicode with `u` and JavaScript does not; everything else goes to `x-pattern`, among it the dot, negated classes, `\s`, `\D`, `\W`, `\p{L}`, `\x`, back references, named groups, lookbehind, non-ASCII characters, possessive quantifiers, atomic groups, inline flags and flags such as `i` | +| `#[Email]` | `string` | valid email address | + +Validation collects all field errors rather than stopping at the first one; a request reports at most the first 100 errors in total, nested lists included, and the rest of the body is not checked. Then comes the note `Only the first 100 errors are reported, the rest of the request was not checked` under the key `body`, only when something was actually left unchecked. Messages state the actual limits, for example `Value must have between 1 and 50 items` instead of a generic `Invalid value`. + +### Custom constraints + +A custom constraint implements `ConstraintInterface` and is also a PHP attribute: + +```php +interface ConstraintInterface +{ + public function validate(mixed $value, ConstraintContext $context): ?string; +} +``` + +Return `null` for success or one developer-facing message for failure. `ConstraintContext` exposes the property path, the DTO class and `value('sibling')` for other converted properties of the same DTO; defaults are checked at container compilation with all sibling defaults, and a sibling without a default is `null` there; constraints must not throw for ordinary invalid client input. Custom constraints have no OpenAPI representation unless the application extends the OpenAPI builders. + +### Constraints on list items + +A constraint on a list validates the list, so there are no per-item constraints for `list` or `list`. To check every item, write a custom constraint that loops over the list, or use a list of small item DTOs, which validates each item and reports it as `items[1].quantity`. + +## Custom conversions with Cast + +Use `#[Cast]` when a field has an application-specific textual representation. It names a caster class and optionally passes constructor arguments: + +```php +interface CasterInterface +{ + public function cast(mixed $value): mixed; +} + +final class CastException extends RuntimeException +{ +} +``` + +Casters are in `Tomaj\NetteApi\Input`, including `DateFormat`, `UnixTimestamp` and `Split`. The caster runs **instead of** the built-in conversion for that property. It runs first, returns the property's declared value, and only then do `Range`, `Length`, `Pattern`, `Email` and custom constraints run on that cast value. Nested paths still work exactly as elsewhere. + +A caster reports invalid client input by throwing `Tomaj\NetteApi\Input\CastException` with a clear message. It becomes a 400 in the normal error envelope under the property path: + +```json +{ + "status": "error", + "message": "wrong input", + "detail": { + "issuedOn": ["Date must match d.m.Y, for example 24.12.2026"] + } +} +``` + +Other exceptions are programmer/server errors and are not disguised as client validation errors. Container compilation verifies that the caster class exists, is instantiable, implements `CasterInterface`, accepts the declared attribute arguments and has a native `cast()` return type identical to the property type (or a documented covariant class subtype). A `list` caster must declare `array` with matching list-item PHPDoc. This check is limited to native declarations; `mixed` is not accepted as a caster return type. An incompatible caster fails during compilation, not on the first request. + +### OpenAPI schema hints + +A caster can optionally implement `OpenApiCasterInterface` alongside `CasterInterface`: + +```php +interface OpenApiCasterInterface +{ + /** @return array{type?: string, format?: string, example?: mixed} */ + public function openApiSchema(): array; +} +``` + +The returned `type`, `format` and `example` describe the **wire value**, not the resulting PHP object. Without this optional interface, OpenAPI uses a string schema and the DTO description/example can document the format. A caster never changes runtime validation through its schema hint. + +### Built-in casters and a Czech date + +`DateFormat`, `UnixTimestamp` and `Split` cover the common non-default representations: + +| Caster | Example input | Result | +| --- | --- | --- | +| `#[Cast(DateFormat::class, 'd.m.Y')]` | `'24.12.2026'` | `DateTimeImmutable` at midnight, rejecting impossible dates and trailing input | +| `#[Cast(UnixTimestamp::class)]` | `1798185600` or `'1798185600'` | `DateTimeImmutable` from seconds since Unix epoch | +| `#[Cast(Split::class, ',')]` | `'red,green,blue'` | `list` (always strings: a `list` property needs a caster of its own); no implicit trimming or removal of empty items | + +```php +final readonly class IssueInput +{ + public function __construct( + #[Body] + #[Cast(DateFormat::class, 'd.m.Y')] + public DateTimeImmutable $issuedOn, + ) { + } +} +``` + +The `DateFormat('d.m.Y')` schema hint is `{type: string, example: '24.12.2026'}`. Only `DateFormat('Y-m-d')` adds `format: date`, because OpenAPI `date` means the RFC 3339 full date. A NUL byte or any other unparsable value is a `400` at the field, not an exception. + +### CSV to list<string> + +```php +final readonly class ReportInput +{ + /** @param list $columns */ + public function __construct( + #[Query] + #[Cast(Split::class, ',')] + public array $columns = [], + ) { + } +} +``` + +In OpenAPI the property is one string with the example `red,green,blue`, and the console shows one text input. `?columns=id,createdAt,total` becomes `['id', 'createdAt', 'total']`. `Split` returns an empty list for an omitted optional property only through the property's normal default; an explicitly present empty string produces `['']`, which a constraint can reject. + +### Decimal string to a Money value object + +A custom caster class can construct an application value object. The following example intentionally handles a comma decimal separator without using a floating-point conversion: + +```php +final readonly class DecimalMoneyCaster implements CasterInterface, OpenApiCasterInterface +{ + public function cast(mixed $value): Money + { + if (!is_string($value) || !preg_match('/^(0|[1-9][0-9]*),([0-9]{2})$/D', $value, $m)) { + throw new CastException('Money must use a comma and exactly two decimal places, for example 12,50'); + } + + return Money::fromMinorUnits(((int) $m[1]) * 100 + (int) $m[2], 'EUR'); + } + + public function openApiSchema(): array + { + return ['type' => 'string', 'example' => '12,50']; + } +} + +final readonly class PriceInput +{ + public function __construct( + #[Body] + #[Cast(DecimalMoneyCaster::class)] + public Money $price, + ) { + } +} +``` + +`12,50` becomes `Money` and a subsequent custom `PositiveMoney` constraint receives that `Money` object. `12.50`, `1a` and an array produce a 400 at `price` with the caster's message. Currency-specific formatting remains in the application caster rather than becoming another global scalar rule. Because the caster replaces the built-in conversion, `Money` is never compiled as a transport DTO: it can have a private constructor and a static factory, and the compiler only checks that `cast()` declares a `Money` return type. Named caster arguments such as `#[Cast(MyCaster::class, suffix: 'x')]` keep their names in the compiled container. + diff --git a/docs/guide/typed-input.md b/docs/guide/typed-input.md new file mode 100644 index 000000000..9d3d153b4 --- /dev/null +++ b/docs/guide/typed-input.md @@ -0,0 +1,290 @@ +--- +title: Typed input (DTO) +description: 'Typed request DTOs in Nette API: Query, Path, Header, Body and File attributes, required values, errors, OpenAPI and the API console. The second, equal way to declare handler input next to params().' +--- + +# Typed input (DTO) + +The classes on this page are part of Nette API 4.0. A runnable project is in [`examples/typed-input`](/examples/typed-input). + +A typed input DTO keeps the request contract next to the values a handler uses. Attributes describe where each value comes from, property types describe its PHP type, and constraint attributes describe validation. The same declaration feeds validation, OpenAPI and the API console. + +More on the DTO style: [body, files and content types](/guide/typed-input-body), [conversion, casts and constraints](/guide/typed-input-conversion). + +## params() or a DTO + +A handler declares its input in one of two equal ways. Both are fully supported, share registration, authorization, rate limits, outputs, OpenAPI and the console, and can be mixed freely in one application. + +| | `params()` | Typed DTO | +| --- | --- | --- | +| Handler | `BaseHandler` with `params()` and `handle(array $params)` | `TypedHandler` with `handleDto(SomeInput $input)` | +| You declare | a list of `InputParam` objects | a readonly class with attributes on its constructor properties | +| The handler gets | an array of validated values | a typed object | +| Conversion | the `InputType` conversion of [Input params](/guide/params) | the strict conversion of [typed input](/guide/typed-input-conversion) | +| Nested bodies | `JsonInputParam` with a JSON schema | nested DTOs and lists of DTOs, validated recursively | +| A custom input source | any `InputParam` subclass | not available, there are five source attributes | + +Pick `params()` when the endpoint relies on its looser conversion, on a custom `InputParam` or on manual parsing of an unusual body. Pick a DTO when you want typed values, nested bodies, cross-field constraints or the whole request contract in one class. Neither style is deprecated, and choosing one for an endpoint does not affect any other endpoint. [params() and DTO side by side](/guide/input-styles) shows the same endpoint written in both styles. + +`TypedHandler` turns the DTO declaration into the same `InputParam` objects that `params()` returns. + +## The smallest handler + +Extend `TypedHandler` and declare exactly one non-nullable DTO parameter on `handleDto()`. The class of the `handleDto()` parameter is the input DTO; it does not need to be repeated in an attribute or configuration. + +```php +namespace App\Api; + +use Tomaj\NetteApi\Handlers\TypedHandler; +use Tomaj\NetteApi\Input\Query; +use Tomaj\NetteApi\Response\JsonApiResponse; +use Tomaj\NetteApi\Response\ResponseInterface; +use Tomaj\NetteApi\Validation\Range; + +final readonly class ListUsersInput +{ + public function __construct( + #[Query(description: 'Page number')] + #[Range(min: 1)] + public int $page = 1, + + #[Query] + public ?UserStatus $status = null, + ) { + } +} + +final class ListUsersHandler extends TypedHandler +{ + public function handleDto(ListUsersInput $input): ResponseInterface + { + return new JsonApiResponse(200, [ + 'page' => $input->page, + 'status' => $input->status?->value, + 'users' => [], + ]); + } +} +``` + +`GET /api/v1/users/list?page=2&status=active` produces a `ListUsersInput` with an integer `page` and a `UserStatus` enum. `TypedHandler` implements `handle(array $params)` as final; application code writes only `handleDto()`. + +Constructor dependencies, `summary()`, `description()`, `outputs()`, tags and registration work as for `BaseHandler`. Endpoint and authorization attributes are independent of input attributes and can be used together. + +## Source attributes + +Attributes are in `Tomaj\NetteApi\Input` and target promoted constructor properties. Each promoted property has exactly one source attribute. The external name defaults to the property name; pass a name to override it. `description` and repeatable `examples` become the description and examples of the generated `InputParam`. + +| Attribute | Source | Generated parameter type | +| --- | --- | --- | +| `#[Query]` | query string | `InputParam::TYPE_GET`, OpenAPI `in: query` | +| `#[Path]` | matched endpoint path | `InputParam::TYPE_PATH`, OpenAPI `in: path` | +| `#[Header]` | HTTP header | `InputParam::TYPE_HEADER`, OpenAPI `in: header` | +| `#[Body]` | a field in JSON, form or multipart body | `InputParam::TYPE_BODY`, part of `requestBody` | +| `#[File]` | uploaded file | `InputParam::TYPE_FILE`, multipart `requestBody` | + +Every DTO property becomes one `MappedInputParam`, an `InputParam` that validates and maps through the DTO metadata. Code that inspects `params()` checks `getType()`, not a concrete class. + +For example, `#[Header('X-Request-Id')] public ?string $requestId = null` reads `X-Request-Id`, not `requestId`. Header lookup is case-insensitive. A `#[Path]` name starts with a letter or an underscore and has letters, digits and underscores, because it is written as a `{name}` segment; a `#[Header]` name uses dashes, not underscores (`X-Request-Id`, not `X_Request_Id`), because PHP exposes header names with dashes. Anything else is a compile-time error with the corrected name. A path or header value is one string, so a native list or nested DTO there is a compile-time error; split it with a caster, for example `#[Header('X-Tags')] #[Cast(Split::class, ',')] public array $tags`. + +`PathInputParam` and `HeaderInputParam` are also public for handlers that use `params()`, see [Input params](/guide/params#path-header-and-body-params). + +Do not use `#[Header]` for a header that a proxy sets or strips to carry trust, such as `X-Forwarded-User`. PHP and web servers map `X_Request_Id` and `X-Request-Id` to the same name, so a client can send a look-alike. Authenticate such values in the proxy and drop the client's copy there. The `Authorization` header is also read from `REDIRECT_HTTP_AUTHORIZATION`, which Apache with CGI or FastCGI sets after a rewrite such as `RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]`. `BearerTokenAuthorization` reads it the same way, so a token that reaches `#[Header('Authorization')]` also reaches the authorization. Other headers are read from the `HTTP_*` server variables. + +### Path values and URL templates + +A path value is declared in the endpoint URL with `{name}`, for example `users/{id}/detail`. It is required, it cannot be nullable or have a default, and its OpenAPI path placeholder has the same name. A missing or undeclared path parameter is a container-compilation error. Static endpoint URLs work unchanged. A path value is one URL segment: the path is URL-decoded before it is matched, so an encoded slash (`%2F`) is read as a separator and the endpoint is not found. Send a value that can contain `/` in the query or in the body. + +Register the template as the action of the endpoint, in any of the usual ways: + +```yaml +api: + endpoints: + - {method: GET, version: 1, package: users, action: '{id}/detail', handler: App\Api\UserDetailHandler} +``` + +```php +#[Get(1, 'users', '{id}/detail')] +final class UserDetailHandler extends TypedHandler +``` + +```php +$apiDecider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), new UserDetailHandler(), new NoAuthorization()); +``` + +The route has to let the extra segment through, as the one in the [typed input example](/examples/typed-input) does: `/api/v/[/][/]`. A request is looked up among the static endpoints first and then among the templates. If two templates match one URL, the request fails with a `LogicException` that names both, so make a static segment differ. + +### Required values and defaults + +A non-nullable property without a default is required. A nullable property or a property with a default is optional. A missing nullable value becomes `null`; a missing value with a default uses that default. This also sets `required` in OpenAPI. + +Required path parameters cannot be nullable or have a default. An optional body field accepts an omitted field, while an explicit JSON `null` is accepted only for a nullable property. An empty string is not silently converted to `null`. A default is `null`, a scalar, an array or a backed enum case; an object default such as `= new Inner()` is a compile-time error, because defaults are stored in the compiled container. Use `= null` and create the object in the handler. + +## Complete request example + +### GET with query, path and header + +```php +final readonly class UserDetailInput +{ + public function __construct( + #[Path] + #[Range(min: 1)] + public int $id, + + #[Query] + #[Range(min: 1, max: 100)] + public int $limit = 20, + + #[Query] + public ?UserStatus $status = null, + + #[Header('X-Request-Id')] + public ?string $requestId = null, + ) { + } +} +``` + +Request: + +```http +GET /api/v1/users/42/detail?limit=10&status=active HTTP/1.1 +X-Request-Id: req-01J8Y7N6R9 +``` + +The handler receives `id: 42`, `limit: 10`, `status: UserStatus::Active` and the request ID string. No casts or array-key lookups are needed. + + +A request with a body, a nested DTO and a list is in [body, files and content types](/guide/typed-input-body#post-with-a-nested-dto-and-an-array). + +## Error responses + +The response envelope stays the same as `ParamsProcessor`. The detail key is the field path: dots enter nested DTOs and brackets identify list items. Top-level sources use their external names. + +```json +{ + "status": "error", + "message": "wrong input", + "detail": { + "customerEmail": ["Email must be a valid email address"], + "address.postalCode": ["Value must match the pattern /^[0-9]{5}$/"], + "items[1].quantity": ["Value must be at least 1"], + "deliveryAt": ["DateTime must be a valid RFC 3339 date and time"] + } +} +``` + +When error details are disabled, only `status` and `message` are returned. With Problem Details enabled, the same field paths and messages appear in its input-error extension. Malformed JSON and an unreadable body keep the existing body-parser errors. + +The key `body` also carries the failures of the request body as a whole, such as `Too many form fields`, a wrong JSON charset and the note that only the first 100 errors are reported. A DTO field that is itself called `body` shares that key, so its messages are listed together with those; give the property another external name, for example `#[Body('payload')]`, to keep them apart. + +A missing nested object reports the nested object path. Unknown input fields are ignored, matching ordinary query/form parameter handling; they are not silently mapped to properties. + +## OpenAPI and the API console + +`TypedHandler::params()` exposes generated `InputParam` objects, so the existing console automatically gets labels, required markers, defaults, examples, enum choices and file inputs. The console sends each value to its source: path values are URL-encoded into `{name}` segments, header values become request headers, and body values are sent in the first media type the handler reads that the console can build: JSON with the declared types (a nested DTO field takes JSON text, a list field has one input per item and a DTO item takes JSON text), a URL-encoded form or multipart. A file always means multipart, with bracket names for nested fields. There is no DTO-specific console mode, see [Web console](/guide/console). + +For OpenAPI, query, path and header properties become operation parameters. Body properties are combined into one object schema; nested DTOs and lists become nested schemas. By default `requestBody.content` lists both `application/json` and `application/x-www-form-urlencoded`, or JSON and `multipart/form-data` when the DTO contains a file. `#[Consumes]` limits the list and accepted requests to explicit media types. An operation with a body also documents a `415` response. `nullable: true` appears only on body properties: a query string, a path segment or a header cannot carry `null`, so an optional query or header value is simply absent. A nullable enum lists `null` in its `enum`, as OpenAPI 3.0.3 requires. + +The GET example above contributes this operation fragment (responses and unrelated fields omitted): + +```openapi +parameters: + - name: id + in: path + required: true + schema: {type: integer, minimum: 1} + - name: limit + in: query + required: false + schema: {type: integer, minimum: 1, maximum: 100, default: 20} + - name: status + in: query + required: false + schema: {type: string, enum: [active, disabled]} + - name: X-Request-Id + in: header + required: false + schema: {type: string} +``` + +The POST example contributes: + +```openapi +requestBody: + required: true + content: + application/json: + schema: + type: object + required: [customerEmail, address, items] + properties: + customerEmail: {type: string, format: email} + address: + type: object + required: [street, postalCode] + properties: + street: {type: string, minLength: 1, maxLength: 120} + postalCode: {type: string, pattern: '^[0-9]{5}$'} + items: + type: array + minItems: 1 + maxItems: 50 + items: + type: object + required: [sku, quantity] + properties: + sku: {type: string} + quantity: {type: integer, minimum: 1} + deliveryAt: {type: string, format: date-time, nullable: true} +``` + +JSON schema is generated here only as an OpenAPI output format. Runtime validation uses the recursive DTO mapper and never requires a JSON schema. + +### Long-running workers + +The request values of a typed handler (body, files, path and header values) are kept in static state for the current request. `ApiPresenter::run()` resets it at the start of every request, so PHP-FPM, RoadRunner, FrankenPHP worker mode and Swoole all see only the current request as long as every request goes through `ApiPresenter` and a worker handles one request at a time. Concurrent requests in one process, such as interleaved Swoole coroutines, are not supported, because the state is process-wide. Code that calls a typed handler's `params()` outside the presenter in a worker, for example a test or a CLI command, calls `Tomaj\NetteApi\Input\RequestInput::reset()` and `Tomaj\NetteApi\Params\PathValues::reset()` first. + + +## Security notes + +- **Mapping runs before authorization.** The input is converted and validated before the authorization is checked, and only the answer waits for it: a client without access gets `401`, not field errors. The rate limit still runs first. A caster or a constraint is therefore reachable without a login, so keep them pure and cheap: no database, network or file access. Put `#[Length(max: ...)]` on every list. One request reports at most 100 errors in total, however deeply lists and objects are nested; the rest of the body is not checked. +- **Cap the request body at the web server.** `#[Length(max: ...)]` limits a list before its items are mapped, but the body is decoded first, and a list of small objects takes far more memory in PHP than in the request (up to roughly 70 times for a list of small objects, about 18 times for a list of numbers). Limit the size where the request enters: `client_max_body_size` in nginx, `LimitRequestBody` in Apache, and `post_max_size` and `memory_limit` in PHP. +- **`#[Header]` is not proof of origin.** See the note under [source attributes](#source-attributes). +- **Form bodies and cookies.** A DTO with body fields accepts URL-encoded forms by default, which any website can submit without a CORS preflight. For an endpoint authenticated by a cookie or by the client address, use `#[Consumes('application/json')]`, see [body, files and content types](/guide/typed-input-body#forms-and-cookie-authenticated-endpoints). + +## Example + +`examples/typed-input` follows the same standalone Composer layout and `e2e.sh` CI convention as the other examples (`public/index.php`): + +```text +examples/typed-input/ +├── composer.json +├── README.md +├── e2e.sh +├── config/common.neon +├── public/index.php +└── app/Api/ + ├── ListUsersHandler.php # query, backed enum and defaults + ├── UserDetailHandler.php # path id and X-Request-Id header + ├── CreateOrderHandler.php # JSON/form body, nested DTO and list + ├── AvatarUploadHandler.php # multipart body and FileUpload + └── Input/ # readonly DTOs and UserStatus +``` + +The end-to-end test covers successful JSON, form and multipart requests, defaults, enum conversion, every source attribute, strict rejection of `1a`, nested error paths and the generated OpenAPI document. CI runs it with the other examples. + + +## How it is built + +- **Compile-time metadata.** `NetteApiExtension` reflects DTOs and writes their `InputParam` definitions and mapping metadata into the compiled container. Requests and OpenAPI generation do not reflect DTOs again and need no cache invalidation setup; enum backing types are cached per class. Changing a DTO, its parent class, a trait it uses, a caster, a constraint or an enum rebuilds the container like changing endpoint attributes. Without the DI extension, a small generated-metadata registry is built once per request; no runtime Nette Cache dependency is introduced. +- **One metadata pipeline.** DTO metadata is translated into the existing `InputParam` objects, so validation, OpenAPI and the console have no separate DTO branches. +- **Recursive runtime validation.** It handles JSON, form and multipart consistently and gives exact property paths. A JSON schema is only generated for OpenAPI. +- **Readonly promoted properties only.** DTOs are instantiated once through their constructor and cannot be partially mutated by the mapper. A required constructor parameter that is not a promoted property, and variadic or by-reference parameters, are compile-time errors. +- **Strict, explicit scalar conversion.** Invalid client data is a `400`, not a surprising cast. +- **A small constraint set.** Range, Length, Pattern and Email cover common API contracts; custom constraints cover application rules without a validation framework. +- **JSON and form accepted by default, `Consumes` restricts.** One DTO serves JSON and form clients, and OpenAPI advertises the same media types; when a file is present, multipart replaces URL-encoded form, which cannot carry files. `Consumes` is a class-level attribute like the other endpoint attributes, and its name keeps it apart from the HTTP `Accept` header, which is about responses. +- **`handleDto(Input $input)` as the handler method.** The name states that it is the entry point of the handler, and reflection reads the DTO class from its parameter, so no extra attribute or configuration is needed. +- **`Cast` with `CasterInterface`.** Application formats stay local to a property, constructor arguments cover options such as `d.m.Y`, and `CastException` gives field-path 400 errors. An optional schema-hint interface keeps OpenAPI metadata optional for casters. + diff --git a/docs/index.md b/docs/index.md index f52d297e8..6bc0e8f76 100644 --- a/docs/index.md +++ b/docs/index.md @@ -20,11 +20,11 @@ hero: features: - icon: '' title: Handlers, not presenters - details: Every endpoint is a small class with params(), outputs() and handle(). ApiDecider maps method, version and package to it. + details: Every endpoint is a small class. Declare its input with params() and handle(), or with a typed DTO and handleDto(). ApiDecider maps method, version and package to it. link: /guide/handlers - icon: '' title: Validated input - details: GET, POST, PUT, cookie, file, raw and JSON body params with types, allowed values and JSON schemas. Wrong input answers 400. + details: Query, path, header, cookie, file, form and JSON body input, as params or as typed DTO properties, with types, constraints and JSON schemas. Wrong input answers 400. link: /guide/params - icon: '' title: Authorization and limits @@ -40,9 +40,32 @@ features: -A handler is one class: +A handler is one class. Its input is a list of params or a typed DTO, whichever fits the endpoint: -<<< @/../examples/hello-world/app/Api/HelloHandler.php +::: code-group + +<<< @/../examples/hello-world/app/Api/HelloHandler.php [params()] + +```php [Typed DTO] +final readonly class HelloInput +{ + public function __construct( + #[Query(description: 'Who to greet')] + public string $name = 'world', + ) { + } +} + +final class HelloHandler extends TypedHandler +{ + public function handleDto(HelloInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['message' => 'Hello ' . $input->name . '!']); + } +} +``` + +::: and a few lines of configuration register it as `GET /api/v1/hello`: @@ -55,8 +78,8 @@ The [hello world example](/examples/hello-world) runs exactly this code in CI. ## FAQ diff --git a/docs/site-nav.ts b/docs/site-nav.ts index 1617b9797..44c09cd85 100644 --- a/docs/site-nav.ts +++ b/docs/site-nav.ts @@ -9,24 +9,24 @@ type Labels = Record const en: Labels = { guide: 'Guide', examples: 'Examples', reference: 'Reference', faq: 'FAQ', changelog: 'Changelog', version: '3.x', start: 'Getting started', basics: 'Basics', concepts: 'Concepts', security: 'Security and traffic', docs: 'Documentation tools', more: 'More', - 'getting-started': 'Getting started', architecture: 'Architecture', handlers: 'Handlers', params: 'Input params', outputs: 'Outputs and responses', + 'getting-started': 'Getting started', architecture: 'Architecture', handlers: 'Handlers', params: 'Input: params()', 'typed-input': 'Input: typed DTO', 'typed-input-body': 'Typed DTO: body and files', 'typed-input-conversion': 'Typed DTO: conversion and constraints', 'input-styles': 'params() and DTO side by side', outputs: 'Outputs and responses', authorization: 'Authorization', 'rate-limit': 'Rate limiting', cors: 'CORS', logging: 'Logging', errors: 'Error handling', 'problem-details': 'Problem Details (RFC 9457)', 'di-extension': 'DI extension', attributes: 'Attribute endpoints', openapi: 'OpenAPI', console: 'Web console', links: 'Links and versions', versioning: 'Versions of this documentation', upgrade: 'Upgrade guide', contributing: 'Contributing', overview: 'Overview', 'hello-world': 'Example: hello world', 'params-validation': 'Example: params and validation', auth: 'Example: authorization and rate limit', 'openapi-console': 'Example: OpenAPI and console', 'logging-errors': 'Example: logging and errors', 'cors-ex': 'Example: CORS', 'problem-details-ex': 'Example: Problem Details', 'di-extension-ex': 'Example: DI extension', 'attributes-ex': 'Example: attribute endpoints', layers: 'Layers', 'api-decider': 'ApiDecider and endpoints', presenter: 'ApiPresenter pipeline', - 'custom-authorization': 'Example: custom authorization', 'json-body': 'Example: JSON and raw body', 'file-upload': 'Example: file upload', pagination: 'Example: pagination', versions: 'Example: API versions', 'rate-limit-ex': 'Example: rate limit', testing: 'Example: testing', + 'custom-authorization': 'Example: custom authorization', 'json-body': 'Example: JSON and raw body', 'file-upload': 'Example: file upload', 'typed-input-ex': 'Example: typed input', pagination: 'Example: pagination', versions: 'Example: API versions', 'rate-limit-ex': 'Example: rate limit', testing: 'Example: testing', } const sk: Labels = { guide: 'Príručka', examples: 'Príklady', reference: 'Referencia', faq: 'Časté otázky', changelog: 'Changelog', version: '3.x', start: 'Začíname', basics: 'Základy', concepts: 'Koncepty', security: 'Bezpečnosť a prevádzka', docs: 'Dokumentačné nástroje', more: 'Ďalšie', - 'getting-started': 'Začíname', architecture: 'Architektúra', handlers: 'Handlery', params: 'Vstupné parametre', outputs: 'Výstupy a odpovede', + 'getting-started': 'Začíname', architecture: 'Architektúra', handlers: 'Handlery', params: 'Vstup: params()', 'typed-input': 'Vstup: typované DTO', 'typed-input-body': 'Typované DTO: telo a súbory', 'typed-input-conversion': 'Typované DTO: konverzia a validačné obmedzenia', 'input-styles': 'params() a DTO vedľa seba', outputs: 'Výstupy a odpovede', authorization: 'Autorizácia', 'rate-limit': 'Obmedzenie požiadaviek', cors: 'CORS', logging: 'Logovanie', errors: 'Spracovanie chýb', 'problem-details': 'Problem Details (RFC 9457)', 'di-extension': 'DI rozšírenie', attributes: 'Endpointy z atribútov', openapi: 'OpenAPI', console: 'Webová konzola', links: 'Odkazy a verzie', versioning: 'Verzie tejto dokumentácie', upgrade: 'Návod na upgrade', contributing: 'Prispievanie', overview: 'Prehľad', 'hello-world': 'Príklad: hello world', 'params-validation': 'Príklad: parametre a validácia', auth: 'Príklad: autorizácia a obmedzenie požiadaviek', 'openapi-console': 'Príklad: OpenAPI a konzola', 'logging-errors': 'Príklad: logovanie a chyby', 'cors-ex': 'Príklad: CORS', 'problem-details-ex': 'Príklad: Problem Details', 'di-extension-ex': 'Príklad: DI rozšírenie', 'attributes-ex': 'Príklad: endpointy z atribútov', layers: 'Vrstvy', 'api-decider': 'ApiDecider a endpointy', presenter: 'Spracovanie v ApiPresenteri', - 'custom-authorization': 'Príklad: vlastná autorizácia', 'json-body': 'Príklad: JSON a surové telo', 'file-upload': 'Príklad: nahrávanie súborov', pagination: 'Príklad: stránkovanie', versions: 'Príklad: verzie API', 'rate-limit-ex': 'Príklad: obmedzenie požiadaviek', testing: 'Príklad: testovanie', + 'custom-authorization': 'Príklad: vlastná autorizácia', 'json-body': 'Príklad: JSON a surové telo', 'file-upload': 'Príklad: nahrávanie súborov', 'typed-input-ex': 'Príklad: typovaný vstup', pagination: 'Príklad: stránkovanie', versions: 'Príklad: verzie API', 'rate-limit-ex': 'Príklad: obmedzenie požiadaviek', testing: 'Príklad: testovanie', } function nav(l: Labels, p: string): DefaultTheme.NavItem[] { @@ -51,7 +51,7 @@ function sidebar(l: Labels, p: string): DefaultTheme.SidebarItem[] { const e = (k: string, label = k) => ({ text: l[label], link: `${p}/examples/${k}` }) return [ { text: l.start, items: [g('getting-started'), g('di-extension'), g('attributes')] }, - { text: l.basics, items: [g('handlers'), g('params'), g('outputs'), g('errors'), g('problem-details')] }, + { text: l.basics, items: [g('handlers'), g('params'), g('typed-input'), g('typed-input-body'), g('typed-input-conversion'), g('input-styles'), g('outputs'), g('errors'), g('problem-details')] }, { text: l.concepts, items: [g('architecture'), g('layers'), g('api-decider'), g('presenter')] }, { text: l.security, items: [g('authorization'), g('rate-limit'), g('cors'), g('logging')] }, { text: l.docs, items: [g('openapi'), g('console'), g('links')] }, @@ -59,7 +59,7 @@ function sidebar(l: Labels, p: string): DefaultTheme.SidebarItem[] { text: l.examples, items: [ { text: l.overview, link: `${p}/examples/` }, - e('hello-world'), e('params-validation'), e('auth'), e('cors', 'cors-ex'), e('openapi-console'), e('logging-errors'), e('problem-details', 'problem-details-ex'), e('di-extension', 'di-extension-ex'), e('attributes', 'attributes-ex'), + e('hello-world'), e('params-validation'), e('typed-input', 'typed-input-ex'), e('auth'), e('cors', 'cors-ex'), e('openapi-console'), e('logging-errors'), e('problem-details', 'problem-details-ex'), e('di-extension', 'di-extension-ex'), e('attributes', 'attributes-ex'), e('custom-authorization'), e('json-body'), e('file-upload'), e('pagination'), e('versions'), e('rate-limit', 'rate-limit-ex'), e('testing'), ], }, diff --git a/docs/sk/api/reference.md b/docs/sk/api/reference.md index 4c1594047..01b651fa4 100644 --- a/docs/sk/api/reference.md +++ b/docs/sk/api/reference.md @@ -1,6 +1,6 @@ --- title: Referencia -description: Všetky verejné triedy a rozhrania Nette API 3.x podľa namespace, s jednoriadkovým popisom a odkazom na stránku príručky. +description: Verejné triedy a rozhrania Nette API podľa namespace, s jednoriadkovým popisom a odkazom na stránku príručky. --- # Referencia @@ -11,7 +11,7 @@ Všetky triedy sú pod `Tomaj\NetteApi`. | Trieda | Čo robí | Príručka | | --- | --- | --- | -| `ApiDecider` | register endpointov: `addApi()`, `getApi()`, `getApis()`, `enableGlobalPreflight()` | [Architektúra](/sk/guide/architecture) | +| `ApiDecider` | register endpointov: `addApi()`, `getApi()`, `matchPath()`, `getApis()`, `enableGlobalPreflight()` | [Architektúra](/sk/guide/architecture) | | `Api` | jeden zaregistrovaný endpoint: endpoint, handler, autorizácia, obmedzenie požiadaviek | [Architektúra](/sk/guide/architecture) | | `ApiHolder` | používa ho `ApiDecider`: ako uchováva endpoint pred vytvorením handlera; handler môže byť ešte názov triedy alebo služby | [ApiDecider](/sk/guide/api-decider#tri-sposoby-ako-odovzdat-handler) | | `EndpointIdentifier` / `EndpointInterface` | metóda, verzia, balík, akcia | [Handlery](/sk/guide/handlers#registracia-handlera) | @@ -25,7 +25,7 @@ Všetky triedy sú pod `Tomaj\NetteApi`. | Trieda | Čo robí | Príručka | | --- | --- | --- | -| `Handlers\ApiHandlerInterface`, `BaseHandler` | vaše endpointy | [Handlery](/sk/guide/handlers) | +| `Handlers\ApiHandlerInterface`, `BaseHandler`, `TypedHandler` | vaše endpointy; `TypedHandler` berie DTO | [Handlery](/sk/guide/handlers), [Typovaný vstup](/sk/guide/typed-input) | | `Handlers\OpenApiHandler` | OpenAPI 3.0 dokument | [OpenAPI](/sk/guide/openapi) | | `Handlers\ApiListingHandler` | JSON zoznam endpointov vo vlastnej verzii | [Handlery](/sk/guide/handlers#handlery-ktore-su-sucastou-kniznice) | | `Handlers\AlwaysOkHandler`, `EchoHandler` | health check a testovacie endpointy | [Handlery](/sk/guide/handlers#handlery-ktore-su-sucastou-kniznice) | @@ -36,11 +36,26 @@ Všetky triedy sú pod `Tomaj\NetteApi`. | Trieda | Čo robí | Príručka | | --- | --- | --- | -| `Params\GetInputParam`, `PostInputParam`, `PutInputParam`, `CookieInputParam`, `FileInputParam`, `RawInputParam`, `JsonInputParam` | každá jeden vstup | [Parametre](/sk/guide/params) | +| `Params\GetInputParam`, `PostInputParam`, `PutInputParam`, `PathInputParam`, `HeaderInputParam`, `BodyInputParam`, `CookieInputParam`, `FileInputParam`, `RawInputParam`, `JsonInputParam` | každá jeden vstup | [Parametre](/sk/guide/params) | | `Params\InputParam`, `ParamInterface`, `ParamsProcessor` | základná trieda a spracovanie | [Parametre](/sk/guide/params) | | `Validation\InputValidator`, `JsonSchemaValidator`, `InputType` (enum) | kontroly hodnôt | [Parametre](/sk/guide/params#typy) | | `ValidationResult\ValidationResult(Interface)` | výsledok kontroly | [Parametre](/sk/guide/params) | +## Typovaný vstup (4.0.0) + +| Trieda | Čo robí | Príručka | +| --- | --- | --- | +| `Input\Query`, `Path`, `Header`, `Body`, `File` | atribúty, ktoré určujú, odkiaľ sa property DTO číta | [Typovaný vstup](/sk/guide/typed-input#atributy-zdroja) | +| `Input\Consumes`, `Input\FileUpload` | obmedzí akceptované media typy tela; typovaná hodnota nahraného súboru | [Telo, súbory a content typy](/sk/guide/typed-input-body) | +| `Input\Cast`, `CasterInterface`, `OpenApiCasterInterface`, `CastException` | vlastná konverzia jednej property | [Konverzia](/sk/guide/typed-input-conversion#vlastne-konverzie-cez-cast) | +| `Input\DateFormat`, `UnixTimestamp`, `Split` | vstavané castery | [Konverzia](/sk/guide/typed-input-conversion#vstavane-castery-a-cesky-datum) | +| `Validation\Range`, `Length`, `Pattern`, `Email` | vstavané validačné obmedzenia | [Validačné obmedzenia](/sk/guide/typed-input-conversion#validacne-obmedzenia) | +| `Validation\ConstraintInterface`, `ConstraintContext` | vaše vlastné validačné obmedzenia | [Vlastné validačné obmedzenia](/sk/guide/typed-input-conversion#vlastne-validacne-obmedzenia) | +| `Params\MappedInputParam` | `InputParam` vygenerovaný pre jednu property DTO | [Typovaný vstup](/sk/guide/typed-input) | +| `Input\RequestInput`, `Params\PathValues` | stav požiadavky typovaného handlera, nulovaný v dlho bežiacich workeroch | [Dlho bežiace workery](/sk/guide/typed-input#dlho-beziace-workery) | + +Ostatné triedy namespace `Input` sú mechanika za týmito (kompilátor, mapper, metadáta, schéma a pomocníci konverzie). Nie sú uvedené a nie sú určené na rozširovanie ani na priame volanie. + ## Odpovede a výstupy | Trieda | Čo robí | Príručka | @@ -69,7 +84,7 @@ Všetky triedy sú pod `Tomaj\NetteApi`. | Trieda | Čo robí | Príručka | | --- | --- | --- | | `Logger\ApiLoggerInterface` | log požiadaviek | [Logovanie](/sk/guide/logging) | -| `Link\ApiLink`, `ApiLinkExtension`, `ApiLinkNode` | URL a tag `{apiLink}` | [Odkazy](/sk/guide/links) | +| `Link\ApiLink` (`link()`), `ApiLinkExtension`, `ApiLinkNode` | URL a tag `{apiLink}` | [Odkazy](/sk/guide/links) | | `Component\ApiListingControl`, `ApiConsoleControl`, `ApiConsoleFormFactoryInterface`, `DefaultApiConsoleFormFactory` | webová konzola | [Webová konzola](/sk/guide/console) | | `Misc\ConsoleRequest`, `ConsoleResponse` | cURL požiadavka konzoly | [Webová konzola](/sk/guide/console) | | `Misc\CorsOriginAllowlist` | interné (`@internal`), používa ho `setCorsAllowedOrigins()`; vo 4.0 sa môže zmeniť | [CORS](/sk/guide/cors#povolene-originy) | diff --git a/docs/sk/examples/attributes.md b/docs/sk/examples/attributes.md index 872ca917b..edb0047e2 100644 --- a/docs/sk/examples/attributes.md +++ b/docs/sk/examples/attributes.md @@ -44,6 +44,18 @@ Atribúty a `api: discovery:` sú nové vo verzii 4.0.0. <<< @/../examples/attributes/app/Api/UsersListHandler.php +## Typované vstupné DTO + +`GreetHandler` je `TypedHandler`: rovnaké atribúty `#[Get]` a `#[Authorization]`, vstup je v `GreetInput` namiesto `params()`. + +::: code-group + +<<< @/../examples/attributes/app/Api/GreetHandler.php + +<<< @/../examples/attributes/app/Api/GreetInput.php + +::: + ## Endpoint s akciou <<< @/../examples/attributes/app/Api/UserDetailHandler.php diff --git a/docs/sk/examples/di-extension.md b/docs/sk/examples/di-extension.md index 6c4995cea..14af92594 100644 --- a/docs/sk/examples/di-extension.md +++ b/docs/sk/examples/di-extension.md @@ -36,6 +36,18 @@ API používateľov nastavené iba v sekcii `api:` súboru `config/common.neon`, <<< @/../examples/di-extension/app/Api/UsersListHandler.php +## Typované vstupné DTO + +`GreetHandler` je `TypedHandler` zaregistrovaný v `endpoints:` ako ostatné; jeho vstup je DTO `GreetInput` namiesto `params()`. + +::: code-group + +<<< @/../examples/di-extension/app/Api/GreetHandler.php + +<<< @/../examples/di-extension/app/Api/GreetInput.php + +::: + ## Bootstrap <<< @/../examples/di-extension/app/Bootstrap.php diff --git a/docs/sk/examples/index.md b/docs/sk/examples/index.md index e4f014d57..45b4df63f 100644 --- a/docs/sk/examples/index.md +++ b/docs/sk/examples/index.md @@ -1,6 +1,6 @@ --- title: Príklady -description: 'Šestnásť spustiteľných projektov Nette API testovaných v CI: parametre, JSON telo, súbory, stránkovanie, autorizácia, limity, CORS, verzie, OpenAPI, logovanie, DI rozšírenie a endpointy z atribútov.' +description: 'Sedemnásť spustiteľných projektov Nette API testovaných v CI: parametre, typovaný vstup, JSON telo, súbory, stránkovanie, autorizácia, limity, CORS, verzie, OpenAPI, logovanie, DI rozšírenie a endpointy z atribútov.' --- # Príklady @@ -33,6 +33,7 @@ Ak chcete príklad spustiť proti lokálnemu klonu ako CI, použite z koreňa re { title: 'Vlastná autorizácia', text: 'Vlastný ApiAuthorizationInterface s rolami, používateľ v handleri, token alebo API kľúč.', link: '/sk/examples/custom-authorization' }, { title: 'JSON a surové telo', text: 'JSON telo overené schémou a CSV telo.', link: '/sk/examples/json-body' }, { title: 'Nahrávanie súborov', text: 'Jeden aj viac súborov, overená veľkosť a skutočný typ.', link: '/sk/examples/file-upload' }, + { title: 'Typovaný vstup', text: 'Readonly DTO pre query, path, header, JSON alebo formulár a súbor (potrebuje 4.0.0).', link: '/sk/examples/typed-input' }, { title: 'Stránkovanie', text: 'Typované parametre stránky, povolené hodnoty, odkazy, výstup pre každý kód.', link: '/sk/examples/pagination' }, { title: 'Verzie API', text: 'v1 a v2 jedného endpointu, hlavičky zastarania, OpenAPI pre každú verziu.', link: '/sk/examples/versions' }, { title: 'Obmedzenie požiadaviek', text: 'Predvolený limit na IP, kvóta na API kľúč, #[RateLimit] a endpoint bez limitu.', link: '/sk/examples/rate-limit' }, diff --git a/docs/sk/examples/typed-input.md b/docs/sk/examples/typed-input.md new file mode 100644 index 000000000..3d88c7b9d --- /dev/null +++ b/docs/sk/examples/typed-input.md @@ -0,0 +1,54 @@ +--- +title: 'Príklad: typovaný vstup' +description: 'Spustiteľný príklad Nette API: readonly DTO s query, path, header, JSON alebo formulárovým telom a nahratým súborom.' +--- + +# Príklad: typovaný vstup + +Štyri handlery dedia z `TypedHandler`. DTO na `handleDto()` je kontrakt požiadavky: `#[Query]`, `#[Path]`, `#[Header]`, `#[Body]` a `#[File]`. Rovnaký endpoint objednávky prijme JSON aj formulár. Pozrite [Typovaný vstup](/sk/guide/typed-input). + + + +::: tip Od verzie 4.0.0 +Typované handlery, path a header parametre a `#[Consumes]` sú nové v 4.0.0. +::: + +| Požiadavka | Stav | Čo ukazuje | +| --- | --- | --- | +| `GET /api/v1/users/list` | `200` | `page` má predvolenú hodnotu `1`, `status` je null | +| `GET /api/v1/users/list?page=2&status=active` | `200` | celé číslo a backed enum | +| `GET /api/v1/users/list?page=1a` | `400` | `1a` nie je celé číslo | +| `GET /api/v1/users/42/detail` s `X-Request-Id` | `200` | id z cesty a hlavička | +| `POST /api/v1/orders` JSON | `201` | vnorené DTO a `list` | +| `POST /api/v1/orders` formulár | `201` | to isté DTO, zátvorkové mená | +| `POST /api/v1/orders` neplatné telo | `400` | `items[1].quantity` | +| `POST /api/v1/orders` `text/csv` | `415` | content type mimo predvolenej dvojice | +| `POST /api/v1/orders` PSČ `81101` a nový riadok | `400` | `$` vo vzore končí reťazec | +| `POST /api/v1/avatar` multipart | `201` | `FileUpload` | +| `GET /api/v1/openapi` | `200` | path parameter a oba content typy tela | + +## Query DTO + +<<< @/../examples/typed-input/app/Api/Input/ListUsersInput.php + +<<< @/../examples/typed-input/app/Api/ListUsersHandler.php + +## DTO s cestou a hlavičkou + +<<< @/../examples/typed-input/app/Api/Input/UserDetailInput.php + +<<< @/../examples/typed-input/app/Api/UserDetailHandler.php + +## Nahrávanie súboru + +<<< @/../examples/typed-input/app/Api/Input/AvatarInput.php + +<<< @/../examples/typed-input/app/Api/AvatarUploadHandler.php + +## Registrácia + +Endpoint s cestou je `#[Get(1, 'users', '{id}/detail')]`. Routa je obvyklá, s voliteľným tretím segmentom: + +<<< @/../examples/typed-input/app/RouterFactory.php + +<<< @/../examples/typed-input/config/common.neon diff --git a/docs/sk/faq.md b/docs/sk/faq.md index 807e04e9e..49b1ed79c 100644 --- a/docs/sk/faq.md +++ b/docs/sk/faq.md @@ -33,6 +33,14 @@ V 3.x presenter skončí pred loggerom. Pozrite si [Logovanie](/sk/guide/logging Áno, v novom projekte: chyby podľa RFC 9457 majú jeden strojovo čitateľný tvar. Nie sú predvolené, lebo existujúci klienti čítajú `message`. Pozrite si [Problem Details](/sk/guide/problem-details). +## Mám používať params() alebo typované DTO? + +Ktorékoľvek: sú to dva rovnocenné spôsoby deklarácie vstupu handlera a jedno API ich môže miešať. V stránke [Typovaný vstup (DTO)](/sk/guide/typed-input) je, v čom sa líšia, a [params() a DTO vedľa seba](/sk/guide/input-styles) ukazuje tie isté endpointy v oboch štýloch. + +## Prečo môj typovaný endpoint vracia 415? + +Telo má content type, ktorý handler neprijíma, alebo žiadny. DTO s poľami tela predvolene prijíma JSON a URL-enkódovaný formulár a `#[Consumes]` to mení. Pozrite [telo, súbory a content typy](/sk/guide/typed-input-body). + ## Dá sa API nastaviť bez zoznamu volaní addApi()? Áno, od verzie 4.0.0 cez [DI rozšírenie](/sk/guide/di-extension): jedna neon sekcia `api:` s endpointmi, autorizáciami, obmedzeniami požiadaviek, CORS a formátom chýb, skontrolovaná pri kompilácii kontajnera. @@ -55,4 +63,4 @@ Postupujte podľa [návodu na upgrade](/sk/upgrade) a [changelogu](/sk/changelog ## Je k dispozícii kompletný projekt, ktorý si môžem spustiť? -Áno, 13, testovaných v CI: pozrite si [Príklady](/sk/examples/). +Áno, 17, testovaných v CI: pozrite si [Príklady](/sk/examples/). diff --git a/docs/sk/guide/api-decider.md b/docs/sk/guide/api-decider.md index 23fb0f61f..040361768 100644 --- a/docs/sk/guide/api-decider.md +++ b/docs/sk/guide/api-decider.md @@ -41,7 +41,7 @@ services: | metóda | `'GET'` | porovnáva sa veľkými písmenami | | verzia | `1`, `'1.1'` | uloží sa ako reťazec, nesmie obsahovať `/` | | balík | `'users'` | prvý segment cesty za verziou | -| apiAction | `'detail'` alebo `null` | voliteľný druhý segment | +| apiAction | `'detail'`, `'{id}/detail'` alebo `null` | voliteľný druhý segment; `{name}` z neho robí šablónu URL, pozrite nižšie | `getUrl()` vráti `v1/users/detail`, čo používa [OpenAPI](/sk/guide/openapi) aj konzola. @@ -55,6 +55,12 @@ services: 4. nastaví handleru endpoint, takže fungujú `getEndpoint()` a `createLink()`; 5. bez zhody vráti `DefaultHandler` a `NoAuthorization`, ktoré odpovedia `404 Unknown api endpoint` cez metódu `handleNotFound()` error handlera. +`getApi()` si ponecháva svoje štyri argumenty, takže podtrieda, ktorá ho prekrýva, ďalej funguje, a nájde len endpointy so statickou URL. + +### Endpointy so segmentmi {name} + +Endpoint, ktorého akcia má segmenty `{name}`, napríklad `users/{id}/detail`, potrebuje cestu požiadavky. `ApiPresenter` najprv zavolá `getApi()` a keď ten nič nenájde, zavolá `matchPath($method, $version, $package, $apiAction, $path)`. Statický endpoint teda vždy vyhrá. `matchPath()` porovná cestu so všetkými šablónami danej metódy a verzie, uloží zhodné hodnoty pre properties `#[Path]` a vráti `Api`, alebo `null`, keď nezodpovedá žiadna šablóna. Ak jednej ceste vyhovujú dve šablóny, vyhodí `LogicException`, ktorá ich vymenuje, takže zmeňte statický segment tak, aby sa líšili. Globálny preflight odpovie na `OPTIONS` aj pre cestu, ktorá zodpovedá šablóne. Ako šablónu zaregistrovať a smerovať, je v stránke [Typovaný vstup](/sk/guide/typed-input#hodnoty-z-cesty-a-sablony-url). + `GET /api/v1/users` a `POST /api/v1/users` sú dva endpointy s dvoma handlermi. Nezaregistrovaná verzia, napríklad `/api/v3/users`, je `404`, ako testuje [príklad verzií](/sk/examples/versions). ## Tri spôsoby, ako odovzdať handler diff --git a/docs/sk/guide/architecture.md b/docs/sk/guide/architecture.md index 0627fc562..61feb4b41 100644 --- a/docs/sk/guide/architecture.md +++ b/docs/sk/guide/architecture.md @@ -16,7 +16,7 @@ Každá API požiadavka ide do jedného presentera, `Tomaj\NetteApi\Presenters\A | Presenter | `ApiPresenter` | Spúšťa všetky kroky nižšie. Je `final`. | | Zoznam endpointov | `ApiDecider` | `addApi()` registruje endpointy, `getApi()` nájde ten pre požiadavku. | | Endpoint | `EndpointIdentifier` | Metóda, verzia, balík a voliteľná akcia. | -| Handler | `ApiHandlerInterface`, zvyčajne `BaseHandler` | Deklaruje parametre a výstupy, robí samotnú prácu. | +| Handler | `ApiHandlerInterface`, zvyčajne `BaseHandler` alebo `TypedHandler` | Deklaruje parametre (alebo typované vstupné DTO) a výstupy, robí samotnú prácu. | | Autorizácia | `ApiAuthorizationInterface` | Rozhodne, či požiadavka smie bežať. | | Obmedzenie požiadaviek | `RateLimiterInterface` | Voliteľné, pre každý endpoint. | | Chyby | `ErrorHandlerInterface`, `DefaultErrorHandler` | Zmení zlyhania na JSON odpovede. | diff --git a/docs/sk/guide/attributes.md b/docs/sk/guide/attributes.md index 80123eaa4..f3fcd71bd 100644 --- a/docs/sk/guide/attributes.md +++ b/docs/sk/guide/attributes.md @@ -11,7 +11,9 @@ Atribúty v `Tomaj\NetteApi\Attribute` sú nové vo verzii 4.0.0. Potrebujú [DI S atribútmi zapíšete URL endpointu priamo na triedu handlera. V neone nie je zoznam endpointov, ktorý treba držať v súlade s kódom: -```php [app/Api/UsersListHandler.php] +::: code-group + +```php [params()] namespace App\Api; use Tomaj\NetteApi\Attribute\Get; @@ -29,7 +31,37 @@ final class UsersListHandler extends BaseHandler } ``` -`#[Get(1, 'users')]` znamená `GET /api/v1/users`. Neon konfigurácia hovorí iba to, kde sú handlery: +```php [Typed DTO] +namespace App\Api; + +use Tomaj\NetteApi\Attribute\Get; +use Tomaj\NetteApi\Handlers\TypedHandler; +use Tomaj\NetteApi\Input\Query; +use Tomaj\NetteApi\Response\JsonApiResponse; +use Tomaj\NetteApi\Response\ResponseInterface; + +final readonly class UsersListInput +{ + public function __construct( + #[Query] + public int $page = 1, + ) { + } +} + +#[Get(1, 'users')] +final class UsersListHandler extends TypedHandler +{ + public function handleDto(UsersListInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['users' => [], 'page' => $input->page]); + } +} +``` + +::: + +`#[Get(1, 'users')]` znamená `GET /api/v1/users`. Atribúty fungujú rovnako na `BaseHandler` aj na `TypedHandler`; `examples/attributes` obsahuje oba. Neon konfigurácia hovorí iba to, kde sú handlery: ```yaml [config/api.neon] extensions: @@ -48,6 +80,7 @@ Keď Nette kompiluje kontajner, rozšírenie nájde každú triedu v `app/Api` s | --- | --- | | `#[Get(1, 'users')]` | `GET /api/v1/users` | | `#[Get(1, 'users', 'detail')]` | `GET /api/v1/users/detail` | +| `#[Get(1, 'users', '{id}/detail')]` | `GET /api/v1/users/{id}/detail`, `id` číta property `#[Path]`, pozrite [Typovaný vstup](/sk/guide/typed-input#hodnoty-z-cesty-a-sablony-url) | | `#[Post(1, 'users')]` | `POST /api/v1/users` | | `#[Put(1, 'users', 'update')]` | `PUT /api/v1/users/update` | | `#[Patch(1, 'users')]` | `PATCH /api/v1/users` | diff --git a/docs/sk/guide/console.md b/docs/sk/guide/console.md index 553e467af..f11e8ddfa 100644 --- a/docs/sk/guide/console.md +++ b/docs/sk/guide/console.md @@ -30,6 +30,20 @@ Pohľad `default` (`default.latte`) vykreslí zoznam endpointov. Klik na endpoin Formulár má jedno pole pre každý parameter, pole pre token alebo API kľúč (alebo meno a heslo pre Basic) a timeout. Ak ho chcete zmeniť, napíšte vlastný `ApiConsoleFormFactoryInterface`. +## Čo konzola posiela + +Konzola zostaví požiadavku z parametrov handlera, či už pochádzajú z `params()` alebo z typovaného DTO, takže neexistuje osobitný režim pre DTO. + +| Zdroj parametra | Posiela sa ako | +| --- | --- | +| query | query string | +| hodnota z cesty | URL-enkódovaná do segmentu `{name}` v URL | +| hodnota hlavičky | hlavička požiadavky | +| pole tela | prvý media type, ktorý handler číta a konzola ho vie zostaviť: JSON, URL-enkódovaný formulár alebo multipart | +| súbor | multipart upload; pri priloženom súbore idú polia tela v tej istej multipart požiadavke | + +V tele JSON si každá hodnota zachová deklarovaný typ a vstup pre vnorený objekt berie JSON text, napríklad `{}` pre prázdny objekt. Vstup pre zoznam má jedno políčko na položku a položka, ktorá je objekt, berie JSON text. Typované pole, ktoré ostane prázdne, sa nepošle (prázdny reťazec nikdy nie je platné číslo, dátum, voľba, objekt ani položka zoznamu), takže nepoužité políčko zoznamu sa preskočí. Prázdne voliteľné textové pole sa tiež nepošle, takže server použije jeho predvolenú hodnotu; povinné textové pole sa pošle ako prázdny reťazec, aby sa dali vyskúšať jeho obmedzenia dĺžky a patternu. Prázdna hlavička sa nepošle nikdy. Prázdna hodnota z cesty sa neposiela vôbec: konzola ukáže `The path value 'id' is empty. Fill it in and send the request again.` namiesto volania URL s prázdnym segmentom. Číslo, ktoré JSON nezvládne, napríklad `1e999` alebo celé číslo mimo 64-bitového rozsahu, sa pošle ako text, takže server odpovie svojím bežným `400`. + ## Časté otázky ### Prečo odoslanie formulára zlyhá s chybou CSRF? diff --git a/docs/sk/guide/di-extension.md b/docs/sk/guide/di-extension.md index 38725c956..b58c8240e 100644 --- a/docs/sk/guide/di-extension.md +++ b/docs/sk/guide/di-extension.md @@ -50,7 +50,7 @@ Každá položka `api.endpoints` je jeden endpoint: | `method` | áno | HTTP metóda, `GET`, `post`, ... (na veľkosti písmen nezáleží) | | `version` | áno | `1`, `2`, `'2.1'` bez `v`; URL je `/api/v{version}/...`. Verziu s bodkou píšte v úvodzovkách, neon číta `2.10` ako číslo `2.1` | | `package` | áno | prvá časť URL za verziou, bez lomky | -| `action` | nie | druhá časť, `/api/v1/users/detail` má akciu `detail`, bez lomky | +| `action` | nie | druhá časť, `/api/v1/users/detail` má akciu `detail`, bez lomky; `'{id}/detail'` (v úvodzovkách) je šablóna URL, pozrite [Typovaný vstup](/sk/guide/typed-input#hodnoty-z-cesty-a-sablony-url) | | `handler` | áno | handler, pozrite nižšie | | `authorization` | nie | kto ho smie volať, pozrite [Autorizácia](#autorizacia-a-obmedzenie-poziadaviek) | | `rateLimit` | nie | ako často, pozrite [Autorizácia](#autorizacia-a-obmedzenie-poziadaviek) | @@ -62,6 +62,8 @@ api: - {method: GET, version: 1, package: users, handler: App\Api\UsersListHandler} # GET /api/v1/users/detail?id=5 - {method: GET, version: 1, package: users, action: detail, handler: App\Api\UserDetailHandler} + # GET /api/v1/users/5/detail, id číta property #[Path] + - {method: GET, version: 1, package: users, action: '{id}/detail', handler: App\Api\UserDetailByPathHandler} # POST /api/v1/users - {method: POST, version: 1, package: users, handler: App\Api\UserCreateHandler} # GET /api/v2.1/users diff --git a/docs/sk/guide/errors.md b/docs/sk/guide/errors.md index 11b762939..97485af78 100644 --- a/docs/sk/guide/errors.md +++ b/docs/sk/guide/errors.md @@ -18,11 +18,12 @@ description: Ako Nette API mení výnimky, zlý vstup, zlyhanú autorizáciu a p | `handleAuthorizationException(Throwable, array $params)` | `authorized()` vyhodil výnimku | `500 Internal server error`, loguje do Tracy | | `handleNotFound(EndpointInterface)` | URL nezodpovedá žiadny endpoint | `404 Unknown api endpoint` | | `handleRateLimit(RateLimitResponse)` | limit je vyčerpaný a nemá vlastnú odpoveď | `429 Too many requests.`, ak je čas známy, aj `Retry after N seconds.` | +| `handleUnsupportedMediaType(string $detail)` | typovaný handler dostane telo s content typom, ktorý neprijíma | `415 unsupported media type`, s akceptovanými typmi v `detail` len so zapnutými detailmi chýb | Všetky vracajú `ResponseInterface`; `DefaultErrorHandler` vracia `JsonApiResponse` so `status: error` a `message`. ::: tip Od verzie 4.0.0 -`handleNotFound()` a `handleRateLimit()` sú nové, takže `404` a `429` sa dajú zmeniť na jednom mieste. Metódy vracajú `ResponseInterface` namiesto `JsonApiResponse`. `handleAuthorizationException()` už nepošle text výnimky, ak nie sú zapnuté detaily. Pozrite si [návod na upgrade](/sk/upgrade). +`handleNotFound()`, `handleRateLimit()` a `handleUnsupportedMediaType()` sú nové, takže `404`, `429` a `415` sa dajú zmeniť na jednom mieste. Metódy vracajú `ResponseInterface` namiesto `JsonApiResponse`. `handleAuthorizationException()` už nepošle text výnimky, ak nie sú zapnuté detaily. Pozrite si [návod na upgrade](/sk/upgrade). ::: Pre nové projekty odporúčame chyby `application/problem+json` podľa RFC 9457 cez `ProblemDetailsErrorHandler`, pozrite si [Problem Details](/sk/guide/problem-details). `DefaultErrorHandler` ostáva predvolený, aby klienti, ktorí čítajú `message`, fungovali ďalej. diff --git a/docs/sk/guide/getting-started.md b/docs/sk/guide/getting-started.md index e19b56ea7..abba31505 100644 --- a/docs/sk/guide/getting-started.md +++ b/docs/sk/guide/getting-started.md @@ -109,9 +109,11 @@ Potom súbor načítajte v `app/Bootstrap.php`: ## 4. Napíšte handler -Vytvorte `app/Api/HelloHandler.php`: +Vytvorte `app/Api/HelloHandler.php`. Handler deklaruje svoj vstup jedným z dvoch rovnocenných spôsobov: zoznamom parametrov v `params()` alebo typovaným DTO, ktoré dostane `handleDto()`. Oba prechádzajú rovnakým validačným pipeline a dávajú rovnaké OpenAPI aj webovú konzolu a jedno API ich môže kombinovať. Typované DTO konvertuje hodnoty prísnejšie než `params()`. -```php [app/Api/HelloHandler.php] +::: code-group + +```php [params()] 'Hello ' . $input->name . '!']); + } +} +``` + +::: + +S `params()` dostane `handle()` zvalidované parametre ako pole. S typovaným DTO dostane `handleDto()` zvalidovaný objekt `HelloInput`. Oba vrátia odpoveď. Ostatné metódy vysvetľujú [Handlery](/sk/guide/handlers) a atribúty DTO [Typovaný vstup (DTO)](/sk/guide/typed-input). ## 5. Zavolajte ho diff --git a/docs/sk/guide/handlers.md b/docs/sk/guide/handlers.md index a7250939a..d7d747b93 100644 --- a/docs/sk/guide/handlers.md +++ b/docs/sk/guide/handlers.md @@ -5,7 +5,12 @@ description: Písanie handlerov v Nette API - dedenie z BaseHandler, deklarácia # Handlery -Handler je kód jedného endpointu. Implementuje `Tomaj\NetteApi\Handlers\ApiHandlerInterface`; v praxi dedíte z `BaseHandler` a píšete `handle()`. +Handler je kód jedného endpointu. Implementuje `Tomaj\NetteApi\Handlers\ApiHandlerInterface`; v praxi dedíte z jednej z dvoch rovnocenných základných tried, podľa toho, ako chcete deklarovať vstup: + +- `BaseHandler`: vstup vymenujete v `params()` a čítate ho ako pole v `handle(array $params)`. +- `TypedHandler`: vstup opíšete ako readonly DTO s `#[Query]`, `#[Path]`, `#[Header]`, `#[Body]` a `#[File]` a čítate ho ako objekt v `handleDto(SomeInput $input)`. Pozrite [Typovaný vstup (DTO)](/sk/guide/typed-input). + +Oba skončia ako rovnaké objekty `InputParam`, takže validačný pipeline, chybové odpovede, OpenAPI aj webová konzola sú spoločné. Líši sa len konverzia: typované DTO konvertuje striktne (`?page=1a` je `400`), zatiaľ čo `params()` si ponecháva voľnejšiu konverziu, pozrite [Vstupné parametre](/sk/guide/params#typy). Jedno API môže kombinovať oba. @@ -13,17 +18,19 @@ Handler je kód jedného endpointu. Implementuje `Tomaj\NetteApi\Handlers\ApiHan | Metóda | Predvolená hodnota v BaseHandler | Používa | | --- | --- | --- | -| `handle(array $params): ResponseInterface` | abstraktná, píšete ju vy | ApiPresenter | -| `params(): array` | `[]` | validácia, OpenAPI, konzola | +| `handle(array $params): ResponseInterface` | abstraktná, píšete ju vy; `TypedHandler` ju implementuje a volá `handleDto()` | ApiPresenter | +| `params(): array` | `[]`; `TypedHandler` ho zostaví z DTO | validácia, OpenAPI, konzola | | `outputs(): array` | `[]` | kontrola výstupu, OpenAPI | | `summary(): string` | `''` | OpenAPI, konzola | | `description(): string` | `''` | OpenAPI, konzola | | `tags(): array` | `[]` | OpenAPI | | `deprecated(): bool` | `false` | OpenAPI | -`handle()` dostane hodnoty parametrov podľa ich názvov. Vracia odpoveď, napríklad `JsonApiResponse`, pozrite si [Výstupy a odpovede](/sk/guide/outputs). +`handle()` dostane hodnoty parametrov podľa ich názvov; `handleDto()` dostane DTO. Vracia odpoveď, napríklad `JsonApiResponse`, pozrite si [Výstupy a odpovede](/sk/guide/outputs). + +::: code-group -```php +```php [params()] users->find($input->id); + if ($user === null) { + return new JsonApiResponse(404, ['status' => 'error', 'message' => 'User not found']); + } + return new JsonApiResponse(200, ['id' => $user->id, 'name' => $user->name]); + } +} +``` + +::: + `BaseHandler` má konštruktor s voliteľným Fractal `ScopeFactoryInterface`. Keď má váš handler vlastný konštruktor, zavolajte `parent::__construct()`. ## Registrácia handlera diff --git a/docs/sk/guide/input-styles.md b/docs/sk/guide/input-styles.md new file mode 100644 index 000000000..ed8d4d16a --- /dev/null +++ b/docs/sk/guide/input-styles.md @@ -0,0 +1,472 @@ +--- +title: params() a DTO vedľa seba +description: 'Rovnaké endpointy deklarované cez params() aj cez typované DTO v Nette API: sedem dvojíc ukazuje, ako prepísať handler z jedného štýlu na druhý.' +--- + +# params() a DTO vedľa seba + +`params()` s `handle(array $params)` a `TypedHandler` s DTO sú dva rovnocenné spôsoby písania handlerov v jednej aplikácii. Jeden nevypína druhý. Registrácia, autorizácia, výstupy, obmedzenia požiadaviek, OpenAPI a konzola sú spoločné. [Typovaný vstup (DTO)](/sk/guide/typed-input) oba štýly porovnáva a [Vstupné parametre](/sk/guide/params) popisujú prvý z nich. + +## Prepisovanie medzi štýlmi + +Nasledujúce dvojice ukazujú rovnaký kontrakt požiadavky v oboch štýloch, takže handler môžete prepísať z ktoréhokoľvek štýlu na druhý, keď sa to pre daný endpoint hodí. Importy frameworku sú vynechané tam, kde sa nemenia; závislosti aplikácie v konštruktore a vytváranie odpovede ostávajú v handleri. Môžete prepísať jeden endpoint, všetky ostatné handlery nechať bez zmeny a ďalší prepísať, keď sa vám to bude hodiť. Neexistuje globálny prepínač aplikácie. + +### 1. Jednoduchý GET: voliteľné/predvolené query parametre a enum + +S `params()` handler deklaruje každý query parameter, pretypuje hodnoty a mapuje reťazec statusu na enum. `UserStatus::options()` zastupuje pomocnú metódu aplikácie, ktorá vracia povolené hodnoty: + +```php +final class ListUsersHandler extends BaseHandler +{ + public function __construct(private UserRepository $users) + { + parent::__construct(); + } + + public function params(): array + { + return [ + (new GetInputParam('page', InputType::INTEGER)) + ->setDefault(1) + ->setDescription('Page number'), + (new GetInputParam('limit', InputType::INTEGER))->setDefault(20), + (new GetInputParam('status', InputType::STRING)) + ->setAvailableValues(UserStatus::options()), + ]; + } + + public function handle(array $params): ResponseInterface + { + $page = (int) $params['page']; + $limit = (int) $params['limit']; + $status = $params['status'] === null + ? null + : UserStatus::from($params['status']); + + if ($page < 1 || $limit < 1 || $limit > 100) { + return new JsonApiResponse(400, ['status' => 'error']); + } + + return new JsonApiResponse(200, $this->users->findPage($page, $limit, $status)); + } +} +``` + +S DTO sú predvolené hodnoty, voliteľnosť a povolené hodnoty enumu v triede. `Range` nahradí ručnú kontrolu hraníc a `handleDto()` dostane hodnoty pripravené na použitie: + +```php +final readonly class ListUsersInput +{ + public function __construct( + #[Query(description: 'Page number')] + #[Range(min: 1)] + public int $page = 1, + + #[Query] + #[Range(min: 1, max: 100)] + public int $limit = 20, + + #[Query] + public ?UserStatus $status = null, + ) { + } +} + +final class ListUsersHandler extends TypedHandler +{ + public function __construct(private UserRepository $users) + { + parent::__construct(); + } + + public function handleDto(ListUsersInput $input): ResponseInterface + { + return new JsonApiResponse(200, $this->users->findPage( + $input->page, + $input->limit, + $input->status, + )); + } +} +``` + +Zároveň to ukazuje všeobecné pravidlo pre voliteľné a predvolené hodnoty: `?UserStatus $status = null` je voliteľná hodnota a stane sa `null`; `int $limit = 20` je voliteľná hodnota a pri vynechaní sa stane `20`. Povinná hodnota by bola nenulovateľná a bez predvolenej hodnoty, napríklad `#[Query] public string $search`. + +### 2. GET: id v ceste a hlavička požiadavky + +S `params()` URL endpointu obsahuje `users/{id}/detail` a `params()` deklaruje `PathInputParam` a `HeaderInputParam`: + +```php +final class UserDetailHandler extends BaseHandler +{ + public function params(): array + { + return [ + (new PathInputParam('id', InputType::INTEGER))->setRequired(), + new HeaderInputParam('X-Request-Id', InputType::STRING), + ]; + } + + public function handle(array $params): ResponseInterface + { + $id = (int) $params['id']; + $requestId = $params['X-Request-Id']; + + return $this->userDetail($id, $requestId); + } +} +``` + +S DTO `Path` a `Header` zachovajú externé názvy, zatiaľ čo handler používa výstižné typované properties: + +```php +final readonly class UserDetailInput +{ + public function __construct( + #[Path] + #[Range(min: 1)] + public int $id, + + #[Header('X-Request-Id')] + public ?string $requestId = null, + ) { + } +} + +final class UserDetailHandler extends TypedHandler +{ + public function handleDto(UserDetailInput $input): ResponseInterface + { + return $this->userDetail($input->id, $input->requestId); + } +} +``` + +Registrácia endpointu a URL sa nemenia. Deklarácia DTO stále vygeneruje `id` ako povinný parameter cesty a `X-Request-Id` ako voliteľnú hlavičku v OpenAPI. + +### 3. POST JSON: vnorený objekt a pole + +S `params()` obsahuje `JsonInputParam` ručne písanú schému. Handler číta vnorené polia a vytvára vlastné hodnoty: + +```php +final class CreateOrderHandler extends BaseHandler +{ + public function params(): array + { + return [ + (new JsonInputParam('body', <<<'JSON' + { + "type": "object", + "required": ["customerEmail", "address", "items"], + "properties": { + "customerEmail": {"type": "string", "format": "email"}, + "address": { + "type": "object", + "required": ["street", "postalCode"], + "properties": { + "street": {"type": "string"}, + "postalCode": {"type": "string", "pattern": "^[0-9]{5}$"} + } + }, + "items": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "required": ["sku", "quantity"], + "properties": { + "sku": {"type": "string"}, + "quantity": {"type": "integer", "minimum": 1} + } + } + } + } + } + JSON))->setRequired(), + ]; + } + + public function handle(array $params): ResponseInterface + { + $body = $params['body']; + $items = array_map( + fn (array $item) => new OrderItem($item['sku'], (int) $item['quantity']), + $body['items'], + ); + + return $this->orders->create( + $body['customerEmail'], + new Address($body['address']['street'], $body['address']['postalCode']), + $items, + ); + } +} +``` + +S DTO je vnorená štruktúra vyjadrená raz ako triedy. Runtime validácia nepotrebuje JSON schému: + +```php +final readonly class AddressInput +{ + public function __construct( + #[Body] public string $street, + #[Body] #[Pattern('/^[0-9]{5}$/')] public string $postalCode, + ) { + } +} + +final readonly class OrderItemInput +{ + public function __construct( + #[Body] public string $sku, + #[Body] #[Range(min: 1)] public int $quantity, + ) { + } +} + +final readonly class CreateOrderInput +{ + /** @param list $items */ + public function __construct( + #[Body] #[Email] public string $customerEmail, + #[Body] public AddressInput $address, + #[Body] #[Length(min: 1)] public array $items, + ) { + } +} + +final class CreateOrderHandler extends TypedHandler +{ + public function handleDto(CreateOrderInput $input): ResponseInterface + { + $items = array_map( + fn (OrderItemInput $item) => new OrderItem($item->sku, $item->quantity), + $input->items, + ); + + return $this->orders->create( + $input->customerEmail, + new Address($input->address->street, $input->address->postalCode), + $items, + ); + } +} +``` + +`list` je dôležité: mapperu aj OpenAPI hovorí, čo obsahuje položka poľa. Chyba v quantity druhej položky sa nahlási pod `items[1].quantity`. + +### 4. Formulárový POST + +S `params()` objekty `PostInputParam` popisujú URL-enkódovaný prihlasovací formulár: + +```php +final class LoginHandler extends BaseHandler +{ + public function params(): array + { + return [ + (new PostInputParam('email', InputType::STRING))->setRequired(), + (new PostInputParam('password', InputType::STRING))->setRequired(), + (new PostInputParam('remember', InputType::BOOLEAN))->setDefault(false), + ]; + } + + public function handle(array $params): ResponseInterface + { + return $this->sessions->login( + (string) $params['email'], + (string) $params['password'], + (bool) $params['remember'], + ); + } +} +``` + +S DTO `Body` znamená pole tela bez ohľadu na to, či je požiadavka JSON alebo formulárová. Hranica `max` je tu jediné pravidlo dĺžky, pretože minimum by pri prihlásení začalo odmietať existujúce krátke heslá: + +```php +final readonly class LoginInput +{ + public function __construct( + #[Body] #[Email] public string $email, + #[Body] #[Length(max: 200)] public string $password, + #[Body] public bool $remember = false, + ) { + } +} + +final class LoginHandler extends TypedHandler +{ + public function handleDto(LoginInput $input): ResponseInterface + { + return $this->sessions->login($input->email, $input->password, $input->remember); + } +} +``` + +Formulár stále posiela `email=ada%40example.com&password=...&remember=1`. Mapper DTO odmietne neznáme boolean reťazce namiesto toho, aby každý neprázdny reťazec považoval za `true`. + +### 5. Nahrávanie súboru + +S `params()` handler dostane surovú položku uploadu a validuje jej chybu nahrávania a veľkosť: + +```php +final class AvatarUploadHandler extends BaseHandler +{ + public function params(): array + { + return [ + (new PostInputParam('displayName', InputType::STRING))->setRequired(), + (new FileInputParam('avatar'))->setRequired(), + ]; + } + + public function handle(array $params): ResponseInterface + { + $avatar = $params['avatar']; + if ($avatar['error'] !== UPLOAD_ERR_OK || $avatar['size'] > 100_000) { + return new JsonApiResponse(400, ['status' => 'error']); + } + + return $this->avatars->store((string) $params['displayName'], $avatar['tmp_name']); + } +} +``` + +S DTO `FileUpload` poskytne typovaný prístup k rovnakým metadátam. Aplikačné kontroly skutočného typu súboru a ukladania ostávajú explicitné: + +```php +final readonly class AvatarUploadInput +{ + public function __construct( + #[Body] #[Length(min: 1, max: 80)] public string $displayName, + #[File] public FileUpload $avatar, + ) { + } +} + +final class AvatarUploadHandler extends TypedHandler +{ + public function handleDto(AvatarUploadInput $input): ResponseInterface + { + $avatar = $input->avatar; + if ($avatar->error !== UPLOAD_ERR_OK || $avatar->size > 100_000) { + return new JsonApiResponse(400, ['status' => 'error']); + } + + return $this->avatars->store($input->displayName, $avatar->temporaryPath); + } +} +``` + +Názvy multipart polí ostávajú `displayName` a `avatar`. Ani jeden štýl nenahrádza bezpečnostné kontroly aplikácie ani PHP limity uploadov. + +### 6. Vlastná validácia + +S `params()` žije validácia závislá od viacerých hodnôt v `handle()`: + +```php +final class ScheduleHandler extends BaseHandler +{ + public function params(): array + { + return [ + (new JsonInputParam('body', $this->scheduleSchema()))->setRequired(), + ]; + } + + public function handle(array $params): ResponseInterface + { + $startsAt = new DateTimeImmutable($params['body']['startsAt']); + $endsAt = new DateTimeImmutable($params['body']['endsAt']); + if ($endsAt <= $startsAt) { + return new JsonApiResponse(400, [ + 'status' => 'error', + 'message' => 'wrong input', + 'detail' => ['endsAt' => ['End must be later than start']], + ]); + } + + return $this->schedule->create($startsAt, $endsAt); + } +} +``` + +S DTO sú jednoduchá konverzia a RFC 3339 parsovanie deklaratívne. Vlastné validačné obmedzenie vyjadruje pravidlo, ktoré spája viac polí, a zachováva konzistentnú transportnú odpoveď: + +```php +#[Attribute(Attribute::TARGET_PROPERTY)] +final readonly class LaterThan implements ConstraintInterface +{ + public function __construct(private string $otherProperty) + { + } + + public function validate(mixed $value, ConstraintContext $context): ?string + { + $other = $context->value($this->otherProperty); + if ($value instanceof DateTimeImmutable && $other instanceof DateTimeImmutable && $value <= $other) { + return sprintf('Must be later than %s', $this->otherProperty); + } + + return null; + } +} + +final readonly class ScheduleInput +{ + public function __construct( + #[Body] public DateTimeImmutable $startsAt, + #[Body] #[LaterThan('startsAt')] public DateTimeImmutable $endsAt, + ) { + } +} + +final class ScheduleHandler extends TypedHandler +{ + public function handleDto(ScheduleInput $input): ResponseInterface + { + return $this->schedule->create($input->startsAt, $input->endsAt); + } +} +``` + +`ConstraintContext::value()` číta susedné hodnoty v tom istom DTO, takže validačné obmedzenia medzi properties nemusia skúmať HTTP požiadavku. Obchodné pravidlá, ktoré potrebujú databázu, stále patria do aplikačných služieb; validačné obmedzenie má ostať deterministickou kontrolou kontraktu požiadavky. + +### 7. Oba štýly v jednej aplikácii + +Endpoint môže závisieť od voľnejšej konverzie `InputType::INTEGER` v `params()`, od vlastného `InputParam` alebo od ručného parsovania nezvyčajného content typu. Pre taký endpoint je `params()` správny štýl: + +```php +final class ReportHandler extends BaseHandler +{ + public function params(): array + { + return [new GetInputParam('offset', InputType::INTEGER)]; + } + + public function handle(array $params): ResponseInterface + { + // Existujúce správanie endpointu zámerne ostáva bez zmeny. + return $this->reports->generate($params['offset']); + } +} +``` + +Susediaci `ListReportsHandler` môže rozširovať `TypedHandler`. Miešanie štýlov je podporované bez obmedzenia; voľba sa týka pohodlia pri každom endpointe. + +### Kontrolný zoznam prepisu handlera na DTO + +1. **Zachyťte aktuálny kontrakt:** uložte testy endpointu a aktuálnu OpenAPI operáciu vrátane predvolených hodnôt a chybového správania. +2. **Vytvorte readonly DTO:** jednu promovanú property pre každý query, path, header, body alebo file vstup. +3. **Zachovajte externé názvy:** použite explicitné názvy atribútov ako `#[Header('X-Request-Id')]`, ak sa názov property líši. +4. **Zlaďte povinnosť:** nenulovateľná property bez predvolenej hodnoty je povinná; nulovateľná alebo s predvolenou hodnotou je voliteľná. +5. **Nahraďte ručné deklarácie:** použite enumy s hodnotami (backed enum) pre povolené hodnoty a vstavané validačné obmedzenia tam, kde zodpovedajú existujúcim kontrolám. +6. **Spracujte vnorené dáta:** vytvorte vnorené DTO a pridajte PHPDoc `list` pre polia DTO. +7. **Presuňte len validáciu kontraktu:** databázové vyhľadávania a obchodné pravidlá nechajte v službách alebo handleri; pre deterministické pravidlá vstupu použite vlastné validačné obmedzenia. +8. **Prepnite základnú triedu:** nahraďte `handle(array $params)` za `handleDto(Input $input)` a odstráňte ručné pretypovania/prístupy k poľu. +9. **Porovnajte správanie:** spustite úspešné aj chybné požiadavky, skontrolujte cesty polí, porovnajte OpenAPI a skontrolujte formulár konzoly a nahrávanie. +10. **Skontrolujte kompatibilitu:** prísnejšiu konverziu zdôraznite vo svojom changelogu. Ak musí ostať súčasné správanie, ponechajte pre endpoint `params()`. + +Prepis DTO na `params()` ide rovnako opačným smerom: deklarujte jeden `InputParam` pre každú property s rovnakým názvom, príznakom povinnosti, predvolenou hodnotou a povolenými hodnotami, validačné obmedzenia presuňte do handlera alebo vlastného `InputParam` a znova porovnajte operáciu OpenAPI. + diff --git a/docs/sk/guide/layers.md b/docs/sk/guide/layers.md index 3df9ceebf..546abab88 100644 --- a/docs/sk/guide/layers.md +++ b/docs/sk/guide/layers.md @@ -23,7 +23,8 @@ Jedna požiadavka, ktorá prejde, jedna bez tokenu a jedna so zlým vstupom: | Parametre | `InputParam`, `ParamsProcessor` | Načíta a overí vstup; chyby počkajú na autorizáciu | | | Autorizácia | `ApiAuthorizationInterface` | Rozhodne, kto smie volať | `401` | | Chyby parametrov | `ErrorHandlerInterface::handleInputParams()` | Nahlási neplatný vstup | `400` | -| Handler | `ApiHandlerInterface`, `BaseHandler` | Vaša logika, vráti odpoveď | ľubovoľný kód | +| Media type | `ErrorHandlerInterface::handleUnsupportedMediaType()` | Odmietne telo, ktoré typovaný handler neprijíma, po autorizácii | `415` | +| Handler | `ApiHandlerInterface`, `BaseHandler`, `TypedHandler` | Vaša logika, vráti odpoveď | ľubovoľný kód | | Výstupy | `OutputInterface`, `ConfiguratorInterface` | Overí odpoveď voči schéme | `500` | | Chyby | `ErrorHandlerInterface` | Zmení zlyhania na JSON | | | Logger | `ApiLoggerInterface` | Zapíše spracované požiadavky | | @@ -113,6 +114,7 @@ public function handle(array $params): ResponseInterface | `handleSchema()` | výstup nezodpovedá | `500` | | `handleAuthorization()` | `authorized()` vrátil false | `401` so správou | | `handleAuthorizationException()` | `authorized()` vyhodil výnimku | `500` so správou výnimky | +| `handleUnsupportedMediaType()` | typovaný handler dostal telo s iným content typom | `415` | Pozrite si [Spracovanie chýb](/sk/guide/errors). @@ -122,7 +124,7 @@ So službou `ApiLoggerInterface` v kontajneri sa zaloguje každá požiadavka, k ## Časté otázky -### Kam patrí biznis logika? +### Kam patrí obchodná logika? Do handlera alebo do služby, ktorú volá. Ostatné vrstvy iba rozhodujú, či sa spustí, a kontrolujú, čo vráti. diff --git a/docs/sk/guide/links.md b/docs/sk/guide/links.md index 6fe2b8b60..cd666394f 100644 --- a/docs/sk/guide/links.md +++ b/docs/sk/guide/links.md @@ -15,7 +15,18 @@ $url = $apiLink->link(new EndpointIdentifier('GET', 1, 'users', 'detail'), ['id' Potrebuje routu na `Api:Api:default` s parametrami `version`, `package` a `apiAction`, ako v [Začíname](/sk/guide/getting-started). -V handleri, ktorý dedí z `BaseHandler`, zavolajte `$this->createLink($params)` pre odkaz na vlastný endpoint handlera. Najprv potrebuje Nette `LinkGenerator`, inak vyhodí `Nette\InvalidStateException`. Pridajte do služby handlera riadok `setup`: +Pri endpointe, ktorého URL má segmenty `{name}`, napríklad `{id}/detail`, `link()` nechá segmenty doslovné, čo je šablóna cesty z OpenAPI. Segment nahraďte hodnotou s URL kódovaním sami: + +```php +$url = $apiLink->link(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), ['limit' => 5]); +// https://example.com/api/v1/users/{id}/detail?limit=5 +$url = str_replace('{id}', rawurlencode('42'), $url); +// https://example.com/api/v1/users/42/detail?limit=5 +``` + +API konzola robí to isté s hodnotami z vstupov pre cestu, a to po tom, čo `link()` zostavil URL, takže podtrieda, ktorá `link()` prepisuje, stále rozhoduje o URL každého endpointu. + +V handleri, ktorý dedí z `BaseHandler` alebo `TypedHandler`, zavolajte `$this->createLink($params)` pre odkaz na vlastný endpoint handlera. Najprv potrebuje Nette `LinkGenerator`, inak vyhodí `Nette\InvalidStateException`. Pridajte do služby handlera riadok `setup`: ```yaml services: diff --git a/docs/sk/guide/openapi.md b/docs/sk/guide/openapi.md index bb047496b..3a76b9d35 100644 --- a/docs/sk/guide/openapi.md +++ b/docs/sk/guide/openapi.md @@ -56,7 +56,7 @@ Dokument vytvárajú malé buildery v `Tomaj\NetteApi\OpenApi`, každý zodpoved |---|---| | `SpecBuilder` | celý dokument: info, servers, components, paths (filtruje API podľa verzie) | | `PathBuilder` | cesty a operácie (summary, tagy, parametre, telo requestu, security, odpovede) | -| `ParameterBuilder` | query a cookie parametre | +| `ParameterBuilder` | query, cookie, path a header parametre; path a header pochádzajú z [typovaného vstupu](/sk/guide/typed-input) | | `RequestBodyBuilder` | JSON, raw, form a multipart telá requestu | | `ResponseBuilder` | chybové odpovede a ich schémy, odpovede z outputov handlera | | `SecuritySchemeBuilder` | security schémy a požiadavky z autorizácií (prepíšte `createScheme()`) | diff --git a/docs/sk/guide/outputs.md b/docs/sk/guide/outputs.md index 448aa32df..39300c57a 100644 --- a/docs/sk/guide/outputs.md +++ b/docs/sk/guide/outputs.md @@ -88,4 +88,4 @@ Ak má endpoint výstupy, aj vrátená `404` musí jednému zodpovedať, inak va ### Môžem použiť Fractal transformery? -Áno. `BaseHandler` vytvorí Fractal `Manager`, dostupný cez `$this->getFractal()`, a v konštruktore prijme voliteľný `ScopeFactoryInterface`. Pozrite si [Handlery](/sk/guide/handlers#metody). +Áno. `BaseHandler` (a teda aj `TypedHandler`) vytvorí Fractal `Manager`, dostupný cez `$this->getFractal()`, a v konštruktore prijme voliteľný `ScopeFactoryInterface`. Pozrite si [Handlery](/sk/guide/handlers#metody). diff --git a/docs/sk/guide/params.md b/docs/sk/guide/params.md index 965b64366..518ae6422 100644 --- a/docs/sk/guide/params.md +++ b/docs/sk/guide/params.md @@ -7,6 +7,8 @@ description: Deklarácia a validácia vstupu v Nette API - GET, POST, PUT, cooki `params()` vracia vstupy endpointu. `ApiPresenter` ich všetky načíta a zvaliduje pred spustením `handle()`, ktorý dostane hodnoty podľa názvu. +Vstup sa dá deklarovať dvoma rovnocennými spôsobmi: cez `params()`, ako popisuje táto stránka, alebo ako properties typovaného DTO, ktoré číta `TypedHandler::handleDto()`. Oba vytvoria tieto objekty `InputParam` a zdieľajú validáciu, OpenAPI aj konzolu. Pri výbere pomôže [Typovaný vstup (DTO)](/sk/guide/typed-input) a [params() a DTO vedľa seba](/sk/guide/input-styles) ukazuje tie isté endpointy v oboch štýloch. + ## Triedy parametrov @@ -16,6 +18,9 @@ description: Deklarácia a validácia vstupu v Nette API - GET, POST, PUT, cooki | `GetInputParam` | query string | podporuje typy a `setMulti()` | | `PostInputParam` | telo formulára, `$_POST` | podporuje typy a `setMulti()` | | `PutInputParam` | form-encoded telo ľubovoľnej metódy | bez prevodu typu, typ sa ale kontroluje: `INTEGER` odmietne aj `"12"`, použite `STRING` alebo žiadny typ | +| `PathInputParam` | pomenovaný `{placeholder}` v URL endpointu | vždy povinný, pozrite [nižšie](#parametre-path-header-a-body) | +| `HeaderInputParam` | HTTP hlavička, bez ohľadu na veľkosť písmen | pozrite [nižšie](#parametre-path-header-a-body) | +| `BodyInputParam` | jedno pole tela JSON, formulára alebo multipart | pozrite [nižšie](#parametre-path-header-a-body) | | `CookieInputParam` | cookie | bez prevodu typu, typ sa ale kontroluje: `INTEGER` odmietne aj `"12"`, použite `STRING` alebo žiadny typ | | `FileInputParam` | nahraný súbor, `$_FILES` | `setMulti()` pre viac súborov | | `RawInputParam` | celé telo požiadavky ako reťazec | `setMulti()` vyhodí výnimku | @@ -56,6 +61,25 @@ Všetky parametre majú spoločné fluent API: V 3.x `?limit=abc` s typom `INTEGER` nie je chyba: hodnota sa pred validáciou prevedie na `null`, takže voliteľný parameter prejde a povinný vráti `Field is required`. V `handle()` vždy počítajte s `null`. Testuje to [príklad parametrov](/sk/examples/params-validation). ::: +## Parametre Path, Header a Body + +`PathInputParam` číta hodnotu z URL endpointu. Placeholder deklarujte v akcii endpointu ako `{name}`, napríklad `users/{id}/detail`, ako popisuje [Typovaný vstup](/sk/guide/typed-input#hodnoty-z-cesty-a-sablony-url). Parameter je vždy povinný a jeho placeholder v OpenAPI má rovnaký názov. `HeaderInputParam` číta hlavičku požiadavky bez ohľadu na veľkosť písmen. `BodyInputParam` číta jedno pole objektu JSON, URL-enkódovaného formulára alebo multipart tela a `setContentTypes()` uvádza media typy, ktoré prijíma. Typované DTO vygeneruje tieto isté tri triedy z `#[Path]`, `#[Header]` a `#[Body]` a `params()` ich vie deklarovať priamo: + +```php +public function params(): array +{ + return [ + (new PathInputParam('id', InputType::INTEGER))->setRequired(), + new HeaderInputParam('X-Request-Id', InputType::STRING), + (new BodyInputParam('email', InputType::STRING)) + ->setRequired() + ->setContentTypes(['application/json', 'application/x-www-form-urlencoded']), + ]; +} +``` + +OpenAPI ich zapíše ako `in: path`, `in: header` a ako polia `requestBody`. + ## JSON telo `JsonInputParam` berie JSON schému ako reťazec a voči nej validuje dekódované telo: diff --git a/docs/sk/guide/presenter.md b/docs/sk/guide/presenter.md index 87d551c04..66e2303bc 100644 --- a/docs/sk/guide/presenter.md +++ b/docs/sk/guide/presenter.md @@ -12,11 +12,11 @@ description: 'Presné poradie krokov v Nette API ApiPresenter::run(), od CORS a | Krok | Kód | Výstup | | --- | --- | --- | | 1. CORS hlavičky | `sendCorsHeaders()` | | -| 2. Endpoint | `$this->apiDecider->getApi(...)` | `404` cez `DefaultHandler` a `handleNotFound()` | +| 2. Endpoint | `$this->apiDecider->getApi(...)`, potom `matchPath(...)` pre URL s `{name}` | `404` cez `DefaultHandler` a `handleNotFound()` | | 3. Obmedzenie požiadaviek | `checkRateLimit($rateLimit)` | `429`, neloguje sa | | 4. Načítanie parametrov | `new ParamsProcessor($handler->params())` | | | 5. Autorizácia | `checkAuth($authorization, $params)` | `401` alebo `500`, neloguje sa | -| 6. Chyby parametrov | `errorHandler->handleInputParams()` | `400`, neloguje sa | +| 6. Chyby parametrov | `errorHandler->handleUnsupportedMediaType()`, `errorHandler->handleInputParams()` | `415` typovaného handlera, loguje sa; `400`, neloguje sa | | 7. Handler | `$handler->handle($params)` | výnimka: `500` | | 8. Kontrola výstupu | `$output->validate($response)` | bez zhody: `500` | | 9. Logger | `logRequest()` | | diff --git a/docs/sk/guide/problem-details.md b/docs/sk/guide/problem-details.md index 2223635d8..1a3141de5 100644 --- a/docs/sk/guide/problem-details.md +++ b/docs/sk/guide/problem-details.md @@ -44,6 +44,7 @@ Nechajte len jednu službu error handlera: pri dvoch Nette DI nevie autowirovať | `authorized()` je false, `handleAuthorization()` | `401` | `unauthorized` | `getErrorMessage()` | | | neznámy endpoint, `handleNotFound()` | `404` | `not-found` | `Unknown api endpoint` | | | vyčerpaný limit, `handleRateLimit()` | `429` | `rate-limited` | `Too many requests.`, ak je čas známy, aj `Retry after N seconds.` | `limit`, `retryAfter`, ak je známy | +| content type tela nie je akceptovaný, `handleUnsupportedMediaType()` | `415` | `unsupported-media-type` | prijatý typ a akceptované typy | | | výnimka v handleri, `handle()` | `500` | `internal-error` | text výnimky, len so zapnutými detailmi | | | výnimka v `authorized()`, `handleAuthorizationException()` | `500` | `internal-error` | text výnimky, len so zapnutými detailmi | | | výstup nesedí, `handleSchema()` | `500` | `invalid-output` | žiadny | `outputErrors`, len so zapnutými detailmi | @@ -54,7 +55,7 @@ Chyby validácie sú zoznam `{"parameter": ..., "detail": ...}` a posielajú sa ## Vlastné problémy z handlera -Biznis chybu, napríklad objednávku vypredaného produktu, vráti handler ako `ProblemDetailsResponse`: +Obchodnú chybu, napríklad objednávku vypredaného produktu, vráti handler ako `ProblemDetailsResponse`: ```php use Tomaj\NetteApi\Error\ProblemDetails; diff --git a/docs/sk/guide/typed-input-body.md b/docs/sk/guide/typed-input-body.md new file mode 100644 index 000000000..c44ad6d24 --- /dev/null +++ b/docs/sk/guide/typed-input-body.md @@ -0,0 +1,164 @@ +--- +title: 'Typovaný vstup: telo, súbory a content typy' +description: 'Polia tela typovaného DTO v Nette API: vnorené objekty a zoznamy, content typy JSON, formulár a multipart, Consumes, 415 a nahrávanie súborov.' +--- + +# Typovaný vstup: telo, súbory a content typy + +Táto stránka popisuje polia tela typovaného DTO: vnorené objekty a zoznamy, content typy JSON, formulár a multipart, `#[Consumes]` a nahrávanie súborov. Základy sú v stránke [Typovaný vstup (DTO)](/sk/guide/typed-input). + +## POST s vnoreným DTO a poľom + +```php +final readonly class AddressInput +{ + public function __construct( + #[Body] + #[Length(min: 1, max: 120)] + public string $street, + + #[Body] + #[Pattern('/^[0-9]{5}$/')] + public string $postalCode, + ) { + } +} + +final readonly class ItemInput +{ + public function __construct( + #[Body] + public string $sku, + + #[Body] + #[Range(min: 1)] + public int $quantity, + ) { + } +} + +final readonly class CreateOrderInput +{ + /** @param list $items */ + public function __construct( + #[Body] + #[Email] + public string $customerEmail, + + #[Body] + public AddressInput $address, + + #[Body] + #[Length(min: 1, max: 50)] + public array $items, + + #[Body] + public ?DateTimeImmutable $deliveryAt = null, + ) { + } +} +``` + +JSON telo požiadavky: + +```json +{ + "customerEmail": "ada@example.com", + "address": {"street": "Main 1", "postalCode": "81101"}, + "items": [ + {"sku": "BOOK-1", "quantity": 2}, + {"sku": "PEN-2", "quantity": 1} + ], + "deliveryAt": "2026-11-06T14:30:00+01:00" +} +``` + +Mapper DTO rekurzívne vytvorí `AddressInput` a oba objekty `ItemInput`. `list` je povinný PHPDoc pre pole DTO; pre polia skalárov sú podporované `list`, `list`, `list` a `list`. Čítajú sa bežné zápisy: `list`, `non-empty-list`, `T[]`, s `|null` alebo úvodným `?` (nulovateľnosť určuje typ v PHP) a `@phpstan-param` alebo `@psalm-param` namiesto `@param`. Za typom môže nasledovať popis (`@var list Názvy vecí`). Položka je jeden nenulovateľný typ, preto `list` a `list` sú chybou kompilácie; použite DTO položky. Asociatívne polia, union typy okrem nulovateľných, `mixed`, `object` a netypované polia sa odmietnu pri kompilácii kontajnera, nie v polovici požiadavky. Predvolená hodnota zoznamu sa v tom istom čase skontroluje po položkách, takže `@param list` s predvolenou hodnotou `['x']` sa neskompiluje. + +Rovnaké DTO funguje s URL-enkódovanými formulárovými poľami a s multipart poľami, ak má property `#[File]` alebo `#[Consumes('multipart/form-data')]`. Vnorené polia používajú PHP zápis s hranatými zátvorkami, napríklad `address[street]` a `items[0][sku]`; `deliveryAt` ostáva rovnaký RFC 3339 reťazec. Parsovanie tela závisí od content typu, nie od JSON schémy. + +## Content typy tela + +`TypedHandler` s poľami tela predvolene akceptuje **`application/json`** aj **`application/x-www-form-urlencoded`**. Ak jeho DTO obsahuje property `#[File]`, predvolené typy sú **`application/json`** a **`multipart/form-data`**: multipart nahradí URL-enkódovaný formulár, pretože ten nedokáže preniesť súbory, a súbory sa posielajú spolu s poľami tela. Content type sa porovnáva bez parametrov, takže `application/json; charset=utf-8` je akceptovaný. JSON sa vždy číta ako UTF-8: iný `charset`, napríklad `application/json; charset=ISO-8859-1`, je `400` namiesto nesprávneho dekódovania (akceptuje sa `utf-8`, jeho bežný zápis `utf8` a `us-ascii`). Telo, ktoré príde bez akéhokoľvek `Content-Type`, je `415` aj keď sú všetky polia voliteľné, inak by sa potichu zahodilo. + +OpenAPI ponúka rovnaké možnosti v `requestBody.content`: JSON a URL-enkódovaný formulár alebo JSON a multipart pri súbore. Keď je súbor povinný, ponúka sa len multipart, pretože JSON požiadavka by mohla dostať len `400`. Properties so súbormi sú len v schéme `multipart/form-data`, pretože JSON nedokáže preniesť súbor. JSON požiadavka na DTO s povinným súborom dostane `400` s cestou poľa súboru a správou `File is required and can only be uploaded as multipart/form-data, but the request is application/json`. Polia tela sú parametre `TYPE_BODY` a súbory parametre `TYPE_FILE`; stále existuje len jedna cesta validácie a mapovania. + +### Obmedzenie akceptovaných typov cez Consumes + +Ak endpoint zámerne podporuje len jednu reprezentáciu, použite atribút triedy `#[Consumes]`. Akceptuje jeden alebo viac media typov: + +```php +#[Consumes('application/json')] +final class CreateOrderHandler extends TypedHandler +{ + public function handleDto(CreateOrderInput $input): ResponseInterface + { + // Len JSON + } +} +``` + +```php +#[Consumes('application/json', 'application/x-www-form-urlencoded')] +final class ImportHandler extends TypedHandler +{ + // Explicitne rovnaké dva typy ako predvolené pre DTO bez súborov. +} +``` + +Endpoint iba na nahrávanie použije `#[Consumes('multipart/form-data')]`. Obmedzenie na formulárový typ bez `multipart/form-data` znamená, že endpoint nemôže prijať súbory; nemožná kombinácia, napríklad povinný `#[File]` s konzumáciou len JSON, je chybou kompilácie kontajnera. + +Požiadavka s iným content typom sa pred mapovaním odmietne s **415 Unsupported Media Type**. 415 sa pošle až po autorizácii a obmedzeniach požiadaviek, takže klient bez prístupu dostane `401`, a `ApiLoggerInterface` ju zaloguje ako obslúženú požiadavku. Pri zapnutých detailoch chýb hláška uvádza prijatý typ aj presné akceptované typy, napríklad: + +```json +{ + "status": "error", + "message": "unsupported media type", + "detail": "Content-Type 'text/csv' is not supported for this endpoint. Use one of: application/json, application/x-www-form-urlencoded." +} +``` + +Chýbajúci content type tela pri požiadavke, ktorá telo vyžaduje, dostane rovnakú zrozumiteľnú 415 namiesto neskoršej chyby null property. Pri zapnutých Problem Details sa použije status 415 a rovnaká hláška v tomto formáte a jeho `detail` vždy uvádza akceptované typy. Predvolená obálka `detail` vynechá, keď sú detaily chýb vypnuté, rovnako ako pri chybách polí. + +### Rozdiely medzi JSON, formulárom a multipart + +| Oblasť | JSON | URL-enkódovaný formulár / multipart | +| --- | --- | --- | +| Vnorené DTO | objekty: `{"address":{"street":"Main 1"}}` | názvy so zátvorkami: `address[street]=Main+1` | +| Zoznamy DTO | polia: `"items":[{"sku":"BOOK-1"}]` | indexované názvy: `items[0][sku]=BOOK-1` | +| Natívne skalárne typy | čísla a booleany ostávajú JSON číslami/booleanmi | hodnoty prichádzajú ako reťazce a prechádzajú rovnakou striktnou konverziou | +| Null | explicitné `null` je povolené len pre nulovateľnú property | neexistuje null literál: vynechajte pole, aby použilo null alebo predvolenú hodnotu | +| Prázdny reťazec | skutočný reťazec, nie null | skutočný reťazec, nie null | +| Objekt vs zoznam | `{}` je objekt, aj keď mu chýbajú properties. `[]` je zoznam a je zamietnutý všade, kde sa vyžaduje objekt, vrátane prázdneho zoznamu. JSON objekt je zamietnutý tam, kde sa vyžaduje zoznam | názvy so zátvorkami tvoria objekt (`address[street]`); indexované názvy tvoria zoznam (`items[0]`) | +| Súbory | nepodporované | len `multipart/form-data` | + +Napríklad JSON `"quantity": 2` ostane integer, zatiaľ čo formulárové `quantity=2` sa stane integer až po tom, ako kompletný reťazec prejde striktnou konverziou. Ani jedno neakceptuje `2pcs`. JSON `false` a formulárové `remember=0` sú platné booleany; ľubovoľný neprázdny formulárový reťazec sa potichu nestane `true`. + +Pre voliteľnú formulárovú hodnotu vynechajte `deliveryAt` namiesto poslania `deliveryAt=null` alebo prázdnej hodnoty. Multipart súbor nemožno nahradiť JSON base64 reťazcom; aplikácia, ktorá potrebuje base64 uploady, môže ponechať `BaseHandler` a spracovať vlastné raw telo. + +PHP číta multipart telá len pri `POST`. Telo `multipart/form-data` poslané cez `PUT` alebo `PATCH` PHP nespracuje, preto endpoint odpovie `400` hláškou `multipart/form-data is only parsed by PHP for POST requests, but this one is PUT. Send it with POST, or use application/json`. Uploady a multipart formuláre posielajte cez `POST`. URL-enkódovaný formulár s viac poliami, než dovoľuje `max_input_vars` v PHP (predvolene 1000), je `400` s hláškou `Too many form fields`, pri `POST` aj pri `PUT` a `PATCH`. Multipart `POST` s väčším počtom polí PHP odreže skôr, než ho aplikácia uvidí, a nedá sa odlíšiť od úplného: pre takéto formuláre zvýšte `max_input_vars` alebo pošlite JSON. + +## Formuláre a endpointy autentifikované cez cookie + +URL-enkódovaný formulár je „jednoduchá“ požiadavka medzi webmi: stránka na ľubovoľnom webe ho môže odoslať do vášho API spolu s cookies návštevníka a bez CORS preflightu, čo telo JSON nedokáže. DTO s poľami tela formulár prijíma predvolene, takže endpoint autentifikovaný iba session cookie alebo adresou klienta sa dá zasiahnuť takým formulárom z cudzieho webu. Obmedzte ho na JSON cez `#[Consumes('application/json')]` a nastavte cookie `SameSite`. Endpointov autentifikovaných bearer tokenom alebo hlavičkou API kľúča sa to netýka, pretože formulár v prehliadači tieto hlavičky nastaviť nevie. + + +## Nahrávanie súboru + +```php +final readonly class AvatarInput +{ + public function __construct( + #[Body] + #[Length(min: 1, max: 80)] + public string $displayName, + + #[File(description: 'PNG or JPEG image')] + public FileUpload $avatar, + ) { + } +} +``` + +`FileUpload` je typovaný value object knižnice pre nahraný súbor. Sprístupňuje pôvodný názov, content type od klienta, dočasnú cestu, veľkosť a chybu nahrávania; neverí content typu od klienta ani automaticky nepresúva súbor. `?FileUpload` znamená voliteľný súbor a `list` prijme viac súborov v jednom poli. Pred uložením skontrolujte chybu nahrávania, veľkosť a skutočný typ, rovnako ako pri `FileInputParam`. Chyby nahrávania ako `UPLOAD_ERR_INI_SIZE` sa nemenia na validačné chyby; `FileUpload` ich nesie v `error`. Za chýbajúci súbor sa považuje len chýbajúci záznam alebo `UPLOAD_ERR_NO_FILE` s prázdnym názvom, a pri `list` keď majú všetky položky `UPLOAD_ERR_NO_FILE`. Požiadavky s nahrávaním musia používať `POST`, pozrite vyššie. `#[File]` patrí do vstupného DTO handlera; `#[File]` vo vnorenom DTO alebo v zozname DTO je chybou kompilácie, pretože PHP drží vnorené uploady v samostatnom strome `$_FILES` a polia tela sa nikdy nesmú čítať ako metadáta uploadu. + diff --git a/docs/sk/guide/typed-input-conversion.md b/docs/sk/guide/typed-input-conversion.md new file mode 100644 index 000000000..1e5a72c24 --- /dev/null +++ b/docs/sk/guide/typed-input-conversion.md @@ -0,0 +1,182 @@ +--- +title: 'Typovaný vstup: konverzia, castery a validačné obmedzenia' +description: 'Ako typované DTO v Nette API striktne konvertuje hodnoty, spúšťa vlastné castery a validuje cez Range, Length, Pattern, Email a vlastné validačné obmedzenia.' +--- + +# Typovaný vstup: konverzia, castery a validačné obmedzenia + +Táto stránka popisuje, čo sa stane s hodnotou medzi požiadavkou a property DTO: striktná konverzia, `#[Cast]` a atribúty validačných obmedzení. Základy sú v stránke [Typovaný vstup (DTO)](/sk/guide/typed-input). + +## Striktná konverzia + +Typovaný vstup sa nespolieha na voľné PHP pretypovania skalárov. + +| Cieľový typ | Akceptovaný vstup | +| --- | --- | +| `string` | reťazec, ktorý je platné UTF-8; hodnota z query, formulára, hlavičky alebo cesty s inými bajtmi je `400` `Value must be valid UTF-8` | +| `int` | celé číslo alebo reťazec len s voliteľným znamienkom a číslicami, v rozsahu PHP integer | +| `float` | integer/float alebo kompletný desatinný či vedecký číselný reťazec; NaN a nekonečno sa odmietnu | +| `bool` | boolean `true`/`false`, integer `1`/`0`, reťazec `'true'`/`'false'`/`'1'`/`'0'` (bez ohľadu na veľkosť písmen) | +| backed enum | presne jedna z jeho backing hodnôt; enumy s integer hodnotami používajú pravidlá konverzie integer | +| `DateTimeImmutable` | RFC 3339 reťazec s dátumom, časom a explicitným offsetom, napríklad `2026-11-06T14:30:00+01:00` (`T` a `Z` môžu byť malé písmená; priestupná sekunda ako `23:59:60` sa odmietne, pretože ju PHP nevie vyjadriť) | +| `array` | zoznam, ktorého každá položka zodpovedá typu z PHPDoc | + +Reťazec musí byť platné UTF-8, aby sa dal vložiť do JSON odpovede: `?q=%E9` (bajt Latin-1) je `400` `Value must be valid UTF-8` na poli, nie hodnota, pri ktorej `Length` alebo `Pattern` ohlási zavádzajúcu správu. JSON telo sa aj tak dekóduje ako UTF-8. Týka sa to len typovaného vstupu; handler s `params()` naďalej prijíma akékoľvek bajty ako doteraz, pretože zmena by odmietla požiadavky, ktoré dnes fungujú. + +`?page=1a` pre integer je `400`, nikdy `1` alebo `null`. Biele znaky sa implicitne neodstránia a neznáme reťazce sa nemenia na `false`. JSON čísla a booleany si zachovajú typy, takže celé číslo zapísané ako float, `1.0` alebo `1e2`, nie je integer: klient, ktorý celé čísla serializuje ako floaty, musí pre integer property poslať `1`. Normalizácia aplikácie patrí do handlera alebo vlastného validačného obmedzenia, nie do prekvapivých globálnych pretypovaní. + +Zoznam v query stringu používa PHP zápis so zátvorkami `ids[]=3&ids[]=4` a OpenAPI pomenuje parameter `ids[]`, aby ho vygenerovaní klienti posielali v tomto tvare. Hodnota oddelená čiarkami namiesto toho používa `Split`. Formulárové telá podporujú PHP názvy so zátvorkami; iné vnorené formulárové kódovania sa nedekódujú. V query môžu byť len skaláre, enumy a zoznamy z nich: vnorené DTO alebo `list` za `#[Query]` je chybou kompilácie, pretože OpenAPI nevie popísať vnorenie v PHP zápise so zátvorkami pre vygenerovaného klienta. Vnorené objekty čítajte z tela cez `#[Body]`. + +Mapovanie DTO podporuje len päť zdrojov vyššie; vstup z iného zdroja použije `params()` s vlastným `InputParam`. + +## Validačné obmedzenia + +Atribúty validačných obmedzení sú v `Tomaj\NetteApi\Validation` a dajú sa kombinovať na jednej property. Spúšťajú sa po úspešnej konverzii na skonvertovanú hodnotu; validačné obmedzenie na zozname validuje jeho dĺžku, nie jeho skalárne položky. + +| Atribút | Použitie | Význam | +| --- | --- | --- | +| `#[Range(min: 1, max: 100)]` | `int`, `float` | inkluzívne číselné hranice; jednu možno vynechať | +| `#[Length(min: 1, max: 80)]` | `string`, `array` | počet Unicode znakov alebo položiek zoznamu; jednu hranicu možno vynechať; zoznam nad `max` sa odmietne skôr, než sa namapujú jeho položky | +| `#[Pattern('/^[A-Z]+$/')]` | `string` | kompletná zhoda s PCRE, `$` sedí len na úplnom konci, pretože sa pridáva modifikátor `D` (`/^[0-9]{5}$/` odmietne `81101` s koncovým novým riadkom); neplatný pattern je chybou kompilácie; pattern je PCRE, nie JavaScript, a vždy sa kontroluje cez PCRE; OpenAPI `pattern` je ECMA 262, preto ho dostane len výraz, ktorý tam znamená to isté, a inak sa celý PCRE pattern (aj s oddeľovačmi a príznakmi) uvedie v rozšírení `x-pattern`; ten jednoduchý podjazyk tvoria ASCII literály, escapované interpunkčné znaky, `\n`, `\r`, `\t`, triedy z literálov a rozsahov (aj s `\-`), skupiny, lookahead, alternatívy, kotvy a kvantifikátory, bez iného príznaku než `u` a `D`, pričom `\d`, `\w` a `\b` len bez `u`, pretože PCRE ich s `u` číta ako Unicode a JavaScript nie; všetko ostatné ide do `x-pattern`, medzi tým bodka, negované triedy, `\s`, `\D`, `\W`, `\p{L}`, `\x`, spätné odkazy, pomenované skupiny, lookbehind, znaky mimo ASCII, posesívne kvantifikátory, atomické skupiny, inline flagy a príznaky ako `i` | +| `#[Email]` | `string` | platná emailová adresa | + +Validácia zhromaždí všetky chyby polí, nezastaví sa na prvej; jedna požiadavka nahlási najviac prvých 100 chýb spolu, aj z vnorených zoznamov, zvyšok tela sa nekontroluje a potom príde poznámka `Only the first 100 errors are reported, the rest of the request was not checked` pod kľúčom `body`, len ak sa skutočne niečo nechalo nekontrolované. Hlášky uvádzajú skutočné limity, napríklad `Value must have between 1 and 50 items` namiesto všeobecného `Invalid value`. + +### Vlastné validačné obmedzenia + +Vlastné validačné obmedzenie implementuje `ConstraintInterface` a zároveň je PHP atribútom: + +```php +interface ConstraintInterface +{ + public function validate(mixed $value, ConstraintContext $context): ?string; +} +``` + +Pri úspechu vráti `null`, pri chybe jednu hlášku zrozumiteľnú vývojárovi. `ConstraintContext` sprístupňuje cestu property, triedu DTO a `value('sibling')` pre ostatné skonvertované properties toho istého DTO; predvolené hodnoty sa kontrolujú pri kompilácii kontajnera spolu so všetkými predvolenými hodnotami súrodencov a súrodenec bez predvolenej hodnoty je tam `null`; validačné obmedzenia nesmú hádzať výnimky pre bežný neplatný vstup klienta. Vlastné validačné obmedzenia nemajú reprezentáciu v OpenAPI, pokiaľ aplikácia nerozšíri OpenAPI buildery. + +### Validačné obmedzenia položiek zoznamu + +Obmedzenie na zozname validuje zoznam, takže pre `list` alebo `list` neexistujú validačné obmedzenia jednotlivých položiek. Ak chcete skontrolovať každú položku, napíšte vlastné validačné obmedzenie, ktoré prejde zoznam v cykle, alebo použite zoznam malých DTO položiek, ktorý validuje každú položku a hlási ju ako `items[1].quantity`. + +## Vlastné konverzie cez Cast + +`#[Cast]` použite, keď má pole aplikačne špecifickú textovú reprezentáciu. Pomenuje triedu castera a voliteľne odovzdá argumenty konštruktora: + +```php +interface CasterInterface +{ + public function cast(mixed $value): mixed; +} + +final class CastException extends RuntimeException +{ +} +``` + +Castery sú v `Tomaj\NetteApi\Input` vrátane `DateFormat`, `UnixTimestamp` a `Split`. Caster beží **namiesto** vstavanej konverzie pre danú property. Spustí sa ako prvý, vráti deklarovanú hodnotu property a až potom sa na skonvertovanej hodnote spustia `Range`, `Length`, `Pattern`, `Email` a vlastné validačné obmedzenia. Vnorené cesty fungujú presne ako inde. + +Caster hlási neplatný klientsky vstup vyhodením `Tomaj\NetteApi\Input\CastException` so zrozumiteľnou hláškou. Zmení sa na 400 v bežnej chybovej obálke pod cestou property: + +```json +{ + "status": "error", + "message": "wrong input", + "detail": { + "issuedOn": ["Date must match d.m.Y, for example 24.12.2026"] + } +} +``` + +Iné výnimky sú chyby programátora/servera a nemaskujú sa ako klientske validačné chyby. Kompilácia kontajnera overí, že trieda castera existuje, je inštanciovateľná, implementuje `CasterInterface`, akceptuje deklarované argumenty atribútu a má natívny návratový typ `cast()` zhodný s typom property (alebo zdokumentovaný kovariantný typ podtriedy). Caster pre `list` musí deklarovať `array` so zhodným PHPDoc položiek zoznamu. Kontrola je obmedzená na natívne deklarácie; `mixed` nie je akceptovaný ako návratový typ castera. Nekompatibilný caster zlyhá pri kompilácii, nie pri prvej požiadavke. + +### Nápovedy OpenAPI schémy + +Caster môže voliteľne implementovať `OpenApiCasterInterface` popri `CasterInterface`: + +```php +interface OpenApiCasterInterface +{ + /** @return array{type?: string, format?: string, example?: mixed} */ + public function openApiSchema(): array; +} +``` + +Vrátené `type`, `format` a `example` popisujú **hodnotu na drôte**, nie výsledný PHP objekt. Bez tohto voliteľného rozhrania OpenAPI použije reťazcovú schému a formát môže popísať description/example DTO. Caster nikdy nemení runtime validáciu cez svoju nápovedu schémy. + +### Vstavané castery a český dátum + +`DateFormat`, `UnixTimestamp` a `Split` pokrývajú bežné neštandardné reprezentácie: + +| Caster | Príklad vstupu | Výsledok | +| --- | --- | --- | +| `#[Cast(DateFormat::class, 'd.m.Y')]` | `'24.12.2026'` | `DateTimeImmutable` o polnoci, odmietne nemožné dátumy a vstup s koncovkou | +| `#[Cast(UnixTimestamp::class)]` | `1798185600` alebo `'1798185600'` | `DateTimeImmutable` zo sekúnd od Unix epoch | +| `#[Cast(Split::class, ',')]` | `'red,green,blue'` | `list` (vždy reťazce: property `list` potrebuje vlastný caster); bez implicitného trimovania alebo odstraňovania prázdnych položiek | + +```php +final readonly class IssueInput +{ + public function __construct( + #[Body] + #[Cast(DateFormat::class, 'd.m.Y')] + public DateTimeImmutable $issuedOn, + ) { + } +} +``` + +Nápoveď schémy `DateFormat('d.m.Y')` je `{type: string, example: '24.12.2026'}`. Len `DateFormat('Y-m-d')` pridá `format: date`, pretože OpenAPI `date` znamená plný dátum podľa RFC 3339. NUL bajt alebo iná nespracovateľná hodnota je `400` na danom poli, nie výnimka. + +### CSV na list<string> + +```php +final readonly class ReportInput +{ + /** @param list $columns */ + public function __construct( + #[Query] + #[Cast(Split::class, ',')] + public array $columns = [], + ) { + } +} +``` + +V OpenAPI je property jeden reťazec s príkladom `red,green,blue` a konzola ukazuje jedno textové pole. `?columns=id,createdAt,total` sa zmení na `['id', 'createdAt', 'total']`. `Split` vráti prázdny zoznam pre vynechanú voliteľnú property len cez jej bežnú predvolenú hodnotu; explicitne prítomný prázdny reťazec vytvorí `['']`, čo môže validačné obmedzenie zamietnuť. + +### Desatinný reťazec na value object Money + +Vlastná trieda castera môže vytvoriť value object aplikácie. Nasledujúci príklad zámerne spracuje desatinnú čiarku bez konverzie na float: + +```php +final readonly class DecimalMoneyCaster implements CasterInterface, OpenApiCasterInterface +{ + public function cast(mixed $value): Money + { + if (!is_string($value) || !preg_match('/^(0|[1-9][0-9]*),([0-9]{2})$/D', $value, $m)) { + throw new CastException('Money must use a comma and exactly two decimal places, for example 12,50'); + } + + return Money::fromMinorUnits(((int) $m[1]) * 100 + (int) $m[2], 'EUR'); + } + + public function openApiSchema(): array + { + return ['type' => 'string', 'example' => '12,50']; + } +} + +final readonly class PriceInput +{ + public function __construct( + #[Body] + #[Cast(DecimalMoneyCaster::class)] + public Money $price, + ) { + } +} +``` + +`12,50` sa stane `Money` a následné vlastné validačné obmedzenie `PositiveMoney` dostane tento objekt `Money`. `12.50`, `1a` a pole vytvoria 400 na `price` s hláškou castera. Formátovanie špecifické pre menu ostáva v casteri aplikácie namiesto ďalšieho globálneho skalárneho pravidla. Keďže caster nahrádza vstavanú konverziu, `Money` sa nikdy nekompiluje ako transportné DTO: môže mať privátny konštruktor a statickú továrenskú metódu a kompilátor len skontroluje, že `cast()` deklaruje návratový typ `Money`. Pomenované argumenty castera, napríklad `#[Cast(MyCaster::class, suffix: 'x')]`, si v skompilovanom kontajneri zachovajú názvy. + diff --git a/docs/sk/guide/typed-input.md b/docs/sk/guide/typed-input.md new file mode 100644 index 000000000..f265bc7d6 --- /dev/null +++ b/docs/sk/guide/typed-input.md @@ -0,0 +1,290 @@ +--- +title: Typovaný vstup (DTO) +description: 'Typované DTO požiadavky v Nette API: atribúty Query, Path, Header, Body a File, povinné hodnoty, chyby, OpenAPI a API konzola. Druhý, rovnocenný spôsob deklarácie vstupu handlera popri params().' +--- + +# Typovaný vstup (DTO) + +Triedy na tejto stránke sú súčasťou Nette API 4.0. Spustiteľný projekt je v [`examples/typed-input`](/sk/examples/typed-input). + +Typované vstupné DTO drží kontrakt požiadavky pri hodnotách, ktoré handler používa. Atribúty určujú, odkiaľ hodnota pochádza, typy properties určujú jej PHP typ a atribúty validačných obmedzení validáciu. Rovnaká deklarácia napája validáciu, OpenAPI aj API konzolu. + +Viac o štýle s DTO: [telo, súbory a content typy](/sk/guide/typed-input-body), [konverzia, castery a validačné obmedzenia](/sk/guide/typed-input-conversion). + +## params() alebo DTO + +Handler deklaruje svoj vstup jedným z dvoch rovnocenných spôsobov. Oba sú plne podporované, zdieľajú registráciu, autorizáciu, obmedzenia požiadaviek, výstupy, OpenAPI aj konzolu a v jednej aplikácii sa dajú ľubovoľne miešať. + +| | `params()` | Typované DTO | +| --- | --- | --- | +| Handler | `BaseHandler` s `params()` a `handle(array $params)` | `TypedHandler` s `handleDto(SomeInput $input)` | +| Deklarujete | zoznam objektov `InputParam` | readonly triedu s atribútmi na properties konštruktora | +| Handler dostane | pole zvalidovaných hodnôt | typovaný objekt | +| Konverzia | konverzia `InputType` z [Vstupných parametrov](/sk/guide/params) | striktná konverzia z [typovaného vstupu](/sk/guide/typed-input-conversion) | +| Vnorené telá | `JsonInputParam` s JSON schémou | vnorené DTO a zoznamy DTO, validované rekurzívne | +| Vlastný zdroj vstupu | ľubovoľná podtrieda `InputParam` | nie je k dispozícii, existuje päť atribútov zdroja | + +`params()` zvoľte, keď endpoint spolieha na jeho voľnejšiu konverziu, na vlastný `InputParam` alebo na ručné spracovanie nezvyčajného tela. DTO zvoľte, keď chcete typované hodnoty, vnorené telá, validačné obmedzenia cez viac polí alebo celý kontrakt požiadavky v jednej triede. Ani jeden štýl nie je zastaraný a voľba štýlu pre jeden endpoint neovplyvní žiadny iný. [params() a DTO vedľa seba](/sk/guide/input-styles) ukazuje ten istý endpoint napísaný oboma štýlmi. + +`TypedHandler` prevedie deklaráciu DTO na tie isté objekty `InputParam`, ktoré vracia `params()`. + +## Najmenší handler + +Rozšírte `TypedHandler` a v `handleDto()` deklarujte práve jeden nenulovateľný parameter DTO. Trieda parametra `handleDto()` je vstupné DTO; netreba ju opakovať v atribúte ani konfigurácii. + +```php +namespace App\Api; + +use Tomaj\NetteApi\Handlers\TypedHandler; +use Tomaj\NetteApi\Input\Query; +use Tomaj\NetteApi\Response\JsonApiResponse; +use Tomaj\NetteApi\Response\ResponseInterface; +use Tomaj\NetteApi\Validation\Range; + +final readonly class ListUsersInput +{ + public function __construct( + #[Query(description: 'Page number')] + #[Range(min: 1)] + public int $page = 1, + + #[Query] + public ?UserStatus $status = null, + ) { + } +} + +final class ListUsersHandler extends TypedHandler +{ + public function handleDto(ListUsersInput $input): ResponseInterface + { + return new JsonApiResponse(200, [ + 'page' => $input->page, + 'status' => $input->status?->value, + 'users' => [], + ]); + } +} +``` + +`GET /api/v1/users/list?page=2&status=active` vytvorí `ListUsersInput` s celočíselnou hodnotou `page` a enumom `UserStatus`. `TypedHandler` implementuje `handle(array $params)` ako final; aplikačný kód píše len `handleDto()`. + +Závislosti v konštruktore, `summary()`, `description()`, `outputs()`, tagy a registrácia fungujú ako pri `BaseHandler`. Atribúty endpointu a autorizácie sú nezávislé od vstupných atribútov a dajú sa kombinovať. + +## Atribúty zdroja + +Atribúty sú v `Tomaj\NetteApi\Input` a cielia na promované properties konštruktora. Každá promovaná property má práve jeden atribút zdroja. Externý názov je predvolene názov property; odovzdaním názvu ho zmeníte. `description` a opakovateľné `examples` sa stanú popisom a príkladmi vygenerovaného `InputParam`. + +| Atribút | Zdroj | Typ vygenerovaného parametra | +| --- | --- | --- | +| `#[Query]` | query string | `InputParam::TYPE_GET`, OpenAPI `in: query` | +| `#[Path]` | nájdená cesta endpointu | `InputParam::TYPE_PATH`, OpenAPI `in: path` | +| `#[Header]` | HTTP hlavička | `InputParam::TYPE_HEADER`, OpenAPI `in: header` | +| `#[Body]` | pole JSON, formulárového alebo multipart tela | `InputParam::TYPE_BODY`, časť `requestBody` | +| `#[File]` | nahraný súbor | `InputParam::TYPE_FILE`, multipart `requestBody` | + +Každá property DTO sa stane jedným `MappedInputParam`, teda `InputParam`, ktorý validuje a mapuje cez metadáta DTO. Kód, ktorý skúma `params()`, kontroluje `getType()`, nie konkrétnu triedu. + +Napríklad `#[Header('X-Request-Id')] public ?string $requestId = null` číta `X-Request-Id`, nie `requestId`. Vyhľadávanie hlavičky nerozlišuje veľkosť písmen. Názov v `#[Path]` začína písmenom alebo podčiarkovníkom a má písmená, číslice a podčiarkovníky, pretože sa píše ako segment `{name}`; názov v `#[Header]` používa pomlčky, nie podčiarkovníky (`X-Request-Id`, nie `X_Request_Id`), pretože PHP sprístupňuje názvy hlavičiek s pomlčkami. Čokoľvek iné je chybou kompilácie s opraveným názvom. Hodnota z cesty alebo hlavičky je jeden reťazec, preto je tam natívny zoznam alebo vnorené DTO chybou kompilácie; rozdeľte ju casterom, napríklad `#[Header('X-Tags')] #[Cast(Split::class, ',')] public array $tags`. + +`PathInputParam` a `HeaderInputParam` sú verejné aj pre handlery, ktoré používajú `params()`, pozrite [Vstupné parametre](/sk/guide/params#parametre-path-header-a-body). + +`#[Header]` nepoužívajte pre hlavičku, ktorú proxy nastavuje alebo odstraňuje ako nositeľku dôvery, napríklad `X-Forwarded-User`. PHP a webservery mapujú `X_Request_Id` aj `X-Request-Id` na rovnaký názov, takže klient môže poslať podobne vyzerajúcu hlavičku. Takéto hodnoty overte v proxy a kópiu od klienta tam zahoďte. Hlavička `Authorization` sa číta aj z `REDIRECT_HTTP_AUTHORIZATION`, ktorú Apache s CGI alebo FastCGI nastaví po prepise, napríklad `RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]`. `BearerTokenAuthorization` ju číta rovnako, takže token, ktorý sa dostane do `#[Header('Authorization')]`, sa dostane aj do autorizácie. Ostatné hlavičky sa čítajú zo serverových premenných `HTTP_*`. + +### Hodnoty z cesty a šablóny URL + +Hodnota z cesty sa deklaruje v URL endpointu ako `{name}`, napríklad `users/{id}/detail`. Je povinná, nemôže byť nulovateľná ani mať predvolenú hodnotu a placeholder v OpenAPI ceste má rovnaký názov. Chýbajúci alebo nedeklarovaný parameter cesty je chybou kompilácie kontajnera. Statické URL endpointov fungujú bez zmeny. Hodnota z cesty je jeden segment URL: cesta sa pred porovnaním dekóduje, takže zakódované lomítko (`%2F`) sa číta ako oddeľovač a endpoint sa nenájde. Hodnotu, ktorá môže obsahovať `/`, posielajte v query alebo v tele. + +Šablónu zaregistrujte ako akciu endpointu niektorým zo zvyčajných spôsobov: + +```yaml +api: + endpoints: + - {method: GET, version: 1, package: users, action: '{id}/detail', handler: App\Api\UserDetailHandler} +``` + +```php +#[Get(1, 'users', '{id}/detail')] +final class UserDetailHandler extends TypedHandler +``` + +```php +$apiDecider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), new UserDetailHandler(), new NoAuthorization()); +``` + +Route musí prepustiť aj dodatočný segment, ako to robí route v [príklade typovaného vstupu](/sk/examples/typed-input): `/api/v/[/][/]`. Požiadavka sa hľadá najprv medzi statickými endpointmi a potom medzi šablónami. Ak jednej URL vyhovujú dve šablóny, požiadavka skončí s `LogicException`, ktorá pomenuje obe, takže zmeňte statický segment tak, aby sa líšili. + +### Povinné hodnoty a predvolené hodnoty + +Nenulovateľná property bez predvolenej hodnoty je povinná. Nulovateľná property alebo property s predvolenou hodnotou je voliteľná. Chýbajúca nulovateľná hodnota sa stane `null`; chýbajúca hodnota s predvolenou hodnotou použije túto hodnotu. Rovnako sa nastaví `required` v OpenAPI. + +Povinné parametre cesty nemôžu byť nulovateľné ani mať predvolenú hodnotu. Voliteľné pole tela akceptuje vynechanie poľa, zatiaľ čo explicitné JSON `null` akceptuje len nulovateľná property. Prázdny reťazec sa potichu nemení na `null`. Predvolená hodnota je `null`, skalár, pole alebo case backed enumu; objekt ako predvolená hodnota, napríklad `= new Inner()`, je chybou kompilácie, pretože predvolené hodnoty sa ukladajú do skompilovaného kontajnera. Použite `= null` a objekt vytvorte v handleri. + +## Kompletný príklad požiadavky + +### GET s query, cestou a hlavičkou + +```php +final readonly class UserDetailInput +{ + public function __construct( + #[Path] + #[Range(min: 1)] + public int $id, + + #[Query] + #[Range(min: 1, max: 100)] + public int $limit = 20, + + #[Query] + public ?UserStatus $status = null, + + #[Header('X-Request-Id')] + public ?string $requestId = null, + ) { + } +} +``` + +Požiadavka: + +```http +GET /api/v1/users/42/detail?limit=10&status=active HTTP/1.1 +X-Request-Id: req-01J8Y7N6R9 +``` + +Handler dostane `id: 42`, `limit: 10`, `status: UserStatus::Active` a reťazec s ID požiadavky. Nie sú potrebné pretypovania ani prístupy ku kľúčom poľa. + + +Požiadavka s telom, vnoreným DTO a zoznamom je v stránke [telo, súbory a content typy](/sk/guide/typed-input-body#post-s-vnorenym-dto-a-polom). + +## Chybové odpovede + +Obálka odpovede ostáva rovnaká ako pri `ParamsProcessor`. Kľúč detailu je cesta poľa: bodky vstupujú do vnorených DTO a hranaté zátvorky označujú položky zoznamu. Najvyššie zdroje používajú svoje externé názvy. + +```json +{ + "status": "error", + "message": "wrong input", + "detail": { + "customerEmail": ["Email must be a valid email address"], + "address.postalCode": ["Value must match the pattern /^[0-9]{5}$/"], + "items[1].quantity": ["Value must be at least 1"], + "deliveryAt": ["DateTime must be a valid RFC 3339 date and time"] + } +} +``` + +Pri vypnutých detailoch chýb sa vrátia len `status` a `message`. So zapnutými Problem Details sa rovnaké cesty polí a hlášky objavia v jeho rozšírení pre chyby vstupu. Pokazené JSON a nečitateľné telo zachovajú existujúce chyby parsera tela. + +Kľúč `body` nesie aj zlyhania tela požiadavky ako celku, napríklad `Too many form fields`, nesprávny charset JSON a poznámku, že sa hlásia len prvých 100 chýb. Pole DTO, ktoré sa samo volá `body`, ten kľúč zdieľa, takže jeho hlášky sa vypíšu spolu s nimi; ak ich chcete oddeliť, dajte property iný externý názov, napríklad `#[Body('payload')]`. + +Chýbajúci vnorený objekt nahlási cestu vnoreného objektu. Neznáme vstupné polia sa ignorujú, rovnako ako pri bežných query/formulárových parametroch; potichu sa nemapujú na properties. + +## OpenAPI a API konzola + +`TypedHandler::params()` sprístupní vygenerované objekty `InputParam`, takže existujúca konzola automaticky získa popisky, označenie povinnosti, predvolené hodnoty, príklady, voľby enumov a polia pre súbory. Konzola pošle každú hodnotu do jej zdroja: hodnoty z cesty sa URL-enkódujú do segmentov `{name}`, hodnoty hlavičiek sa stanú hlavičkami požiadavky a hodnoty tela sa pošlú v prvom media type, ktorý handler číta a konzola ho vie zostaviť: JSON s deklarovanými typmi (pole s vnoreným DTO berie JSON text, pole so zoznamom má jeden vstup na položku a položka DTO berie JSON text), URL-enkódovaný formulár alebo multipart. Súbor vždy znamená multipart, s názvami so zátvorkami pre vnorené polia. Neexistuje osobitný DTO režim konzoly, pozrite [Webová konzola](/sk/guide/console). + +V OpenAPI sa query, path a header properties stanú parametrami operácie. Properties tela sa spoja do jednej objektovej schémy; vnorené DTO a zoznamy sa stanú vnorenými schémami. Predvolene `requestBody.content` obsahuje `application/json` aj `application/x-www-form-urlencoded`, alebo JSON a `multipart/form-data`, ak DTO obsahuje súbor. `#[Consumes]` obmedzí tento zoznam aj akceptované požiadavky na explicitné media typy. Operácia s telom dokumentuje aj odpoveď `415`. `nullable: true` sa objaví len pri properties tela: query reťazec, segment cesty ani hlavička nemôžu niesť `null`, takže voliteľná hodnota z query alebo hlavičky jednoducho chýba. Nulovateľný enum uvádza `null` vo svojom `enum`, ako to vyžaduje OpenAPI 3.0.3. + +Príklad GET vyššie pridá tento fragment operácie (odpovede a nesúvisiace polia sú vynechané): + +```openapi +parameters: + - name: id + in: path + required: true + schema: {type: integer, minimum: 1} + - name: limit + in: query + required: false + schema: {type: integer, minimum: 1, maximum: 100, default: 20} + - name: status + in: query + required: false + schema: {type: string, enum: [active, disabled]} + - name: X-Request-Id + in: header + required: false + schema: {type: string} +``` + +Príklad POST pridá: + +```openapi +requestBody: + required: true + content: + application/json: + schema: + type: object + required: [customerEmail, address, items] + properties: + customerEmail: {type: string, format: email} + address: + type: object + required: [street, postalCode] + properties: + street: {type: string, minLength: 1, maxLength: 120} + postalCode: {type: string, pattern: '^[0-9]{5}$'} + items: + type: array + minItems: 1 + maxItems: 50 + items: + type: object + required: [sku, quantity] + properties: + sku: {type: string} + quantity: {type: integer, minimum: 1} + deliveryAt: {type: string, format: date-time, nullable: true} +``` + +JSON schéma sa tu generuje len ako výstupný formát OpenAPI. Runtime validácia používa rekurzívny mapper DTO a nikdy nevyžaduje JSON schému. + +### Dlho bežiace workery + +Hodnoty požiadavky typovaného handlera (telo, súbory, hodnoty z cesty a hlavičiek) sa držia v statickom stave pre aktuálnu požiadavku. `ApiPresenter::run()` ho vynuluje na začiatku každej požiadavky, takže PHP-FPM, RoadRunner, worker režim FrankenPHP aj Swoole vidia len aktuálnu požiadavku, pokiaľ každá požiadavka prechádza cez `ApiPresenter` a worker spracúva jednu požiadavku naraz. Súbežné požiadavky v jednom procese, napríklad prekladané Swoole korutiny, nie sú podporované, pretože stav je spoločný pre celý proces. Kód, ktorý vo workeri volá `params()` typovaného handlera mimo presentera, napríklad test alebo CLI príkaz, najprv zavolá `Tomaj\NetteApi\Input\RequestInput::reset()` a `Tomaj\NetteApi\Params\PathValues::reset()`. + + +## Bezpečnostné poznámky + +- **Mapovanie beží pred autorizáciou.** Vstup sa konvertuje a validuje skôr, ako sa skontroluje autorizácia, a čaká až odpoveď: klient bez prístupu dostane `401`, nie chyby polí. Obmedzenie požiadaviek beží stále ako prvé. Caster alebo validačné obmedzenie je teda dostupné bez prihlásenia, preto ich držte čisté a lacné: žiadny prístup k databáze, sieti ani súborom. Na každý zoznam dajte `#[Length(max: ...)]`. Jedna požiadavka nahlási najviac 100 chýb spolu, nech sú zoznamy a objekty vnorené akokoľvek hlboko; zvyšok tela sa nekontroluje. +- **Veľkosť tela obmedzte na webservery.** `#[Length(max: ...)]` obmedzí zoznam skôr, ako sa jeho položky mapujú, ale telo sa dekóduje ako prvé a zoznam malých objektov zaberie v PHP oveľa viac pamäte než v požiadavke (až zhruba 70-krát pri zozname malých objektov, približne 18-krát pri zozname čísel). Obmedzte veľkosť tam, kde požiadavka vstupuje: `client_max_body_size` v nginx, `LimitRequestBody` v Apache a `post_max_size` s `memory_limit` v PHP. +- **`#[Header]` nie je dôkaz pôvodu.** Pozrite poznámku pod [atribútmi zdroja](#atributy-zdroja). +- **Formuláre a cookies.** DTO s poľami tela predvolene prijíma URL-enkódované formuláre, ktoré môže odoslať ľubovoľný web bez CORS preflightu. Pre endpoint autentifikovaný cookie alebo adresou klienta použite `#[Consumes('application/json')]`, pozrite [telo, súbory a content typy](/sk/guide/typed-input-body#formulare-a-endpointy-autentifikovane-cez-cookie). + +## Príklad + +`examples/typed-input` má rovnaký samostatný Composer layout a konvenciou `e2e.sh` v CI ako ostatné príklady. Súbory sú rozložené ako v ostatných príkladoch (`public/index.php`): + +```text +examples/typed-input/ +├── composer.json +├── README.md +├── e2e.sh +├── config/common.neon +├── public/index.php +└── app/Api/ + ├── ListUsersHandler.php # query, enum s hodnotou a predvolené hodnoty + ├── UserDetailHandler.php # path id a hlavička X-Request-Id + ├── CreateOrderHandler.php # JSON/formulárové telo, vnorené DTO a list + ├── AvatarUploadHandler.php # multipart telo a FileUpload + └── Input/ # readonly DTO a UserStatus +``` + +End-to-end test pokrýva úspešné JSON, formulárové a multipart požiadavky, predvolené hodnoty, konverziu enumov, každý atribút zdroja, striktné zamietnutie `1a`, cesty vnorených chýb a vygenerovaný OpenAPI dokument. CI ho spúšťa spolu s ostatnými príkladmi. + + +## Ako je to postavené + +- **Metadáta pri kompilácii.** `NetteApiExtension` reflektuje DTO a zapíše ich definície `InputParam` a metadáta mapovania do skompilovaného kontajnera. Požiadavky ani generovanie OpenAPI DTO znova nereflektujú a nepotrebujú žiadne nastavenie invalidácie cache; backing typy enumov sa cachujú pre každú triedu. Zmena DTO, jeho rodičovskej triedy, traitu, ktorý používa, casteru, validačného obmedzenia alebo enumu prebuduje kontajner rovnako ako zmena atribútov endpointov. Bez DI rozšírenia sa raz za požiadavku zostaví malý register vygenerovaných metadát; nepridáva sa žiadna runtime závislosť na Nette Cache. +- **Jeden pipeline metadát.** Metadáta DTO sa prekladajú na existujúce objekty `InputParam`, takže validácia, OpenAPI a konzola nemajú osobitné vetvy pre DTO. +- **Rekurzívna runtime validácia.** Spracuje JSON, formulár aj multipart rovnako a dáva presné cesty k properties. JSON schéma sa generuje len pre OpenAPI. +- **Iba readonly promoted properties.** DTO sa vytvoria raz cez konštruktor a mapper ich nemôže čiastočne meniť. Povinný parameter konštruktora, ktorý nie je promoted property, a variadické alebo referenčné parametre sú chybou kompilácie. +- **Striktná, explicitná konverzia skalárov.** Neplatné dáta od klienta sú `400`, nie prekvapivý cast. +- **Malá sada validačných obmedzení.** Range, Length, Pattern a Email pokrývajú bežné kontrakty API; vlastné validačné obmedzenia pokrývajú pravidlá aplikácie bez validačného frameworku. +- **Predvolene JSON aj formulár, `Consumes` obmedzuje.** Jedno DTO obslúži klientov s JSON aj formulárom a OpenAPI inzeruje rovnaké media typy; keď je prítomný súbor, multipart nahradí URL-enkódovaný formulár, ktorý súbory nezvládne. `Consumes` je atribút na úrovni triedy ako ostatné atribúty endpointov a jeho názov ho odlišuje od HTTP hlavičky `Accept`, ktorá sa týka odpovedí. +- **`handleDto(Input $input)` ako metóda handlera.** Názov hovorí, že ide o vstupný bod handlera, a reflexia číta triedu DTO z jeho parametra, takže netreba ďalší atribút ani konfiguráciu. +- **`Cast` s `CasterInterface`.** Formáty aplikácie ostávajú pri property, argumenty konštruktora pokrývajú voľby ako `d.m.Y` a `CastException` dáva chyby 400 s cestou k poľu. Voliteľné rozhranie nápovedy schémy necháva metadáta OpenAPI pre castery nepovinné. + diff --git a/docs/sk/index.md b/docs/sk/index.md index cde77773a..a7679a1a8 100644 --- a/docs/sk/index.md +++ b/docs/sk/index.md @@ -20,11 +20,11 @@ hero: features: - icon: '' title: Handlery namiesto presenterov - details: Každý endpoint je malá trieda s params(), outputs() a handle(). ApiDecider k nej priradí metódu, verziu a balík. + details: Každý endpoint je malá trieda. Jej vstup deklarujete cez params() a handle() alebo cez typované DTO a handleDto(). ApiDecider k nej priradí metódu, verziu a balík. link: /sk/guide/handlers - icon: '' title: Validovaný vstup - details: GET, POST, PUT, cookie, súbor, raw a JSON telo s typmi, povolenými hodnotami a JSON schémami. Zlý vstup vráti 400. + details: Vstup z query, cesty, hlavičky, cookie, súboru, formulára a JSON tela, ako parametre alebo ako properties typovaného DTO, s typmi, validačnými obmedzeniami a JSON schémami. Zlý vstup vráti 400. link: /sk/guide/params - icon: '' title: Autorizácia a limity @@ -40,9 +40,32 @@ features: -Handler je jedna trieda: +Handler je jedna trieda. Jej vstup je zoznam parametrov alebo typované DTO, podľa toho, čo sa k endpointu hodí: -<<< @/../examples/hello-world/app/Api/HelloHandler.php +::: code-group + +<<< @/../examples/hello-world/app/Api/HelloHandler.php [params()] + +```php [Typed DTO] +final readonly class HelloInput +{ + public function __construct( + #[Query(description: 'Who to greet')] + public string $name = 'world', + ) { + } +} + +final class HelloHandler extends TypedHandler +{ + public function handleDto(HelloInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['message' => 'Hello ' . $input->name . '!']); + } +} +``` + +::: a niekoľko riadkov konfigurácie ho zaregistruje ako `GET /api/v1/hello`: @@ -55,8 +78,8 @@ a niekoľko riadkov konfigurácie ho zaregistruje ako `GET /api/v1/hello`: ## Časté otázky diff --git a/examples/attributes/README.md b/examples/attributes/README.md index 187c4ec3e..46e922141 100644 --- a/examples/attributes/README.md +++ b/examples/attributes/README.md @@ -6,12 +6,15 @@ Documentation: [tomaj.github.io/nette-api/examples/attributes](https://tomaj.git Needs nette-api 4.0. +`GET /api/v1/greet` is the same kind of endpoint as `hello` written with a typed input DTO (`TypedHandler`), next to the `params()` handlers. + ## Run it ```bash composer install php -S 127.0.0.1:8000 -t public public/index.php curl -i http://127.0.0.1:8000/api/v1/hello +curl 'http://127.0.0.1:8000/api/v1/greet?name=Nette' curl -i -H 'Authorization: Bearer secret-token' http://127.0.0.1:8000/api/v1/users ``` diff --git a/examples/attributes/app/Api/GreetHandler.php b/examples/attributes/app/Api/GreetHandler.php new file mode 100644 index 000000000..12c7e9e76 --- /dev/null +++ b/examples/attributes/app/Api/GreetHandler.php @@ -0,0 +1,22 @@ + 'Hello ' . $input->name . '!']); + } +} diff --git a/examples/attributes/app/Api/GreetInput.php b/examples/attributes/app/Api/GreetInput.php new file mode 100644 index 000000000..2083af1c0 --- /dev/null +++ b/examples/attributes/app/Api/GreetInput.php @@ -0,0 +1,19 @@ + 'Hello ' . $input->name . '!']); + } +} diff --git a/examples/di-extension/app/Api/GreetInput.php b/examples/di-extension/app/Api/GreetInput.php new file mode 100644 index 000000000..2083af1c0 --- /dev/null +++ b/examples/di-extension/app/Api/GreetInput.php @@ -0,0 +1,19 @@ +inner->handleRateLimit($rateLimit); } + + public function handleUnsupportedMediaType(string $detail): ResponseInterface + { + return $this->inner->handleUnsupportedMediaType($detail); + } } diff --git a/examples/typed-input/README.md b/examples/typed-input/README.md new file mode 100644 index 000000000..ffb0d93d3 --- /dev/null +++ b/examples/typed-input/README.md @@ -0,0 +1,28 @@ +# Typed input + +A small API whose handlers extend `TypedHandler` and read a readonly DTO: query, path, header, JSON or form body and a multipart file. + +Documentation: [tomaj.github.io/nette-api/examples/typed-input](https://tomaj.github.io/nette-api/examples/typed-input) + +Needs nette-api 4.0. + +## Run it + +```bash +composer install +php -S 127.0.0.1:8000 -t public public/index.php +curl "http://127.0.0.1:8000/api/v1/users/list?page=2&status=active" +curl -H 'X-Request-Id: req-01' http://127.0.0.1:8000/api/v1/users/42/detail +curl -X POST -H 'Content-Type: application/json' -d '{"customerEmail":"ada@example.com","address":{"street":"Main 1","postalCode":"81101"},"items":[{"sku":"BOOK-1","quantity":2}]}' http://127.0.0.1:8000/api/v1/orders +curl http://127.0.0.1:8000/api/v1/openapi +``` + +`GET /api/v1/users/list` reads `page` and `status` from the query string. `GET /api/v1/users/42/detail` reads the path id and `X-Request-Id`. `POST /api/v1/orders` accepts the same nested order as JSON or as a form. `POST /api/v1/avatar` accepts a multipart file. `GET /api/v1/openapi` is the generated document. + +## Test it + +```bash +./e2e.sh +``` + +`e2e.sh` starts the PHP built-in server on port 8099 and checks every response with curl. CI runs it against the current code of the library with `examples/ci/example.sh typed-input`. diff --git a/examples/typed-input/app/Api/AvatarUploadHandler.php b/examples/typed-input/app/Api/AvatarUploadHandler.php new file mode 100644 index 000000000..0ef38ef67 --- /dev/null +++ b/examples/typed-input/app/Api/AvatarUploadHandler.php @@ -0,0 +1,29 @@ +avatar; + if ($avatar->error !== UPLOAD_ERR_OK) { + return new JsonApiResponse(400, ['status' => 'error', 'message' => 'upload failed']); + } + + return new JsonApiResponse(201, [ + 'name' => $input->displayName, + 'file' => $avatar->originalName, + 'size' => $avatar->size, + ]); + } +} diff --git a/examples/typed-input/app/Api/CreateOrderHandler.php b/examples/typed-input/app/Api/CreateOrderHandler.php new file mode 100644 index 000000000..23a216527 --- /dev/null +++ b/examples/typed-input/app/Api/CreateOrderHandler.php @@ -0,0 +1,25 @@ + $input->customerEmail, + 'street' => $input->address->street, + 'items' => count($input->items), + 'quantity' => $input->items[0]->quantity, + ]); + } +} diff --git a/examples/typed-input/app/Api/Input/AddressInput.php b/examples/typed-input/app/Api/Input/AddressInput.php new file mode 100644 index 000000000..f0de01475 --- /dev/null +++ b/examples/typed-input/app/Api/Input/AddressInput.php @@ -0,0 +1,22 @@ + $items */ + public function __construct( + #[Body] + #[Email] + public string $customerEmail, + #[Body] + public AddressInput $address, + #[Body] + #[Length(min: 1, max: 50)] + public array $items, + ) { + } +} diff --git a/examples/typed-input/app/Api/Input/ItemInput.php b/examples/typed-input/app/Api/Input/ItemInput.php new file mode 100644 index 000000000..661526fdf --- /dev/null +++ b/examples/typed-input/app/Api/Input/ItemInput.php @@ -0,0 +1,20 @@ + $input->page, + 'status' => $input->status?->value, + ]); + } +} diff --git a/examples/typed-input/app/Api/UserDetailHandler.php b/examples/typed-input/app/Api/UserDetailHandler.php new file mode 100644 index 000000000..6e16b4a75 --- /dev/null +++ b/examples/typed-input/app/Api/UserDetailHandler.php @@ -0,0 +1,23 @@ + $input->id, + 'requestId' => $input->requestId, + ]); + } +} diff --git a/examples/typed-input/app/Bootstrap.php b/examples/typed-input/app/Bootstrap.php new file mode 100644 index 000000000..76c11aa8c --- /dev/null +++ b/examples/typed-input/app/Bootstrap.php @@ -0,0 +1,21 @@ +enableTracy(__DIR__ . '/../log'); + $configurator->setTempDirectory(__DIR__ . '/../temp'); + $configurator->addConfig(__DIR__ . '/../config/common.neon'); + return $configurator; + } +} diff --git a/examples/typed-input/app/RouterFactory.php b/examples/typed-input/app/RouterFactory.php new file mode 100644 index 000000000..0ea847272 --- /dev/null +++ b/examples/typed-input/app/RouterFactory.php @@ -0,0 +1,18 @@ + + $router->addRoute('/api/v/[/][/]', 'Api:Api:default'); + return $router; + } +} diff --git a/examples/typed-input/composer.json b/examples/typed-input/composer.json new file mode 100644 index 000000000..2135e1205 --- /dev/null +++ b/examples/typed-input/composer.json @@ -0,0 +1,15 @@ +{ + "name": "acme/typed-input-api", + "description": "Typed request DTOs: query, path, header, JSON or form body and a file upload", + "type": "project", + "require": { + "php": ">=8.4", + "tomaj/nette-api": "^4.0", + "nette/bootstrap": "^3.2" + }, + "autoload": { + "psr-4": { + "App\\": "app/" + } + } +} diff --git a/examples/typed-input/config/common.neon b/examples/typed-input/config/common.neon new file mode 100644 index 000000000..08e99ca2e --- /dev/null +++ b/examples/typed-input/config/common.neon @@ -0,0 +1,16 @@ +extensions: + api: Tomaj\NetteApi\DI\NetteApiExtension + +services: + router: App\RouterFactory::create + apiLink: Tomaj\NetteApi\Link\ApiLink + +api: + outputConfigurator: Tomaj\NetteApi\Output\Configurator\EnvConfigurator('APP_ENV', 'production') + + discovery: + paths: [%appDir%/Api] + namespace: App\Api + + endpoints: + - {method: GET, version: 1, package: openapi, handler: Tomaj\NetteApi\Handlers\OpenApiHandler, authorization: false} diff --git a/examples/typed-input/e2e.sh b/examples/typed-input/e2e.sh new file mode 100755 index 000000000..66bfc5149 --- /dev/null +++ b/examples/typed-input/e2e.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +# End-to-end check: typed DTOs for query, path, header, JSON, form and multipart. +set -euo pipefail +cd "$(dirname "$0")" +[[ -f vendor/autoload.php ]] || { echo "fail: vendor/ is missing, run composer install first" >&2; exit 1; } +source ../ci/lib.sh +serve 8099 +JSON=(-H 'Content-Type: application/json') + +request "$BASE/api/v1/users/list" +expect_status 200 "defaults" +expect_body '{"page":1,"status":null}' "defaults" +ok "an omitted page uses its default and an omitted enum is null" + +request "$BASE/api/v1/users/list?page=2&status=active" +expect_status 200 "query" +expect_body '{"page":2,"status":"active"}' "query" +ok "page is an integer and status is the backed enum" + +request "$BASE/api/v1/users/list?page=1a" +expect_status 400 "strict int" +expect_body '"page":["Value must be an integer"]' "strict int" +ok "1a is rejected instead of being cast to 1" + +request -H 'X-Request-Id: req-01' "$BASE/api/v1/users/42/detail" +expect_status 200 "path and header" +expect_body '{"id":42,"requestId":"req-01"}' "path and header" +ok "the path id and the request header reach the DTO" + +request -X POST "${JSON[@]}" -d '{"customerEmail":"ada@example.com","address":{"street":"Main 1","postalCode":"81101"},"items":[{"sku":"BOOK-1","quantity":2}]}' "$BASE/api/v1/orders" +expect_status 201 "json" +expect_body '{"email":"ada@example.com","street":"Main 1","items":1,"quantity":2}' "json" +ok "a nested JSON body becomes DTOs" + +request -X POST -H 'Content-Type: application/x-www-form-urlencoded' \ + --data 'customerEmail=ada%40example.com&address[street]=Main+1&address[postalCode]=81101&items[0][sku]=BOOK-1&items[0][quantity]=2' \ + "$BASE/api/v1/orders" +expect_status 201 "form" +expect_body '"quantity":2' "form" +ok "the same DTO accepts a form body in bracket notation" + +request -X POST "${JSON[@]}" -d '{"customerEmail":"nope","address":{"street":"","postalCode":"abc"},"items":[{"sku":"A","quantity":1},{"sku":"B","quantity":0}]}' "$BASE/api/v1/orders" +expect_status 400 "nested errors" +expect_body '"items[1].quantity":["Value must be at least 1"]' "nested quantity" +expect_body '"address.postalCode"' "nested postal code" +ok "nested failures use field paths" + +request -X POST "${JSON[@]}" -d '{"customerEmail":"ada@example.com","address":{"street":"Main 1","postalCode":"81101\n"},"items":[{"sku":"BOOK-1","quantity":2}]}' "$BASE/api/v1/orders" +expect_status 400 "pattern with a trailing newline" +expect_body '"address.postalCode"' "pattern with a trailing newline" +ok "a postal code followed by a newline does not match the pattern" + +request -X POST -H 'Content-Type: text/csv' --data 'a,b' "$BASE/api/v1/orders" +expect_status 415 "media type" +expect_body 'text/csv' "media type" +ok "a content type outside #[Consumes] defaults is 415" + +png="$(mktemp)" +printf 'png' > "$png" +request -F "displayName=Ada" -F "avatar=@$png;filename=a.png;type=image/png" "$BASE/api/v1/avatar" +expect_status 201 "upload" +expect_body '{"name":"Ada","file":"a.png","size":3}' "upload" +ok "a multipart file arrives as FileUpload" +rm -f "$png" + +request "$BASE/api/v1/openapi" +expect_status 200 "openapi" +expect_body '"in":"path"' "path parameter" +expect_body 'application/x-www-form-urlencoded' "form content type" +ok "OpenAPI lists the path parameter and both body content types" diff --git a/examples/typed-input/public/index.php b/examples/typed-input/public/index.php new file mode 100644 index 000000000..8cf0b6fd6 --- /dev/null +++ b/examples/typed-input/public/index.php @@ -0,0 +1,10 @@ +createContainer() + ->getByType(Nette\Application\Application::class) + ->run(); diff --git a/rector.php b/rector.php index 93584e3be..c41912178 100644 --- a/rector.php +++ b/rector.php @@ -17,6 +17,8 @@ RenameMethodRector::class, // \Redis as the return type is a fatal error while loading the class without ext-redis, before the test can be skipped NarrowObjectReturnTypeRector::class => [__DIR__ . '/tests/RateLimit/Storage/PhpRedisStorageTest.php'], + // the use statements are the fixture TypeNameTest reads back from this file + __DIR__ . '/tests/Input/Fixtures/ImportScope.php', ]) ->withPhpSets(php84: true) ->withPreparedSets(typeDeclarations: true, phpunitCodeQuality: true) diff --git a/src/ApiDecider.php b/src/ApiDecider.php index b86a1ea82..1fbc01242 100644 --- a/src/ApiDecider.php +++ b/src/ApiDecider.php @@ -13,6 +13,9 @@ use Tomaj\NetteApi\Handlers\CorsPreflightHandler; use Tomaj\NetteApi\Handlers\CorsPreflightHandlerInterface; use Tomaj\NetteApi\Handlers\DefaultHandler; +use Tomaj\NetteApi\Input\EndpointTemplate; +use Tomaj\NetteApi\Params\InputParam; +use Tomaj\NetteApi\Params\PathValues; use Tomaj\NetteApi\RateLimit\AutowiredRateLimit; use Tomaj\NetteApi\RateLimit\RateLimiterInterface; use Tomaj\NetteApi\RateLimit\RateLimitInterface; @@ -33,6 +36,8 @@ public function __construct( * Get api handler that match input method, version, package and apiAction. * If decider cannot find handler for given handler, returns defaults. * + * Endpoints with {name} segments are found by matchPath(), because they need the request path. + * * @param string $apiAction * * @return Api @@ -41,6 +46,7 @@ public function getApi(string $method, string $version, string $package, ?string { $method = strtoupper($method); $apiAction = $apiAction === '' ? null : $apiAction; + PathValues::reset(); foreach ($this->apis as $api) { $identifier = $api->getEndpoint(); @@ -59,6 +65,47 @@ public function getApi(string $method, string $version, string $package, ?string return new Api(new EndpointIdentifier($method, $version, $package, $apiAction), new DefaultHandler(), new NoAuthorization()); } + /** + * Finds an endpoint whose URL has {name} segments, for example users/{id}/detail, and stores the matched values + * for #[Path] properties. Called after getApi() found no static endpoint. Null when no template matches. + * + * @param string|null $requestPath absolute or application path of the request + * + * @throws \LogicException when more than one template matches + */ + public function matchPath(string $method, string $version, string $package, ?string $apiAction, ?string $requestPath): ?Api + { + if ($requestPath === null) { + return null; + } + + $method = strtoupper($method); + $apiAction = $apiAction === '' ? null : $apiAction; + $matched = $this->matchTemplate($method, $version, $requestPath); + if (count($matched) > 1) { + $urls = array_map(static fn (array $match): string => $match[0]->getEndpoint()->getUrl(), $matched); + throw new \LogicException(sprintf( + "%s request '%s' matches more than one endpoint (%s). Make a static segment differ so only one URL template matches.", + $method, + $requestPath, + implode(', ', $urls), + )); + } + if (count($matched) === 1) { + [$api, $captured] = $matched[0]; + PathValues::set($captured); + $handler = $this->getHandler($api); + $handler->setEndpointIdentifier($api->getEndpoint()); + return new Api($api->getEndpoint(), $handler, $api->getAuthorization(), $api->getRateLimit()); + } + + if ($method === 'OPTIONS' && $this->globalPreflightHandler && $this->matchTemplate('', $version, $requestPath) !== []) { + return new Api(new EndpointIdentifier('OPTIONS', $version, $package, $apiAction), $this->globalPreflightHandler, new NoAuthorization()); + } + + return null; + } + public function enableGlobalPreflight(?CorsPreflightHandlerInterface $corsHandler = null): void { if (!$corsHandler && !$this->globalPreflightHandler) { @@ -125,23 +172,60 @@ public function getAuthorizations(): array private function getHandler(ApiHolder $api): ApiHandlerInterface { $handler = $api->getHandler(); - if (!is_string($handler)) { - return $handler; + if (is_string($handler)) { + if (str_starts_with($handler, '@')) { + /** + * @var ApiHandlerInterface $resolved + */ + $resolved = $this->container->getByName(substr($handler, 1)); + } else { + /** + * @var ApiHandlerInterface $resolved + * @var class-string $handler + */ + $resolved = $this->container->getByType($handler); + } + $handler = $resolved; + } + + $this->checkPath($api->getEndpoint(), $handler); + return $handler; + } + + /** + * @return list}> + */ + private function matchTemplate(string $method, string $version, string $requestPath): array + { + $normalized = EndpointTemplate::normalize($requestPath, $version); + if ($normalized === null) { + return []; + } + + $matched = []; + foreach ($this->apis as $api) { + $identifier = $api->getEndpoint(); + if (($method !== '' && $method !== $identifier->getMethod()) || !str_contains($identifier->getUrl(), '{')) { + continue; + } + $captured = EndpointTemplate::match($identifier->getUrl(), $normalized); + if ($captured !== null) { + $matched[] = [$api, $captured]; + } } - if (str_starts_with($handler, '@')) { - /** - * @var ApiHandlerInterface $apiHandler - */ - $apiHandler = $this->container->getByName(substr($handler, 1)); - return $apiHandler; + return $matched; + } + + private function checkPath(EndpointInterface $endpoint, ApiHandlerInterface $handler): void + { + $names = []; + foreach ($handler->params() as $param) { + if ($param->getType() === InputParam::TYPE_PATH) { + $names[] = $param->getKey(); + } } - /** - * @var ApiHandlerInterface $apiHandler - * @var class-string $handler - */ - $apiHandler = $this->container->getByType($handler); - return $apiHandler; + EndpointTemplate::assert($endpoint->getUrl(), $names, $handler::class); } } diff --git a/src/Authorization/BearerTokenAuthorization.php b/src/Authorization/BearerTokenAuthorization.php index f6bcc94ce..1194406f1 100644 --- a/src/Authorization/BearerTokenAuthorization.php +++ b/src/Authorization/BearerTokenAuthorization.php @@ -6,6 +6,7 @@ use Tomaj\NetteApi\Misc\IpDetectorInterface; use Tomaj\NetteApi\Misc\TokenRepositoryInterface; +use Tomaj\NetteApi\Params\HeaderBag; class BearerTokenAuthorization extends TokenAuthorization { @@ -26,8 +27,9 @@ public function __construct(TokenRepositoryInterface $tokenRepository, IpDetecto #[\Override] protected function readAuthorizationToken(): ?string { - $header = $_SERVER['HTTP_AUTHORIZATION'] ?? null; - if (!is_string($header)) { + // also finds the header that Apache hands over as REDIRECT_HTTP_AUTHORIZATION + $header = HeaderBag::get('Authorization'); + if ($header === null) { $this->errorMessage = 'Authorization header HTTP_Authorization is not set'; return null; } diff --git a/src/DI/EndpointDefinition.php b/src/DI/EndpointDefinition.php index 2638b8c2c..9bfd03852 100644 --- a/src/DI/EndpointDefinition.php +++ b/src/DI/EndpointDefinition.php @@ -6,6 +6,7 @@ use Nette\DI\Definitions\Statement; use Nette\DI\InvalidConfigurationException; +use Tomaj\NetteApi\Input\EndpointTemplate; /** * One endpoint as written in neon (api.endpoints) or found by discovery, before it becomes an addApi() call. @@ -79,13 +80,13 @@ public function __construct( if ($package === '') { throw $this->invalid('package', '', 'it is empty', $this->example('package', "'users'", 'package: users')); } - if (str_contains($package, '/')) { + if (str_contains($package, '/') && !EndpointTemplate::isComposite($package)) { [$first, $rest] = explode('/', $package, 2); throw $this->invalid('package', $package, 'a package is one URL segment without a slash', str_contains($rest, '/') || $first === '' || $rest === '' ? $this->example('package', "'users'", 'package: users') : $this->example('package', sprintf("'%s', '%s'", $first, $rest), sprintf('package: %s, action: %s', $first, $rest))); } - if ($this->action !== null && str_contains($this->action, '/')) { + if ($this->action !== null && str_contains($this->action, '/') && !EndpointTemplate::isComposite($this->action)) { throw $this->invalid('action', $this->action, 'an action is one URL segment without a slash', $this->example('action', "'detail'", 'action: detail')); } } diff --git a/src/DI/NetteApiExtension.php b/src/DI/NetteApiExtension.php index a86ac9fe5..feebc9685 100644 --- a/src/DI/NetteApiExtension.php +++ b/src/DI/NetteApiExtension.php @@ -28,6 +28,10 @@ use Tomaj\NetteApi\Error\ProblemDetailsErrorHandler; use Tomaj\NetteApi\Handlers\ApiHandlerInterface; use Tomaj\NetteApi\Handlers\BaseHandler; +use Tomaj\NetteApi\Handlers\TypedHandler; +use Tomaj\NetteApi\Input\DtoCompiler; +use Tomaj\NetteApi\Input\DtoMetadataRegistry; +use Tomaj\NetteApi\Input\EndpointTemplate; use Tomaj\NetteApi\Handlers\CorsPreflightHandler; use Tomaj\NetteApi\Logger\ApiLoggerInterface; use Tomaj\NetteApi\Logger\LogMaskMode; @@ -61,6 +65,7 @@ use Tomaj\NetteApi\RateLimit\Storage\RateLimitStorageInterface; use Tomaj\NetteApi\RateLimit\Storage\LazyStorage; use Tomaj\NetteApi\RateLimit\Storage\RedisStorage; +use Nette\PhpGenerator\ClassType; use Nette\PhpGenerator\Literal; use Tomaj\NetteApi\RateLimit\Redis\RedisClientInterface; use Tomaj\NetteApi\RateLimit\TokenBucketLimiter; @@ -142,6 +147,9 @@ final class NetteApiExtension extends CompilerExtension /** @var array own service name => service it returns ("@name" in neon) */ private array $aliases = []; + /** @var array> handler class => compiled DTO metadata */ + private array $typedExport = []; + public function __construct() { $this->endpoints = new EndpointCollector(); @@ -405,6 +413,17 @@ public function beforeCompile(): void $check(); } $this->checkRateLimitStorage(); + $this->compileTypedInput(); + } + + #[\Override] + public function afterCompile(ClassType $class): void + { + if ($this->typedExport === []) { + return; + } + + $this->getInitialization()->addBody(DtoMetadataRegistry::class . '::install(?);', [$this->typedExport]); } /** @@ -1426,4 +1445,55 @@ private function checkType(string $class, string $type, string $where): void )); } } + + /** + * Reflects typed handlers while the container is compiled and stores the result for initialize(). + */ + private function compileTypedInput(): void + { + /** @var array> $urls */ + $urls = []; + foreach ($this->endpoints->all() as $endpoint) { + $action = $endpoint->action === null ? '' : sprintf('/%s', $endpoint->action); + $url = sprintf('v%s/%s%s', $endpoint->version, $endpoint->package, $action); + $urls[$endpoint->method][] = $url; + $class = $this->handlerClass($endpoint); + if ($class === null || !is_a($class, TypedHandler::class, true)) { + continue; + } + + $metadata = DtoCompiler::compile($class); + EndpointTemplate::assert($url, $metadata->pathNames(), sprintf('%s (%s)', $class, $endpoint->source)); + foreach ($metadata->files as $file) { + $this->compiler->addDependencies([$file]); + } + $this->typedExport[$class] = $metadata->export(); + } + + EndpointTemplate::assertDisjoint($urls); + } + + private function handlerClass(EndpointDefinition $endpoint): ?string + { + $handler = $endpoint->handler; + if ($handler instanceof Statement) { + $entity = $handler->getEntity(); + $entity = is_string($entity) ? $entity : ''; + + return class_exists($entity) ? ltrim($entity, '\\') : null; + } + if (str_starts_with($handler, '@')) { + $name = substr($handler, 1); + if (!$this->getContainerBuilder()->hasDefinition($name)) { + return null; + } + $type = $this->getContainerBuilder()->getDefinition($name)->getType(); + $type = is_string($type) ? $type : ''; + + return class_exists($type) ? $type : null; + } + $class = ltrim($handler, '\\'); + + return class_exists($class) ? $class : null; + } } diff --git a/src/Error/DefaultErrorHandler.php b/src/Error/DefaultErrorHandler.php index a2e708d5e..b4ef01dc6 100644 --- a/src/Error/DefaultErrorHandler.php +++ b/src/Error/DefaultErrorHandler.php @@ -67,6 +67,12 @@ public function handleRateLimit(RateLimitResponse $rateLimit): JsonApiResponse return new JsonApiResponse(Response::S429_TOO_MANY_REQUESTS, ['status' => 'error', 'message' => $message]); } + #[\Override] + public function handleUnsupportedMediaType(string $detail): JsonApiResponse + { + return $this->error(Response::S415_UnsupportedMediaType, 'unsupported media type', $detail); + } + private function internalError(Throwable $exception): JsonApiResponse { Debugger::log($exception, Debugger::EXCEPTION); diff --git a/src/Error/ErrorHandlerInterface.php b/src/Error/ErrorHandlerInterface.php index 41251ed3a..ff6d8f72e 100644 --- a/src/Error/ErrorHandlerInterface.php +++ b/src/Error/ErrorHandlerInterface.php @@ -60,4 +60,9 @@ public function handleNotFound(EndpointInterface $endpoint): ResponseInterface; * Rate limit has no remaining requests and returned no own error response (429) */ public function handleRateLimit(RateLimitResponse $rateLimit): ResponseInterface; + + /** + * Body content type is missing or not accepted by the handler (415) + */ + public function handleUnsupportedMediaType(string $detail): ResponseInterface; } diff --git a/src/Error/NegotiatingErrorHandler.php b/src/Error/NegotiatingErrorHandler.php index 0d5451d26..0148e398a 100644 --- a/src/Error/NegotiatingErrorHandler.php +++ b/src/Error/NegotiatingErrorHandler.php @@ -72,6 +72,12 @@ public function handleRateLimit(RateLimitResponse $rateLimit): ResponseInterface return $this->select()->handleRateLimit($rateLimit); } + #[\Override] + public function handleUnsupportedMediaType(string $detail): ResponseInterface + { + return $this->select()->handleUnsupportedMediaType($detail); + } + private function select(): ErrorHandlerInterface { $this->response->addHeader('Vary', 'Accept'); diff --git a/src/Error/ProblemDetailsErrorHandler.php b/src/Error/ProblemDetailsErrorHandler.php index aef0cea90..d2ebf364e 100644 --- a/src/Error/ProblemDetailsErrorHandler.php +++ b/src/Error/ProblemDetailsErrorHandler.php @@ -29,6 +29,8 @@ public const string TYPE_INTERNAL = 'internal-error'; + public const string TYPE_UNSUPPORTED_MEDIA = 'unsupported-media-type'; + public const string TYPE_INVALID_OUTPUT = 'invalid-output'; private ?string $typeBaseUri; @@ -112,6 +114,12 @@ public function handleRateLimit(RateLimitResponse $rateLimit): ProblemDetailsRes return $this->problem(Response::S429_TOO_MANY_REQUESTS, 'Too Many Requests', self::TYPE_RATE_LIMITED, $detail, $extensions); } + #[\Override] + public function handleUnsupportedMediaType(string $detail): ProblemDetailsResponse + { + return $this->problem(Response::S415_UnsupportedMediaType, 'Unsupported Media Type', self::TYPE_UNSUPPORTED_MEDIA, $detail); + } + private function internalError(Throwable $exception): ProblemDetailsResponse { Debugger::log($exception, Debugger::EXCEPTION); diff --git a/src/Handlers/TypedHandler.php b/src/Handlers/TypedHandler.php new file mode 100644 index 000000000..ce5827541 --- /dev/null +++ b/src/Handlers/TypedHandler.php @@ -0,0 +1,39 @@ + + */ + #[\Override] + final public function params(): array + { + return DtoMetadataRegistry::forHandler(static::class)->inputParams(); + } + + /** + * @param array $params + */ + #[\Override] + final public function handle(array $params): ResponseInterface + { + $metadata = DtoMetadataRegistry::forHandler(static::class); + $input = $metadata->instantiate($params); + // DtoCompiler checks at compile time that handleDto() exists, is public and takes exactly this DTO + return $this->handleDto($input); + } +} diff --git a/src/Input/Body.php b/src/Input/Body.php new file mode 100644 index 000000000..f4b7e3d26 --- /dev/null +++ b/src/Input/Body.php @@ -0,0 +1,22 @@ + $examples named examples, the same pairs as InputParam::addExample() + */ + public function __construct( + public ?string $name = null, + public ?string $description = null, + public array $examples = [], + ) { + } +} diff --git a/src/Input/Cast.php b/src/Input/Cast.php new file mode 100644 index 000000000..1829b7cc0 --- /dev/null +++ b/src/Input/Cast.php @@ -0,0 +1,23 @@ + */ + public array $arguments; + + /** + * @param class-string $caster + */ + public function __construct(public string $caster, mixed ...$arguments) + { + $this->arguments = $arguments; + } +} diff --git a/src/Input/CastException.php b/src/Input/CastException.php new file mode 100644 index 000000000..88227c4f3 --- /dev/null +++ b/src/Input/CastException.php @@ -0,0 +1,12 @@ + */ + public array $types; + + public function __construct(string ...$types) + { + $this->types = $types; + } +} diff --git a/src/Input/ConversionFailed.php b/src/Input/ConversionFailed.php new file mode 100644 index 000000000..ea830b2bf --- /dev/null +++ b/src/Input/ConversionFailed.php @@ -0,0 +1,12 @@ +format === '') { + throw new \InvalidArgumentException("DateFormat needs a PHP date format, for example #[Cast(DateFormat::class, 'd.m.Y')]."); + } + } + + #[\Override] + public function cast(mixed $value): \DateTimeImmutable + { + $example = $this->example(); + $message = 'Date must match ' . $this->format . ', for example ' . $example; + if (!is_string($value) || $value === '' || str_contains($value, "\0")) { + throw new CastException($message); + } + + $date = \DateTimeImmutable::createFromFormat(sprintf('!%s', $this->format), $value); + if ($date === false || $date->format($this->format) !== $value) { + throw new CastException($message); + } + + return $date; + } + + /** + * @return array{type: string, format?: string, example: string} + */ + #[\Override] + public function openApiSchema(): array + { + // OpenAPI `date` is the RFC 3339 full-date, so other formats are a plain string with an example + if ($this->format === 'Y-m-d') { + return ['type' => 'string', 'format' => 'date', 'example' => $this->example()]; + } + + return ['type' => 'string', 'example' => $this->example()]; + } + + private function example(): string + { + return new \DateTimeImmutable('2026-12-24T00:00:00+00:00')->format($this->format); + } +} diff --git a/src/Input/DtoCompiler.php b/src/Input/DtoCompiler.php new file mode 100644 index 000000000..18347aad6 --- /dev/null +++ b/src/Input/DtoCompiler.php @@ -0,0 +1,1178 @@ + */ + private array $files = []; + + /** @var list */ + private array $stack = []; + + public static function compile(string $handler): DtoMetadata + { + return new self()->handler($handler); + } + + private function handler(string $handler): DtoMetadata + { + if (!class_exists($handler)) { + $this->fail(sprintf( + "Typed handler '%s' does not exist. Check the class name and the autoload section of composer.json.", + $handler, + )); + } + if (!is_a($handler, TypedHandler::class, true)) { + $this->fail(sprintf( + '%s must extend %s to use a typed input DTO. A handler that implements handle(array $params) stays on %s.', + $handler, + TypedHandler::class, + BaseHandler::class, + )); + } + + $reflection = new \ReflectionClass($handler); + $this->touch($reflection); + $dto = $this->dtoClass($reflection); + $fields = $this->dto($dto, true); + $contentTypes = $this->contentTypes($reflection, $fields); + $readsBody = false; + $bodyRequired = false; + $firstBody = null; + foreach ($fields as $field) { + if (!$field->readsBody()) { + continue; + } + $readsBody = true; + $firstBody ??= $field->property; + if ($field->required()) { + $bodyRequired = true; + } + } + + return new DtoMetadata($handler, $dto, $fields, $contentTypes, $bodyRequired, $readsBody, $firstBody, array_values($this->files)); + } + + /** @param \ReflectionClass<*> $handler */ + private function dtoClass(\ReflectionClass $handler): string + { + if (!$handler->hasMethod('handleDto')) { + $this->fail(sprintf( + '%s must implement public function handleDto(SomeInput $input): ResponseInterface. TypedHandler reads the DTO class from that parameter.', + $handler->getName(), + )); + } + + $method = $handler->getMethod('handleDto'); + if (!$method->isPublic() || $method->isStatic()) { + $this->fail(sprintf( + '%s::handleDto() must be a public instance method with one DTO parameter, for example public function handleDto(ListUsersInput $input): ResponseInterface.', + $handler->getName(), + )); + } + + $parameters = $method->getParameters(); + if (count($parameters) !== 1 || $parameters[0]->isVariadic()) { + $this->fail(sprintf( + '%s::handleDto() must declare exactly one parameter, the input DTO. It has %d. Example: public function handleDto(ListUsersInput $input): ResponseInterface.', + $handler->getName(), + count($parameters), + )); + } + + $parameter = $parameters[0]; + if ($parameter->allowsNull() || $parameter->isOptional()) { + $this->fail(sprintf( + '%s::handleDto($%s) must be a non-nullable DTO without a default. The request always produces the object; nullability belongs on the DTO properties.', + $handler->getName(), + $parameter->getName(), + )); + } + + $type = $parameter->getType(); + if (!$type instanceof \ReflectionNamedType || $type->isBuiltin()) { + $this->fail(sprintf( + '%s::handleDto($%s) must be type-hinted with the DTO class, for example handleDto(ListUsersInput $input). Unions, scalars and missing types are not an input DTO.', + $handler->getName(), + $parameter->getName(), + )); + } + + $return = $method->getReturnType(); + if (!$return instanceof \ReflectionNamedType || $return->isBuiltin() || !is_a($return->getName(), ResponseInterface::class, true)) { + $this->fail(sprintf( + '%s::handleDto() must return %s (or a subtype). Add `: ResponseInterface` so the response is the same type BaseHandler::handle() returns.', + $handler->getName(), + ResponseInterface::class, + )); + } + + return $type->getName(); + } + + /** + * @param \ReflectionClass<*> $handler + * @param list $fields + * @return list + */ + private function contentTypes(\ReflectionClass $handler, array $fields): array + { + $attributes = $handler->getAttributes(Consumes::class); + if (count($attributes) > 1) { + $this->fail(sprintf( + '%s has more than one #[Consumes]. Declare every media type on a single attribute, for example #[Consumes(\'application/json\')].', + $handler->getName(), + )); + } + + $declared = null; + if ($attributes !== []) { + try { + $consumes = $attributes[0]->newInstance(); + } catch (\Throwable $exception) { + $this->fail(sprintf( + '%s #[Consumes] is invalid: %s. Pass one or more media types, for example #[Consumes(\'application/json\')].', + $handler->getName(), + $exception->getMessage(), + )); + } + if ($consumes->types === []) { + $this->fail(sprintf( + '%s #[Consumes] needs at least one media type, for example #[Consumes(\'application/json\')].', + $handler->getName(), + )); + } + $declared = []; + foreach ($consumes->types as $type) { + $normalized = MediaTypes::normalize($type); + if (!in_array($normalized, MediaTypes::ALL, true)) { + $this->fail(sprintf( + "%s #[Consumes] has '%s', which a typed body cannot read. Use one of: %s.", + $handler->getName(), + $type, + implode(', ', MediaTypes::ALL), + )); + } + if (in_array($normalized, $declared, true)) { + $this->fail(sprintf( + "%s #[Consumes] lists '%s' twice. List each media type once.", + $handler->getName(), + $normalized, + )); + } + $declared[] = $normalized; + } + } + + $hasFile = self::containsFile($fields); + $types = $declared ?? ($hasFile + ? [MediaTypes::JSON, MediaTypes::MULTIPART] + : [MediaTypes::JSON, MediaTypes::FORM]); + if ($hasFile && !in_array(MediaTypes::MULTIPART, $types, true)) { + $this->fail(sprintf( + '%s has a #[File] property but does not accept multipart/form-data, so the file cannot be uploaded. Add it to #[Consumes], or remove #[Consumes] to accept application/json and multipart/form-data.', + $handler->getName(), + )); + } + + return $types; + } + + /** + * @return list + */ + private function dto(string $class, bool $root): array + { + if (in_array($class, $this->stack, true)) { + $this->fail(sprintf( + 'DTO %s refers to itself (%s). Nested DTOs cannot form a cycle; keep the nesting one way.', + $class, + implode(' -> ', [...$this->stack, $class]), + )); + } + if (!class_exists($class) && !interface_exists($class) && !enum_exists($class)) { + $this->fail(sprintf( + "DTO '%s' does not exist. Use a readonly class in the same project, and check the namespace and the use statement.", + $class, + )); + } + + $this->stack[] = $class; + $reflection = new \ReflectionClass($class); + $this->touch($reflection); + if (!$reflection->isInstantiable()) { + $this->fail(sprintf( + '%s cannot be an input DTO. Use a concrete readonly class with a constructor, not an enum, an interface or an abstract class.', + $class, + )); + } + + $constructor = $reflection->getConstructor(); + if ($constructor === null) { + $this->fail(sprintf( + '%s needs a constructor with promoted properties, for example public function __construct(#[Query] public int $page = 1).', + $class, + )); + } + + foreach ($constructor->getParameters() as $parameter) { + if ($parameter->isVariadic() || $parameter->isPassedByReference()) { + $this->fail(sprintf( + '%s::__construct() parameter $%s is %s. A DTO constructor takes only promoted properties, for example public function __construct(#[Query] public int $page = 1).', + $class, + $parameter->getName(), + $parameter->isVariadic() ? 'variadic' : 'passed by reference', + )); + } + if (!$parameter->isPromoted() && !$parameter->isOptional()) { + $this->fail(sprintf( + '%s::__construct() has the required parameter $%s that is not a promoted property, so the mapper cannot pass it. Make it a promoted property with a source attribute, for example #[Body] public string $%s, give it a default, or move it out of the DTO.', + $class, + $parameter->getName(), + $parameter->getName(), + )); + } + } + + $properties = []; + foreach ($reflection->getProperties() as $property) { + if ($property->isStatic()) { + $this->fail(sprintf('%s::$%s is static. A DTO property has to be a promoted constructor parameter.', $class, $property->getName())); + } + $properties[] = $property; + } + if ($properties === []) { + $this->fail(sprintf('%s has no properties. Add the inputs as promoted constructor properties with #[Query], #[Path], #[Header], #[Body] or #[File].', $class)); + } + + $fields = []; + $names = []; + foreach ($properties as $property) { + $field = $this->property($property, $reflection, $root); + if (isset($names[$field->externalName])) { + $this->fail(sprintf( + "%s properties \$%s and \$%s both use the external name '%s'. Each input name can be declared once; pass a different name, for example #[Query('pageSize')].", + $class, + $names[$field->externalName], + $field->property, + $field->externalName, + )); + } + $names[$field->externalName] = $field->property; + $fields[] = $field; + } + $this->checkDefaults($class, $fields); + array_pop($this->stack); + + return $fields; + } + + /** @param \ReflectionClass<*> $dto */ + private function property(\ReflectionProperty $property, \ReflectionClass $dto, bool $root): Field + { + $class = $dto->getName(); + $name = $property->getName(); + if (!$property->isPromoted()) { + $this->fail(sprintf( + '%s::$%s is not a promoted constructor property. Declare it in the constructor: public function __construct(#[Body] public string $%s).', + $class, + $name, + $name, + )); + } + if (!$property->isReadOnly()) { + $this->fail(sprintf( + '%s::$%s must be readonly. Declare `readonly class %s` or `public readonly` on $%s, so the mapper creates the value once.', + $class, + $name, + $dto->getShortName(), + $name, + )); + } + + $parameter = null; + $constructor = $dto->getConstructor(); + foreach ($constructor instanceof \ReflectionMethod ? $constructor->getParameters() : [] as $candidate) { + if ($candidate->getName() === $name) { + $parameter = $candidate; + } + } + if (!$parameter instanceof \ReflectionParameter) { + $this->fail(sprintf('%s::$%s is missing from the constructor. Promoted properties are declared as constructor parameters.', $class, $name)); + } + + [$typeName, $builtin, $nullable] = $this->type($property, $dto); + $source = $this->source($property, $dto, $root); + $external = $this->externalName($source['attribute'], $name, $class); + $list = $this->list($property, $dto, $typeName); + $hasDefault = $parameter->isDefaultValueAvailable(); + if ($source['source'] === Source::Path && $nullable) { + $this->fail(sprintf( + '%s::$%s is a path parameter and cannot be nullable. A {name} segment is always present. Use `public int $%s` and put {%s} in the endpoint URL.', + $class, + $name, + $name, + $external, + )); + } + if ($source['source'] === Source::Path && $hasDefault) { + $this->fail(sprintf( + '%s::$%s is a path parameter and cannot have a default. Remove the default and put {%s} in the endpoint URL, for example #[Get(1, \'users\', \'{%s}/detail\')].', + $class, + $name, + $external, + $external, + )); + } + + $default = null; + if ($hasDefault) { + $default = $parameter->getDefaultValue(); + $this->checkDefaultValue($class, $name, $default); + } + + $enumClass = null; + $enumInt = false; + $enumValues = []; + if (!$builtin && enum_exists($typeName)) { + if (!is_a($typeName, \BackedEnum::class, true)) { + $this->fail(sprintf( + '%s::$%s uses %s, which is not a backed enum. Give the enum a string or int backing (`enum Status: string`) or accept the backing value as a string.', + $class, + $name, + $typeName, + )); + } + $enumClass = $typeName; + $this->touch(new \ReflectionEnum($typeName)); + $backing = new \ReflectionEnum($typeName)->getBackingType(); + $enumInt = $backing instanceof \ReflectionNamedType && $backing->getName() === 'int'; + $enumValues = ScalarCoercer::enumValues($typeName); + } + + // a caster replaces the built-in conversion, so its result type is not compiled as a transport DTO + $casted = $property->getAttributes(Cast::class) !== []; + $children = []; + $item = null; + $listItem = null; + $listItemBuiltin = false; + if ($typeName === 'array') { + if ($list === null) { + $found = $this->documentedType($property, $dto); + $this->fail(sprintf( + '%s::$%s is an array without an item type. Add `/** @param list $%s */` (or list, list, list, list, list). Associative and untyped arrays are rejected.%s', + $class, + $name, + $name, + $found === null ? '' : sprintf(' Found `%s`, but only list, non-empty-list and T[] are read.', $found), + )); + } + $listItem = $list['name']; + $listItemBuiltin = $list['builtin']; + $item = $casted ? null : $this->itemField($list, $source['source'], $class, $name, $root); + } elseif (!$casted && !$builtin && $enumClass === null && $typeName !== \DateTimeImmutable::class && $typeName !== FileUpload::class) { + $children = $this->dto($typeName, false); + } + + if (!$casted && ($listItem !== null || $children !== []) && in_array($source['source'], [Source::Path, Source::Header], true)) { + $this->fail(sprintf( + "%s::\$%s reads #[%s], which is one string, so it cannot be %s. Use a scalar type or split the string, for example #[Cast(Split::class, ',')].", + $class, + $name, + new \ReflectionClass($source['attribute'])->getShortName(), + $listItem !== null ? sprintf('list<%s>', $listItem) : $typeName, + )); + } + if (!$casted && $source['source'] === Source::Query && ($children !== [] || ($item instanceof Field && $item->children !== []))) { + $this->fail(sprintf( + '%s::$%s reads #[Query], which carries flat values, so it cannot be %s. Read nested objects from the body with #[Body], or use a scalar, an enum or a list of them in the query.', + $class, + $name, + $listItem !== null ? sprintf('list<%s>', $listItem) : $typeName, + )); + } + if ($source['source'] === Source::File && $typeName !== FileUpload::class && $listItem !== FileUpload::class) { + $this->fail(sprintf( + '%s::$%s uses #[File] but its type is %s. Use FileUpload, ?FileUpload or list.', + $class, + $name, + $typeName === 'array' ? sprintf('list<%s>', (string) $listItem) : $typeName, + )); + } + if ($source['source'] !== Source::File && ($typeName === FileUpload::class || $listItem === FileUpload::class)) { + $this->fail(sprintf('%s::$%s is a FileUpload, so it needs #[File], not #[%s].', $class, $name, new \ReflectionClass($source['attribute'])->getShortName())); + } + + $constraints = $this->constraints($property, $dto, $typeName); + $cast = $this->caster($property, $dto, $typeName, $builtin, $listItem, $listItemBuiltin); + $this->checkListDefault($class, $name, $default, $listItem, $listItemBuiltin); + + return new Field( + property: $name, + externalName: $external, + source: $source['source'], + typeName: $typeName, + builtin: $builtin, + nullable: $nullable, + hasDefault: $hasDefault, + default: $default, + description: $source['attribute']->description, + examples: $this->examples($source['attribute'], $class, $name), + listItem: $listItem, + listItemBuiltin: $listItemBuiltin, + enumClass: $enumClass, + enumInt: $enumInt, + enumValues: $enumValues, + constraints: $constraints['instances'], + constraintSpecs: $constraints['specs'], + casterClass: $cast['class'], + casterArguments: $cast['arguments'], + casterSchema: $cast['schema'], + children: $children, + item: $item, + dtoClass: $class, + ); + } + + /** + * @param \ReflectionClass<*> $dto + * @return array{0: string, 1: bool, 2: bool} + */ + private function type(\ReflectionProperty $property, \ReflectionClass $dto): array + { + $type = $property->getType(); + $class = $dto->getName(); + $name = $property->getName(); + if (!$type instanceof \ReflectionType) { + $this->fail(sprintf( + '%s::$%s has no type. Declare a concrete type such as string, int, a backed enum, DateTimeImmutable or another readonly DTO.', + $class, + $name, + )); + } + + $nullable = $type->allowsNull(); + if ($type instanceof \ReflectionUnionType) { + $this->fail(sprintf( + '%s::$%s has type %s. Typed input supports one type, or a nullable type (`?int` or `int|null`), not a union.', + $class, + $name, + (string) $type, + )); + } + if (!$type instanceof \ReflectionNamedType) { + $this->fail(sprintf('%s::$%s has type %s. Intersection types are not supported; use one class.', $class, $name, (string) $property->getType())); + } + + $typeName = $type->getName(); + if ($typeName === 'self') { + $typeName = $class; + } elseif ($typeName === 'parent' && $dto->getParentClass() instanceof \ReflectionClass) { + $typeName = $dto->getParentClass()->getName(); + } + if (in_array($typeName, ['mixed', 'object', 'null'], true)) { + $this->fail(sprintf( + '%s::$%s has type %s, which has no contract to validate. Declare string, int, float, bool, a backed enum, DateTimeImmutable, FileUpload or a DTO.', + $class, + $name, + $typeName, + )); + } + if (is_a($typeName, \DateTimeInterface::class, true) && $typeName !== \DateTimeImmutable::class) { + $this->fail(sprintf( + '%s::$%s has type %s. Use DateTimeImmutable itself, the only date type typed input supports (RFC 3339 text, for example 2024-05-01T10:00:00Z); a subclass or an interface cannot be built from the input.', + $class, + $name, + $typeName, + )); + } + if ($type->isBuiltin() && !in_array($typeName, ['int', 'float', 'bool', 'string', 'array'], true)) { + $this->fail(sprintf( + '%s::$%s has type %s. Use string, int, float, bool or list.', + $class, + $name, + $typeName, + )); + } + + return [$typeName, $type->isBuiltin(), $nullable]; + } + + /** + * @param \ReflectionClass<*> $dto + * @return array{source: Source, attribute: Query|Path|Header|Body|File} + */ + private function source(\ReflectionProperty $property, \ReflectionClass $dto, bool $root): array + { + $found = []; + foreach ($property->getAttributes() as $attribute) { + $name = $attribute->getName(); + if (!is_a($name, Query::class, true) && !is_a($name, Path::class, true) && !is_a($name, Header::class, true) && !is_a($name, Body::class, true) && !is_a($name, File::class, true)) { + continue; + } + try { + $instance = $attribute->newInstance(); + } catch (\Throwable $exception) { + $this->fail(sprintf( + '%s::$%s attribute %s is invalid: %s.', + $dto->getName(), + $property->getName(), + new \ReflectionClass($name)->getShortName(), + $exception->getMessage(), + )); + } + $found[] = $this->sourceAttribute($instance); + } + if ($found === []) { + $this->fail(sprintf( + '%s::$%s has no source attribute. Add exactly one of #[Query], #[Path], #[Header], #[Body] or #[File].', + $dto->getName(), + $property->getName(), + )); + } + if (count($found) > 1) { + $this->fail(sprintf( + '%s::$%s has more than one source attribute. Keep exactly one; a value comes from one place.', + $dto->getName(), + $property->getName(), + )); + } + + $attribute = $found[0]; + $source = match (true) { + $attribute instanceof Query => Source::Query, + $attribute instanceof Path => Source::Path, + $attribute instanceof Header => Source::Header, + $attribute instanceof Body => Source::Body, + $attribute instanceof File => Source::File, + }; + if (!$root && $source === Source::File) { + $this->fail(sprintf( + 'Nested DTO %s::$%s uses #[File]. Uploads are read only on the root DTO; move the property to the input DTO of the handler, for example #[File] public FileUpload $%s.', + $dto->getName(), + $property->getName(), + $property->getName(), + )); + } + if (!$root && $source !== Source::Body) { + $this->fail(sprintf( + 'Nested DTO %s::$%s uses #[%s]. Nested properties are part of the body: use #[Body]. Query, path and header belong on the root DTO.', + $dto->getName(), + $property->getName(), + new \ReflectionClass($attribute)->getShortName(), + )); + } + + return ['source' => $source, 'attribute' => $attribute]; + } + + private function sourceAttribute(object $instance): Query|Path|Header|Body|File + { + if ($instance instanceof Query) { + return $instance; + } + if ($instance instanceof Path) { + return $instance; + } + if ($instance instanceof Header) { + return $instance; + } + if ($instance instanceof Body) { + return $instance; + } + if ($instance instanceof File) { + return $instance; + } + + throw new \LogicException(sprintf('Attribute %s is not an input source. Use #[Query], #[Path], #[Header], #[Body] or #[File].', $instance::class)); + } + + private function externalName(Query|Path|Header|Body|File $attribute, string $property, string $class): string + { + $name = $attribute->name ?? $property; + if ($name === '') { + $this->fail(sprintf( + "%s::$%s has an empty input name. Omit the name to use the property, or pass it, for example #[%s('%s')].", + $class, + $property, + new \ReflectionClass($attribute)->getShortName(), + $attribute instanceof Header ? 'X-Request-Id' : 'my_name', + )); + } + if (preg_match('/^[A-Za-z_][A-Za-z0-9_-]*$/', $name) !== 1) { + $this->fail(sprintf( + "%s::$%s input name '%s' must start with a letter or an underscore, and have only letters, digits, underscores and dashes (for example X-Request-Id). Dots and brackets are reserved for error paths.", + $class, + $property, + $name, + )); + } + + if ($attribute instanceof Path && preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $name) !== 1) { + $this->fail(sprintf( + "%s::$%s path name '%s' is written as a {%s} segment of the URL, so it can only have letters, digits and underscores. Use for example #[Path('%s')].", + $class, + $property, + $name, + $name, + str_replace('-', '_', $name), + )); + } + if ($attribute instanceof Header && str_contains($name, '_')) { + $this->fail(sprintf( + "%s::$%s header name '%s' has an underscore, but the request exposes header names with dashes, so it would never match. Use #[Header('%s')].", + $class, + $property, + $name, + str_replace('_', '-', $name), + )); + } + + return $name; + } + + /** + * @return array + */ + private function examples(Query|Path|Header|Body|File $attribute, string $class, string $property): array + { + $examples = []; + foreach ($attribute->examples as $name => $example) { + if (!is_string($name)) { + $this->fail(sprintf( + "%s::$%s examples must be a map of name to value, for example #[Query(examples: ['first page' => 1])]. A list was given.", + $class, + $property, + )); + } + $examples[$name] = $example; + } + + return $examples; + } + + /** + * @param \ReflectionClass<*> $dto + * @return array{name: string, builtin: bool}|null + */ + private function list(\ReflectionProperty $property, \ReflectionClass $dto, string $typeName): ?array + { + $documented = $this->documentedType($property, $dto); + if ($documented === null) { + return null; + } + + // nullability comes from the native type, so `?list`, `list|null` and `null|list` mean list + $type = preg_replace('/^\?\s*|\s*\|\s*null$|^null\s*\|\s*/i', '', $documented) ?? $documented; + $item = null; + if (preg_match('/^(?:non-empty-)?list\s*<\s*(.+?)\s*>$/', $type, $match) === 1 || preg_match('/^([A-Za-z_\\\\][A-Za-z0-9_\\\\]*)\[\]$/', $type, $match) === 1) { + $item = $match[1]; + } + if ($item === null) { + if ($typeName === 'array' && preg_match('/^array\b/', $type) === 1) { + $this->fail(sprintf( + '%s::$%s documents `%s`, an array that is not a list. Use `list` so the item type is explicit; associative arrays are not supported.', + $dto->getName(), + $property->getName(), + $documented, + )); + } + + return null; + } + if ($typeName !== 'array') { + $this->fail(sprintf( + '%s::$%s documents list<%s> but its PHP type is %s. Change the property type to array.', + $dto->getName(), + $property->getName(), + $item, + $typeName, + )); + } + if (preg_match('/^(?:non-empty-)?(?:list|array)\b|[|?&]/', $item) === 1) { + $this->fail(sprintf( + '%s::$%s documents list<%s>. A list item is one non-nullable type: use list, list, list, list, list or list. For nested lists or optional items, declare an item DTO.', + $dto->getName(), + $property->getName(), + $item, + )); + } + if (preg_match('/<|^[a-z]+(?:-[a-z]+)+$/', $item) === 1) { + $this->fail(sprintf( + '%s::$%s documents list<%s>. PHPStan refinements such as positive-int, non-empty-string or int<0, 10> and generic items are not read: use list, list, list, list, list or list, and add a constraint such as #[Range] for the rest.', + $dto->getName(), + $property->getName(), + $item, + )); + } + + $resolved = TypeName::resolve($item, $dto); + $builtin = in_array($resolved, ['string', 'int', 'float', 'bool'], true); + if (!$builtin && !class_exists($resolved)) { + $this->fail(sprintf( + '%s::$%s documents list<%s>, and that type was not found. Use a full name, import it, or use list, list, list, list or list.', + $dto->getName(), + $property->getName(), + $item, + )); + } + + return ['name' => $resolved, 'builtin' => $builtin]; + } + + /** + * The documented type of a property: `@param` of the constructor or the property, `@var` of the property. + * `@phpstan-param` and `@psalm-param` win over `@param`, because they are the more precise ones. + * + * @param \ReflectionClass<*> $dto + */ + private function documentedType(\ReflectionProperty $property, \ReflectionClass $dto): ?string + { + $propertyDoc = $property->getDocComment() ?: ''; + $constructor = $dto->getConstructor(); + $constructorDoc = $constructor instanceof \ReflectionMethod ? ($constructor->getDocComment() ?: '') : ''; + $doc = sprintf("%s\n%s", $propertyDoc, $constructorDoc); + $name = $property->getName(); + + foreach (['(?:phpstan|psalm)-param', 'param'] as $tag) { + if (preg_match('/@' . $tag . '\s+([^$]*?)\s*\$' . $name . '\b/s', $doc, $match) === 1 && $match[1] !== '') { + return $match[1]; + } + } + // one type, possibly with spaces inside its brackets, and then maybe a description: `@var list Names` + if (preg_match('/@(?:phpstan-|psalm-)?var\s+((?:[^\s<>{}()*]|(?[<{(](?:[^<>{}()]|(?&b))*[>})]))+)/', $propertyDoc, $match) === 1) { + return $match[1]; + } + + return null; + } + + /** + * @param array{name: string, builtin: bool} $list + */ + private function itemField(array $list, Source $source, string $class, string $property, bool $root): Field + { + $itemName = $list['name']; + $builtin = $list['builtin']; + $children = []; + $enumClass = null; + $enumInt = false; + $enumValues = []; + if (!$builtin && is_a($itemName, \BackedEnum::class, true)) { + $enumClass = $itemName; + $this->touch(new \ReflectionEnum($itemName)); + $backing = new \ReflectionEnum($itemName)->getBackingType(); + $enumInt = $backing instanceof \ReflectionNamedType && $backing->getName() === 'int'; + $enumValues = ScalarCoercer::enumValues($itemName); + } elseif (!$builtin && $itemName !== FileUpload::class && $itemName !== \DateTimeImmutable::class) { + $children = $this->dto($itemName, false); + } + + return new Field( + property: $property, + externalName: $property, + source: $source, + typeName: $itemName, + builtin: $builtin, + nullable: false, + hasDefault: false, + default: null, + description: null, + examples: [], + listItem: null, + listItemBuiltin: false, + enumClass: $enumClass, + enumInt: $enumInt, + enumValues: $enumValues, + constraints: [], + constraintSpecs: [], + casterClass: null, + casterArguments: [], + casterSchema: null, + children: $children, + item: null, + dtoClass: $class, + ); + } + + /** + * @param \ReflectionClass<*> $dto + * @return array{instances: list, specs: list, args: array}>} + */ + private function constraints(\ReflectionProperty $property, \ReflectionClass $dto, string $typeName): array + { + $instances = []; + $specs = []; + foreach ($property->getAttributes() as $attribute) { + $name = $attribute->getName(); + if (!is_a($name, ConstraintInterface::class, true)) { + continue; + } + try { + $instance = $attribute->newInstance(); + } catch (\Throwable $exception) { + $this->fail(sprintf( + '%s::$%s constraint %s is invalid: %s.', + $dto->getName(), + $property->getName(), + new \ReflectionClass($name)->getShortName(), + $exception->getMessage(), + )); + } + if (!$instance instanceof ConstraintInterface) { + $this->fail(sprintf( + '%s::$%s attribute %s must implement %s to be used as a constraint.', + $dto->getName(), + $property->getName(), + $name, + ConstraintInterface::class, + )); + } + $this->constraintApplies($instance, $typeName, $dto->getName(), $property->getName()); + $this->touch(new \ReflectionClass($instance)); + $arguments = []; + foreach ($attribute->getArguments() as $key => $argument) { + $arguments[$key] = $argument; + } + $instances[] = $instance; + $specs[] = ['class' => $instance::class, 'args' => $arguments]; + } + + return ['instances' => $instances, 'specs' => $specs]; + } + + private function constraintApplies(ConstraintInterface $constraint, string $typeName, string $class, string $property): void + { + $ok = match (true) { + $constraint instanceof Range => $typeName === 'int' || $typeName === 'float', + $constraint instanceof Length => $typeName === 'string' || $typeName === 'array', + $constraint instanceof Pattern, $constraint instanceof Email => $typeName === 'string', + default => true, + }; + if ($ok) { + return; + } + + $this->fail(sprintf( + '%s::$%s has #[%s], which does not apply to %s. %s', + $class, + $property, + new \ReflectionClass($constraint)->getShortName(), + $typeName, + match (true) { + $constraint instanceof Range => 'Use it on int or float.', + $constraint instanceof Length => 'Use it on string (characters) or a list (items).', + default => 'Use it on a string.', + }, + )); + } + + /** + * @param \ReflectionClass<*> $dto + * @return array{class: class-string|null, arguments: array, schema: array|null} + */ + private function caster(\ReflectionProperty $property, \ReflectionClass $dto, string $typeName, bool $builtin, ?string $listItem, bool $listBuiltin): array + { + $found = $property->getAttributes(Cast::class); + if (count($found) > 1) { + $this->fail(sprintf('%s::$%s has more than one #[Cast]. Keep one caster; it replaces the built-in conversion.', $dto->getName(), $property->getName())); + } + if ($found === []) { + return ['class' => null, 'arguments' => [], 'schema' => null]; + } + + try { + $cast = $found[0]->newInstance(); + } catch (\Throwable $exception) { + $this->fail(sprintf('%s::$%s #[Cast] is invalid: %s.', $dto->getName(), $property->getName(), $exception->getMessage())); + } + $class = $cast->caster; + if (!class_exists($class)) { + $this->fail(sprintf( + '%s::$%s #[Cast] names %s, which does not exist. Use a class that implements %s, for example #[Cast(%s::class, \'d.m.Y\')].', + $dto->getName(), + $property->getName(), + $class, + CasterInterface::class, + DateFormat::class, + )); + } + + $reflection = new \ReflectionClass($class); + $this->touch($reflection); + if (!$reflection->isInstantiable() || !$reflection->implementsInterface(CasterInterface::class)) { + $this->fail(sprintf( + '%s::$%s caster %s must be a concrete class implementing %s.', + $dto->getName(), + $property->getName(), + $class, + CasterInterface::class, + )); + } + try { + $instance = $reflection->newInstanceArgs($cast->arguments); + } catch (\Throwable $exception) { + $this->fail(sprintf( + '%s::$%s caster %s cannot be created with the #[Cast] arguments: %s. Its constructor is __construct(%s).', + $dto->getName(), + $property->getName(), + $class, + $exception->getMessage(), + implode(', ', array_map( + static fn (\ReflectionParameter $parameter): string => $parameter->getType() === null ? '$' . $parameter->getName() : sprintf('%s $%s', (string) $parameter->getType(), $parameter->getName()), + $reflection->getConstructor()?->getParameters() ?? [], + )), + )); + } + + $this->casterReturn($reflection, $dto, $property->getName(), $typeName, $builtin, $listItem); + $schema = null; + if ($instance instanceof OpenApiCasterInterface) { + try { + $hint = $instance->openApiSchema(); + } catch (\Throwable $exception) { + $this->fail(sprintf('%s::openApiSchema() failed: %s. Return type, format and example of the wire value.', $class, $exception->getMessage())); + } + $unknown = array_diff(array_keys($hint), ['type', 'format', 'example']); + if ($unknown !== []) { + $this->fail(sprintf( + '%s::openApiSchema() returned %s. Return only type, format and example; they describe the wire value and do not change validation.', + $class, + implode(', ', $unknown), + )); + } + $schema = $hint + ['type' => 'string']; + } + // without a hint the wire value of a caster is a string; its result type says nothing about the request + $schema ??= ['type' => 'string']; + + return ['class' => $class, 'arguments' => $cast->arguments, 'schema' => $schema]; + } + + /** + * @param \ReflectionClass<*> $caster + * @param \ReflectionClass<*> $dto + */ + private function casterReturn(\ReflectionClass $caster, \ReflectionClass $dto, string $property, string $typeName, bool $builtin, ?string $listItem): void + { + $method = $caster->getMethod('cast'); + $return = $method->getReturnType(); + if (!$return instanceof \ReflectionNamedType || $return->allowsNull() || $return->getName() === 'mixed') { + $this->fail(sprintf( + '%s::cast() must declare a native return type identical to %s::$%s (%s). `mixed` and nullable returns are not accepted.', + $caster->getName(), + $dto->getName(), + $property, + $listItem !== null ? 'array' : $typeName, + )); + } + + $returnName = $return->getName(); + if ($listItem !== null) { + if ($returnName !== 'array') { + $this->fail(sprintf( + '%s::cast() must return array for %s::$%s, which is list<%s>. It returns %s.', + $caster->getName(), + $dto->getName(), + $property, + $listItem, + $returnName, + )); + } + $documented = $this->documentedList($method); + $expected = $listItem; + if ($documented === null || TypeName::resolve($documented, $caster) !== $expected) { + $this->fail(sprintf( + '%s::cast() must document `@return list<%s>` because %s::$%s is that list%s. The check reads the docblock of cast().', + $caster->getName(), + $listItem, + $dto->getName(), + $property, + $documented === null ? '' : sprintf(' (it documents list<%s>; a caster gives one item type, for example Split gives list, so list needs a caster of its own)', $documented), + )); + } + } + if ($builtin) { + if ($returnName !== $typeName) { + $this->fail(sprintf( + '%s::cast() must return %s, the type of %s::$%s. It returns %s.', + $caster->getName(), + $typeName, + $dto->getName(), + $property, + $returnName, + )); + } + + return; + } + + if (!is_a($returnName, $typeName, true)) { + $this->fail(sprintf( + '%s::cast() must return %s or a subtype, the type of %s::$%s. It returns %s.', + $caster->getName(), + $typeName, + $dto->getName(), + $property, + $returnName, + )); + } + } + + private function documentedList(\ReflectionMethod $method): ?string + { + $doc = $method->getDocComment(); + if ($doc === false || preg_match('/@return\s+list\s*<\s*([^>]+?)\s*>/', $doc, $match) !== 1) { + return null; + } + + return $match[1]; + } + + /** + * Checks the defaults with every sibling known, so a cross-field constraint can read the other properties. + * A sibling without a default is null, as for an omitted value at runtime. + * + * @param list $fields + */ + private function checkDefaults(string $class, array $fields): void + { + $properties = array_map(static fn (Field $field): string => $field->property, $fields); + $defaults = []; + foreach ($fields as $field) { + if ($field->hasDefault) { + $defaults[$field->property] = $field->default; + } + } + foreach ($fields as $field) { + if (!$field->hasDefault || $field->default === null) { + continue; + } + $context = new ConstraintContext($field->property, $class, $properties, $defaults); + foreach ($field->constraints as $constraint) { + $message = $constraint->validate($field->default, $context); + if ($message !== null) { + $this->fail(sprintf( + '%s::$%s default does not satisfy #[%s]: %s. Change the default or the constraint.', + $class, + $field->property, + new \ReflectionClass($constraint)->getShortName(), + $message, + )); + } + } + } + } + + /** + * The default is kept in the compiled container, so it is null, a scalar, a list or map of those, or a backed enum case. + * Rejecting objects here makes the container and the plain runtime behave the same. + */ + private function checkDefaultValue(string $class, string $property, mixed $default): void + { + if (is_array($default)) { + foreach ($default as $item) { + $this->checkDefaultValue($class, $property, $item); + } + } elseif (is_object($default) && !$default instanceof \BackedEnum) { + $this->fail(sprintf( + '%s::$%s has a default of type %s. A default is null, a scalar, an array or a backed enum case, because it is stored in the compiled container. Use `= null` and create the %s in the handler.', + $class, + $property, + $default::class, + new \ReflectionClass($default)->getShortName(), + )); + } + } + + /** + * A list default is a PHP value of the result type, so every item has to have the declared item type. + */ + private function checkListDefault(string $class, string $property, mixed $default, ?string $listItem, bool $listItemBuiltin): void + { + if (!is_array($default) || $listItem === null) { + return; + } + if (!array_is_list($default)) { + $this->fail(sprintf('%s::$%s default must be a list, for example [], because the property is list<%s>.', $class, $property, $listItem)); + } + foreach ($default as $index => $item) { + $valid = match (true) { + !$listItemBuiltin => $item instanceof $listItem, + $listItem === 'int' => is_int($item), + $listItem === 'float' => is_float($item) || is_int($item), + $listItem === 'bool' => is_bool($item), + default => is_string($item), + }; + if (!$valid) { + $this->fail(sprintf( + '%s::$%s default item %d is %s, but the property is list<%s>. Change the default.', + $class, + $property, + $index, + get_debug_type($item), + $listItem, + )); + } + } + } + + /** + * @param list $fields + */ + private static function containsFile(array $fields): bool + { + return array_any($fields, static fn (Field $field): bool => $field->source === Source::File); + } + + /** @param \ReflectionClass<*> $class */ + private function touch(\ReflectionClass $class): void + { + // the class and its parents: an inherited constructor or default changes the metadata too + for ($current = $class; $current instanceof \ReflectionClass; $current = $current->getParentClass() ?: null) { + $this->touchFile($current); + $this->touchTraits($current); + } + } + + /** @param \ReflectionClass<*> $class */ + private function touchTraits(\ReflectionClass $class): void + { + // a trait can declare the properties, the constructor or the constants, and it may use traits itself + foreach ($class->getTraits() as $trait) { + $this->touchFile($trait); + $this->touchTraits($trait); + } + } + + /** @param \ReflectionClass<*> $class */ + private function touchFile(\ReflectionClass $class): void + { + $file = $class->getFileName(); + if (is_string($file)) { + $this->files[$file] = $file; + } + } + + private function fail(string $message): never + { + throw new \LogicException($message); + } +} diff --git a/src/Input/DtoMapper.php b/src/Input/DtoMapper.php new file mode 100644 index 000000000..a21e9b899 --- /dev/null +++ b/src/Input/DtoMapper.php @@ -0,0 +1,406 @@ + */ + private array $values = []; + + /** @var array> */ + private array $errors = []; + + /** Errors produced so far in this request, nested ones included. */ + private int $errorCount = 0; + + /** Something was left unchecked because the budget was spent. */ + private bool $skipped = false; + + public function __construct(private readonly DtoMetadata $metadata) + { + } + + public function value(Field $field): mixed + { + $this->evaluate(); + if (array_key_exists($field->property, $this->values)) { + return $this->values[$field->property]; + } + + return $field->hasDefault ? $field->default : null; + } + + /** + * @return array> + */ + public function errors(Field $field): array + { + $this->evaluate(); + $own = []; + $name = $field->externalName; + foreach ($this->errors as $path => $messages) { + if ($path === $name || str_starts_with($path, sprintf('%s.', $name)) || str_starts_with($path, sprintf('%s[', $name))) { + $own[$path] = $messages; + } + } + // errors of the request as a whole belong to one field, so that they are reported once: the first body field, or the first field when nothing reads a body + if ($field->property === ($this->metadata->firstBody ?? $this->metadata->fields[0]->property) && isset($this->errors['body'])) { + $own['body'] = $this->errors['body']; + } + + return $own; + } + + private function evaluate(): void + { + if ($this->done) { + return; + } + $this->done = true; + + RequestInput::boot($this->metadata->handler, $this->metadata->contentTypes, $this->metadata->bodyRequired, $this->metadata->readsBody); + $failure = RequestInput::failure(); + $converted = []; + foreach ($this->untilTruncated($this->metadata->fields) as $field) { + if ($failure !== null && $field->readsBody()) { + continue; + } + $result = $this->convert($field, RequestInput::read($field), $field->externalName); + if ($result['errors'] !== []) { + self::merge($this->errors, $result['errors'], $result['value']); + continue; + } + $converted[$field->property] = $result['value']; + } + + $properties = array_map(static fn (Field $field): string => $field->property, $this->metadata->fields); + foreach ($this->metadata->fields as $field) { + if (!array_key_exists($field->property, $converted) || $converted[$field->property] === null) { + continue; + } + foreach ($this->messages($field, $converted[$field->property], $field->externalName, $properties, $converted) as $message) { + $this->errors[$field->externalName][] = $message; + } + } + if ($failure !== null) { + $this->errors['body'][] = $failure; + } + if ($this->skipped) { + // under `body` because it is about the request as a whole, not about the field that happened to use the last of the budget + $this->errors['body'][] = sprintf('Only the first %d errors are reported, the rest of the request was not checked', self::MAX_ERRORS); + } + $this->values = $converted; + } + + /** + * @return array{value: mixed, errors: array>} + */ + private function convert(Field $field, mixed $raw, string $path): array + { + if ($raw instanceof MissingValue) { + if ($field->hasDefault) { + return ['value' => $field->default, 'errors' => []]; + } + if ($field->nullable) { + return ['value' => null, 'errors' => []]; + } + + if ($field->source === Source::File && RequestInput::mediaType() !== MediaTypes::MULTIPART) { + return $this->fail($path, 'File is required and can only be uploaded as multipart/form-data, but the request is ' . RequestInput::mediaType()); + } + + return $this->fail($path, 'Field is required'); + } + if ($raw === null) { + if ($field->nullable) { + return ['value' => null, 'errors' => []]; + } + + return $this->fail($path, 'Value must not be null'); + } + + if ($field->casterClass !== null) { + try { + $caster = new ($field->casterClass)(...$field->casterArguments); + $value = $caster->cast($raw); + } catch (CastException $exception) { + return $this->fail($path, $exception->getMessage()); + } + + return ['value' => $value, 'errors' => []]; + } + + if ($field->source === Source::File || $field->typeName === FileUpload::class) { + return $this->file($field, $raw, $path); + } + if ($field->item instanceof Field) { + return $this->list($field, $raw, $path); + } + if ($field->children !== []) { + return $this->object($field, $raw, $path); + } + + try { + return ['value' => $this->scalar($field, $raw), 'errors' => []]; + } catch (ConversionFailed $exception) { + return $this->fail($path, $exception->getMessage()); + } + } + + /** + * @return array{value: mixed, errors: array>} + */ + private function object(Field $field, mixed $raw, string $path): array + { + if ($raw instanceof \stdClass) { + $raw = get_object_vars($raw); + } elseif (!is_array($raw) || array_is_list($raw)) { + return $this->fail($path, 'Value must be an object'); + } + + $converted = []; + $errors = []; + foreach ($this->untilTruncated($field->children) as $child) { + $childRaw = array_key_exists($child->externalName, $raw) ? $raw[$child->externalName] : new MissingValue(); + $result = $this->convert($child, $childRaw, sprintf('%s.%s', $path, $child->externalName)); + if ($result['errors'] !== []) { + self::merge($errors, $result['errors'], $result['value']); + continue; + } + $converted[$child->property] = $result['value']; + } + + $properties = array_map(static fn (Field $child): string => $child->property, $field->children); + foreach ($field->children as $child) { + if (!array_key_exists($child->property, $converted) || $converted[$child->property] === null) { + continue; + } + $childPath = sprintf('%s.%s', $path, $child->externalName); + foreach ($this->messages($child, $converted[$child->property], $childPath, $properties, $converted) as $message) { + $errors[$childPath][] = $message; + } + } + if ($errors !== []) { + return ['value' => null, 'errors' => $errors]; + } + + return ['value' => $this->instantiate($field->typeName, $field->children, $converted), 'errors' => []]; + } + + /** + * @return array{value: mixed, errors: array>} + */ + private function list(Field $field, mixed $raw, string $path): array + { + if (!is_array($raw) || !array_is_list($raw)) { + return $this->fail($path, 'Value must be a list'); + } + + // the item count alone decides Length, so a list of the wrong size is rejected before its items are converted + foreach ($field->constraints as $constraint) { + $message = $constraint instanceof Length ? $constraint->validate($raw, new ConstraintContext($path, $field->dtoClass, [], [])) : null; + if ($message !== null) { + return $this->fail($path, $message); + } + } + + $item = $field->itemField(); + + $values = []; + $errors = []; + $index = 0; + foreach ($this->untilTruncated($raw) as $value) { + $result = $this->convert($item, $value, sprintf('%s[%d]', $path, $index++)); + if ($result['errors'] !== []) { + self::merge($errors, $result['errors'], $result['value']); + continue; + } + $values[] = $result['value']; + } + if ($errors !== []) { + return ['value' => null, 'errors' => $errors]; + } + + return ['value' => $values, 'errors' => []]; + } + + /** + * @return array{value: mixed, errors: array>} + */ + private function file(Field $field, mixed $raw, string $path): array + { + if ($field->listItem === FileUpload::class) { + if (!is_array($raw)) { + return $this->fail($path, 'Value must be a file upload'); + } + $uploads = []; + foreach (self::fileList($raw) as $file) { + $uploads[] = FileUpload::fromFile($file); + } + + return ['value' => $uploads, 'errors' => []]; + } + + if (is_array($raw) && is_array($raw['name'] ?? null)) { + return $this->fail($path, 'Value must be a file upload'); + } + + return ['value' => FileUpload::fromFile(self::fileEntry(is_array($raw) ? $raw : [])), 'errors' => []]; + } + + /** + * @param array $file + * @return array> + */ + private static function fileList(array $file): array + { + if (!is_array($file['name'] ?? null)) { + return [self::fileEntry($file)]; + } + + $result = []; + foreach (['name', 'type', 'tmp_name', 'error', 'size'] as $key) { + $values = $file[$key] ?? null; + if (!is_array($values)) { + continue; + } + foreach ($values as $index => $value) { + $result[$index][$key] = $value; + } + } + + return $result; + } + + /** + * @param array $file + * @return array + */ + private static function fileEntry(array $file): array + { + $entry = []; + foreach ($file as $key => $value) { + $entry[$key] = $value; + } + + return $entry; + } + + private function scalar(Field $field, mixed $raw): mixed + { + if ($field->enumClass !== null) { + return ScalarCoercer::toEnum($raw, $field->enumClass); + } + + if ($field->typeName === 'int') { + return ScalarCoercer::toInt($raw); + } + if ($field->typeName === 'float') { + return ScalarCoercer::toFloat($raw); + } + if ($field->typeName === 'bool') { + return ScalarCoercer::toBool($raw); + } + if ($field->typeName === 'string') { + return ScalarCoercer::toString($raw); + } + + return ScalarCoercer::toDateTime($raw); + } + + /** + * @param list $children + * @param array $values + */ + private function instantiate(string $class, array $children, array $values): object + { + $arguments = []; + foreach ($children as $child) { + $arguments[$child->property] = $values[$child->property]; + } + + return new $class(...$arguments); + } + + /** + * @param list $properties + * @param array $values + * @return list + */ + private function messages(Field $field, mixed $value, string $path, array $properties, array $values): array + { + $context = new ConstraintContext($path, $field->dtoClass, $properties, $values); + $messages = []; + foreach ($field->constraints as $constraint) { + $message = $constraint->validate($value, $context); + if ($message !== null) { + $messages[] = $message; + } + } + + $this->errorCount += count($messages); + + return $messages; + } + + /** + * The items of a list, the children of an object or the fields of the DTO, up to the point where the error budget is spent. + * + * @template TValue + * @param array $items + * @return \Generator + */ + private function untilTruncated(array $items): \Generator + { + foreach ($items as $item) { + if ($this->errorCount >= self::MAX_ERRORS) { + $this->skipped = true; + + return; + } + yield $item; + } + } + + /** + * @return array{value: null, errors: array>} + */ + private function fail(string $path, string $message): array + { + ++$this->errorCount; + + return ['value' => null, 'errors' => [$path => [$message]]]; + } + + /** + * Appends in place: copying the whole error array for every bad item made a long invalid list quadratic. + * + * @param array> $left + * @param array> $right + */ + private static function merge(array &$left, array $right, mixed $value): void + { + if ($value !== null) { + throw new \LogicException('A field error is reported without discarding the converted value.'); + } + + foreach ($right as $path => $messages) { + foreach ($messages as $message) { + $left[$path][] = $message; + } + } + } +} diff --git a/src/Input/DtoMetadata.php b/src/Input/DtoMetadata.php new file mode 100644 index 000000000..d42565e58 --- /dev/null +++ b/src/Input/DtoMetadata.php @@ -0,0 +1,133 @@ + $fields root properties, in constructor order + * @param list $contentTypes + * @param list $files absolute paths of the handler and DTO files, so editing one rebuilds the container + */ + public function __construct( + public string $handler, + public string $class, + public array $fields, + public array $contentTypes, + public bool $bodyRequired, + public bool $readsBody, + public ?string $firstBody, + public array $files, + ) { + } + + /** + * @return list + */ + public function inputParams(): array + { + $mapper = new DtoMapper($this); + $params = []; + foreach ($this->fields as $field) { + $params[] = new MappedInputParam($field, $mapper, $this); + } + + return $params; + } + + /** + * @param array $values values keyed by the external name, already converted + */ + public function instantiate(array $values): object + { + $arguments = []; + foreach ($this->fields as $field) { + $arguments[$field->property] = $values[$field->externalName]; + } + + return new ($this->class)(...$arguments); + } + + /** + * @return list + */ + public function pathNames(): array + { + $names = []; + foreach ($this->fields as $field) { + if ($field->source === Source::Path) { + $names[] = $field->externalName; + } + } + + return $names; + } + + /** + * @return array + */ + public function export(): array + { + return [ + 'handler' => $this->handler, + 'class' => $this->class, + 'fields' => array_map(static fn (Field $field): array => $field->export(), $this->fields), + 'contentTypes' => $this->contentTypes, + 'bodyRequired' => $this->bodyRequired, + 'readsBody' => $this->readsBody, + 'firstBody' => $this->firstBody, + 'files' => $this->files, + ]; + } + + /** + * @param array $data + */ + public static function import(array $data): self + { + $fields = []; + $exportedFields = $data['fields'] ?? null; + if (!is_array($exportedFields)) { + throw new \LogicException('Compiled DTO metadata has no fields. Rebuild the DI container.'); + } + foreach ($exportedFields as $field) { + if (!is_array($field)) { + throw new \LogicException('Compiled DTO metadata has a field that is not an array. Rebuild the DI container.'); + } + $fields[] = Field::import(self::stringKeyed($field)); + } + + return new self( + is_string($data['handler']) ? $data['handler'] : '', + is_string($data['class']) ? $data['class'] : '', + $fields, + is_array($data['contentTypes']) ? array_values(array_filter($data['contentTypes'], is_string(...))) : [], + (bool) $data['bodyRequired'], + (bool) $data['readsBody'], + is_string($data['firstBody']) ? $data['firstBody'] : null, + is_array($data['files']) ? array_values(array_filter($data['files'], is_string(...))) : [], + ); + } + + /** + * @param array $data + * @return array + */ + private static function stringKeyed(array $data): array + { + $keyed = []; + foreach ($data as $key => $value) { + $keyed[$key] = $value; + } + + return $keyed; + } +} diff --git a/src/Input/DtoMetadataRegistry.php b/src/Input/DtoMetadataRegistry.php new file mode 100644 index 000000000..b35482fb6 --- /dev/null +++ b/src/Input/DtoMetadataRegistry.php @@ -0,0 +1,73 @@ + */ + private array $handlers = []; + + /** @var array */ + private static array $runtime = []; + + private static ?self $installed = null; + + /** + * @param array> $exported + */ + public static function install(array $exported): void + { + $registry = new self(); + foreach ($exported as $handler => $data) { + $registry->handlers[$handler] = DtoMetadata::import($data); + } + self::$installed = $registry; + } + + /** + * @internal + */ + public static function installed(): bool + { + return self::$installed !== null; + } + + /** + * @internal + */ + public static function installs(string $handler): bool + { + return self::$installed !== null && isset(self::$installed->handlers[$handler]); + } + + /** + * @param class-string $handler + */ + public static function forHandler(string $handler): DtoMetadata + { + if (self::$installed !== null && isset(self::$installed->handlers[$handler])) { + return self::$installed->handlers[$handler]; + } + if (isset(self::$runtime[$handler])) { + return self::$runtime[$handler]; + } + + return self::$runtime[$handler] = DtoCompiler::compile($handler); + } + + /** + * @internal + */ + public static function reset(): void + { + self::$installed = null; + self::$runtime = []; + } +} diff --git a/src/Input/EndpointTemplate.php b/src/Input/EndpointTemplate.php new file mode 100644 index 000000000..24a8fb5be --- /dev/null +++ b/src/Input/EndpointTemplate.php @@ -0,0 +1,195 @@ + + */ + public static function placeholders(string $url): array + { + $names = []; + foreach (self::segments($url) as $segment) { + if (preg_match('/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/', $segment, $match) === 1) { + $names[] = $match[1]; + } + } + + return $names; + } + + /** + * True when a package or action may contain slashes because it is a {name} template. + */ + public static function isComposite(string $value): bool + { + if (!str_contains($value, '{') || !str_contains($value, '/')) { + return false; + } + return array_all(explode('/', $value), fn($segment): bool => !(preg_match('/^(?:[A-Za-z0-9_.-]+|\{[A-Za-z_][A-Za-z0-9_]*\})$/', $segment) !== 1)); + } + + /** + * Captured path parameters when $path matches $template, otherwise null. + * Both values are endpoint URLs such as v1/users/{id}/detail and v1/users/42/detail. + * + * @return array|null + */ + public static function match(string $template, string $path): ?array + { + $expected = self::segments($template); + $actual = self::segments($path); + if (count($expected) !== count($actual)) { + return null; + } + + $captured = []; + foreach ($expected as $index => $segment) { + if (preg_match('/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/', $segment, $match) === 1) { + if ($actual[$index] === '') { + return null; + } + $captured[$match[1]] = $actual[$index]; + continue; + } + if ($segment !== $actual[$index]) { + return null; + } + } + + return $captured; + } + + /** + * Request path reduced to the endpoint URL (v1/users/42), or null when the version is not in the path. + */ + public static function normalize(string $requestPath, string $version): ?string + { + $path = parse_url($requestPath, PHP_URL_PATH); + $path = rawurldecode(is_string($path) ? $path : $requestPath); + $marker = sprintf('/v%s/', $version); + $position = strpos($path, $marker); + if ($position === false) { + $trimmed = trim($path, '/'); + $prefix = sprintf('v%s', $version); + if ($trimmed === $prefix || str_starts_with($trimmed, sprintf('%s/', $prefix))) { + return $trimmed; + } + + return null; + } + + return trim(substr($path, $position), '/'); + } + + /** + * @param list $declared external names of the path parameters + */ + public static function assert(string $url, array $declared, string $where): void + { + $placeholders = self::placeholders($url); + $duplicatePlaceholders = array_diff_assoc($placeholders, array_unique($placeholders)); + if ($duplicatePlaceholders !== []) { + throw new \LogicException(sprintf( + "%s: the endpoint URL '%s' repeats {%s}. Use each path parameter once, for example users/{id}/detail.", + $where, + trim($url, '/'), + implode(', ', array_unique($duplicatePlaceholders)), + )); + } + + foreach (self::segments($url) as $segment) { + if (str_contains($segment, '{') && preg_match('/^\{[A-Za-z_][A-Za-z0-9_]*\}$/', $segment) !== 1) { + throw new \LogicException(sprintf( + "%s: '%s' is not a path parameter in the endpoint URL '%s'. Write a name in braces, for example {id}, as its own URL segment.", + $where, + $segment, + trim($url, '/'), + )); + } + } + + $missing = array_diff($placeholders, $declared); + $undeclared = array_diff($declared, $placeholders); + if ($missing === [] && $undeclared === []) { + return; + } + + throw new \LogicException(sprintf( + "%s: the endpoint URL '%s' and its path parameters do not match. The URL has {%s} and the handler declares [%s]. Every {name} needs a #[Path] property or a PathInputParam with that name, and every path parameter must appear in the URL, for example #[Get(1, 'users', '{id}/detail')] with #[Path] public int \$id.", + $where, + trim($url, '/'), + implode(', ', $placeholders), + implode(', ', $declared), + )); + } + + /** + * Two templates of the same method that can match one request. + * + * @param array> $urlsByMethod method => endpoint URLs + */ + public static function assertDisjoint(array $urlsByMethod): void + { + foreach ($urlsByMethod as $method => $urls) { + $templates = $urls; + $count = count($templates); + for ($left = 0; $left < $count; $left++) { + $leftUrl = $templates[$left]; + for ($right = $left + 1; $right < $count; $right++) { + if (self::overlaps($leftUrl, $templates[$right])) { + throw new \LogicException(sprintf( + "%s endpoints '%s' and '%s' can match the same request. Make a static segment differ, or give them a different number of segments, so only one template matches.", + $method, + trim($templates[$left], '/'), + trim($templates[$right], '/'), + )); + } + } + } + } + } + + public static function overlaps(string $left, string $right): bool + { + if (!str_contains($left, '{') || !str_contains($right, '{')) { + return false; + } + + $leftSegments = self::segments($left); + $rightSegments = self::segments($right); + if (count($leftSegments) !== count($rightSegments)) { + return false; + } + + foreach ($leftSegments as $index => $segment) { + $other = $rightSegments[$index]; + $leftPlaceholder = preg_match('/^\{[A-Za-z_][A-Za-z0-9_]*\}$/', $segment) === 1; + $rightPlaceholder = preg_match('/^\{[A-Za-z_][A-Za-z0-9_]*\}$/', $other) === 1; + if (!$leftPlaceholder && !$rightPlaceholder && $segment !== $other) { + return false; + } + } + + return true; + } + + /** + * @return list + */ + private static function segments(string $url): array + { + $url = trim($url, '/'); + if ($url === '') { + return []; + } + + return explode('/', $url); + } +} diff --git a/src/Input/Field.php b/src/Input/Field.php new file mode 100644 index 000000000..32cd6a912 --- /dev/null +++ b/src/Input/Field.php @@ -0,0 +1,327 @@ + $examples + * @param list $enumValues + * @param list $constraints + * @param list, args: array}> $constraintSpecs + * @param array $casterArguments + * @param array|null $casterSchema + * @param list $children + * @param class-string<\BackedEnum>|null $enumClass + * @param class-string|null $casterClass + */ + public function __construct( + public string $property, + public string $externalName, + public Source $source, + public string $typeName, + public bool $builtin, + public bool $nullable, + public bool $hasDefault, + public mixed $default, + public ?string $description, + public array $examples, + public ?string $listItem, + public bool $listItemBuiltin, + public ?string $enumClass, + public bool $enumInt, + public array $enumValues, + public array $constraints, + public array $constraintSpecs, + public ?string $casterClass, + public array $casterArguments, + public ?array $casterSchema, + public array $children, + public ?self $item, + public string $dtoClass, + ) { + } + + public function required(): bool + { + return !$this->nullable && !$this->hasDefault; + } + + public function itemField(): self + { + if (!$this->item instanceof self) { + throw new \LogicException(sprintf( + 'List property %s::$%s has no item type. Declare it with /** @param list $%s */ using list, list, list, list, list or a DTO.', + $this->dtoClass, + $this->property, + $this->property, + )); + } + + return $this->item; + } + + public function readsBody(): bool + { + return $this->source === Source::Body || $this->source === Source::File; + } + + /** + * @return array + */ + public function export(): array + { + return [ + 'property' => $this->property, + 'externalName' => $this->externalName, + 'source' => $this->source->value, + 'typeName' => $this->typeName, + 'builtin' => $this->builtin, + 'nullable' => $this->nullable, + 'hasDefault' => $this->hasDefault, + 'default' => ValueExport::export($this->default), + 'description' => $this->description, + 'examples' => ValueExport::export($this->examples), + 'listItem' => $this->listItem, + 'listItemBuiltin' => $this->listItemBuiltin, + 'enumClass' => $this->enumClass, + 'enumInt' => $this->enumInt, + 'enumValues' => $this->enumValues, + 'constraintSpecs' => ValueExport::export($this->constraintSpecs), + 'casterClass' => $this->casterClass, + 'casterArguments' => ValueExport::export($this->casterArguments), + 'casterSchema' => $this->casterSchema, + 'children' => array_map(static fn (self $child): array => $child->export(), $this->children), + 'item' => $this->item?->export(), + 'dtoClass' => $this->dtoClass, + ]; + } + + /** + * @param array $data + */ + public static function import(array $data): self + { + $constraints = self::importConstraints($data); + $children = []; + foreach (self::rows($data, 'children') as $child) { + $children[] = self::import(self::stringKeyed($child)); + } + $item = $data['item'] ?? null; + $enumClass = self::nullableString($data, 'enumClass'); + if ($enumClass !== null && !is_a($enumClass, \BackedEnum::class, true)) { + throw new \LogicException(sprintf("Compiled field metadata has enum '%s', which is not a backed enum. Rebuild the DI container.", $enumClass)); + } + $casterClass = self::nullableString($data, 'casterClass'); + if ($casterClass !== null && !is_a($casterClass, CasterInterface::class, true)) { + throw new \LogicException(sprintf("Compiled field metadata has caster '%s', which does not implement %s. Rebuild the DI container.", $casterClass, CasterInterface::class)); + } + + return new self( + self::string($data, 'property'), + self::string($data, 'externalName'), + Source::from(self::string($data, 'source')), + self::string($data, 'typeName'), + self::bool($data, 'builtin'), + self::bool($data, 'nullable'), + self::bool($data, 'hasDefault'), + ValueExport::import($data['default'] ?? null), + self::nullableString($data, 'description'), + self::stringMap(ValueExport::import($data['examples'] ?? [])), + self::nullableString($data, 'listItem'), + self::bool($data, 'listItemBuiltin'), + $enumClass, + self::bool($data, 'enumInt'), + self::enumValues($data), + $constraints['instances'], + $constraints['specs'], + $casterClass, + self::mixedList(ValueExport::import($data['casterArguments'] ?? [])), + self::optionalMap($data['casterSchema'] ?? null), + $children, + is_array($item) ? self::import(self::stringKeyed($item)) : null, + self::string($data, 'dtoClass'), + ); + } + + /** + * @param array $data + * @return array{instances: list, specs: list, args: array}>} + */ + private static function importConstraints(array $data): array + { + $imported = ValueExport::import($data['constraintSpecs'] ?? []); + if (!is_array($imported)) { + throw new \LogicException('Compiled field metadata is missing constraints. Rebuild the DI container.'); + } + $instances = []; + $specs = []; + foreach ($imported as $spec) { + if (!is_array($spec) || !is_string($spec['class'] ?? null) || !is_array($spec['args'] ?? null) || !is_a($spec['class'], ConstraintInterface::class, true)) { + throw new \LogicException('Compiled constraint metadata is invalid. Rebuild the DI container.'); + } + $class = $spec['class']; + $args = []; + foreach ($spec['args'] as $key => $argument) { + $args[$key] = $argument; + } + $instances[] = new $class(...$args); + $specs[] = ['class' => $class, 'args' => $args]; + } + + return ['instances' => $instances, 'specs' => $specs]; + } + + /** + * @param array $data + * @return list> + */ + private static function rows(array $data, string $key): array + { + $rows = $data[$key] ?? []; + if (!is_array($rows)) { + throw new \LogicException(sprintf('Compiled field metadata "%s" is not a list. Rebuild the DI container.', $key)); + } + $list = []; + foreach ($rows as $row) { + if (!is_array($row)) { + throw new \LogicException(sprintf('Compiled field metadata "%s" has an item that is not an array. Rebuild the DI container.', $key)); + } + $list[] = $row; + } + + return $list; + } + + /** + * @param array $data + * @return array + */ + private static function stringKeyed(array $data): array + { + $keyed = []; + foreach ($data as $key => $value) { + $keyed[$key] = $value; + } + + return $keyed; + } + + /** + * @param array $data + */ + private static function string(array $data, string $key): string + { + $value = $data[$key] ?? null; + if (!is_string($value) || $value === '') { + throw new \LogicException(sprintf('Compiled field metadata is missing "%s". Rebuild the DI container.', $key)); + } + + return $value; + } + + /** + * @param array $data + */ + private static function nullableString(array $data, string $key): ?string + { + $value = $data[$key] ?? null; + if ($value === null) { + return null; + } + if (!is_string($value)) { + throw new \LogicException(sprintf('Compiled field metadata "%s" must be a string or null. Rebuild the DI container.', $key)); + } + + return $value === '' ? null : $value; + } + + /** + * @param array $data + */ + private static function bool(array $data, string $key): bool + { + $value = $data[$key] ?? null; + if (!is_bool($value)) { + throw new \LogicException(sprintf('Compiled field metadata "%s" must be a boolean. Rebuild the DI container.', $key)); + } + + return $value; + } + + /** + * @param mixed $value + * @return array + */ + private static function stringMap(mixed $value): array + { + if (!is_array($value)) { + throw new \LogicException('Compiled field metadata examples must be an array. Rebuild the DI container.'); + } + $mapped = []; + foreach ($value as $key => $item) { + if (!is_string($key)) { + throw new \LogicException('Compiled field metadata examples must be named. Rebuild the DI container.'); + } + $mapped[$key] = $item; + } + + return $mapped; + } + + /** + * @param mixed $value + * @return array + */ + private static function mixedList(mixed $value): array + { + if (!is_array($value)) { + throw new \LogicException('Compiled field metadata arguments must be an array. Rebuild the DI container.'); + } + + return $value; + } + + /** + * @return array|null + */ + private static function optionalMap(mixed $value): ?array + { + if ($value === null) { + return null; + } + if (!is_array($value)) { + throw new \LogicException('Compiled field metadata schema must be an array. Rebuild the DI container.'); + } + return array_filter($value, is_string(...), ARRAY_FILTER_USE_KEY); + } + + /** + * @param array $data + * @return list + */ + private static function enumValues(array $data): array + { + $values = $data['enumValues'] ?? []; + if (!is_array($values)) { + throw new \LogicException('Compiled field metadata enum values must be a list. Rebuild the DI container.'); + } + $list = []; + foreach ($values as $value) { + if (!is_int($value) && !is_string($value)) { + throw new \LogicException('Compiled field metadata enum values must be strings or integers. Rebuild the DI container.'); + } + $list[] = $value; + } + + return $list; + } +} diff --git a/src/Input/File.php b/src/Input/File.php new file mode 100644 index 000000000..d61ad823a --- /dev/null +++ b/src/Input/File.php @@ -0,0 +1,22 @@ + $examples named examples, the same pairs as InputParam::addExample() + */ + public function __construct( + public ?string $name = null, + public ?string $description = null, + public array $examples = [], + ) { + } +} diff --git a/src/Input/FileUpload.php b/src/Input/FileUpload.php new file mode 100644 index 000000000..7ceb73857 --- /dev/null +++ b/src/Input/FileUpload.php @@ -0,0 +1,34 @@ + $file one $_FILES entry (name, type, tmp_name, error, size) + */ + public static function fromFile(array $file): self + { + return new self( + is_string($file['name'] ?? null) ? $file['name'] : '', + is_string($file['type'] ?? null) ? $file['type'] : '', + is_string($file['tmp_name'] ?? null) ? $file['tmp_name'] : '', + is_int($file['size'] ?? null) ? $file['size'] : 0, + is_int($file['error'] ?? null) ? $file['error'] : \UPLOAD_ERR_NO_FILE, + ); + } +} diff --git a/src/Input/Header.php b/src/Input/Header.php new file mode 100644 index 000000000..d96bc2c91 --- /dev/null +++ b/src/Input/Header.php @@ -0,0 +1,23 @@ + $examples named examples, the same pairs as InputParam::addExample() + */ + public function __construct( + public ?string $name = null, + public ?string $description = null, + public array $examples = [], + ) { + } +} diff --git a/src/Input/MediaTypes.php b/src/Input/MediaTypes.php new file mode 100644 index 000000000..ef8c62d26 --- /dev/null +++ b/src/Input/MediaTypes.php @@ -0,0 +1,30 @@ + */ + public const array ALL = [self::JSON, self::FORM, self::MULTIPART]; + + public static function normalize(?string $header): string + { + if ($header === null || $header === '') { + return ''; + } + + $separator = strstr($header, ';', true); + return strtolower(trim($separator === false ? $header : $separator)); + } +} diff --git a/src/Input/MissingValue.php b/src/Input/MissingValue.php new file mode 100644 index 000000000..1b041d8d6 --- /dev/null +++ b/src/Input/MissingValue.php @@ -0,0 +1,12 @@ + $examples named examples, the same pairs as InputParam::addExample() + */ + public function __construct( + public ?string $name = null, + public ?string $description = null, + public array $examples = [], + ) { + } +} diff --git a/src/Input/Query.php b/src/Input/Query.php new file mode 100644 index 000000000..601910ee6 --- /dev/null +++ b/src/Input/Query.php @@ -0,0 +1,22 @@ + $examples named examples, the same pairs as InputParam::addExample() + */ + public function __construct( + public ?string $name = null, + public ?string $description = null, + public array $examples = [], + ) { + } +} diff --git a/src/Input/RequestInput.php b/src/Input/RequestInput.php new file mode 100644 index 000000000..232cb2db4 --- /dev/null +++ b/src/Input/RequestInput.php @@ -0,0 +1,332 @@ + */ + private static array $query = []; + + /** @var array */ + private static array $body = []; + + /** @var array */ + private static array $files = []; + + private static ?string $failure = null; + + private static ?string $mediaType = null; + + private static ?string $rawOverride = null; + + public static function reset(): void + { + self::$handler = null; + self::$query = []; + self::$body = []; + self::$files = []; + self::$failure = null; + self::$mediaType = null; + self::$rawOverride = null; + } + + /** + * Replaces php://input. Used by tests; a real request leaves this unset. + * + * @internal + */ + public static function setRawBody(string $raw): void + { + self::$rawOverride = $raw; + } + + /** + * @param list $consumes + */ + public static function boot(string $handler, array $consumes, bool $bodyRequired, bool $readsBody): void + { + if (self::$handler === $handler) { + return; + } + + self::$handler = $handler; + self::$query = self::stringMap($_GET); + self::$body = []; + self::$files = []; + self::$failure = null; + self::$mediaType = null; + if ($readsBody) { + self::loadBody($consumes, $bodyRequired); + } + } + + public static function failure(): ?string + { + return self::$failure; + } + + /** + * The accepted body media type without parameters, or null when the request has no body. + */ + public static function mediaType(): ?string + { + return self::$mediaType; + } + + public static function read(Field $field): mixed + { + return match ($field->source) { + Source::Query => self::value(self::$query, $field->externalName), + Source::Header => self::header($field->externalName), + Source::Path => self::path($field->externalName), + Source::File => self::file($field->externalName), + Source::Body => self::value(self::$body, $field->externalName), + }; + } + + /** + * @param array $data + */ + private static function value(array $data, string $name): mixed + { + if (!array_key_exists($name, $data)) { + return new MissingValue(); + } + + return $data[$name]; + } + + private static function header(string $name): mixed + { + if (!HeaderBag::has($name)) { + return new MissingValue(); + } + + return HeaderBag::get($name); + } + + private static function path(string $name): mixed + { + if (!PathValues::has($name)) { + return new MissingValue(); + } + + return PathValues::get($name); + } + + private static function file(string $name): mixed + { + if (!array_key_exists($name, self::$files)) { + return new MissingValue(); + } + + $file = self::$files[$name]; + if (!is_array($file)) { + return new MissingValue(); + } + $nameValue = $file['name'] ?? null; + $error = $file['error'] ?? null; + $empty = is_array($nameValue) + ? is_array($error) && $error !== [] && array_filter($error, static fn (mixed $slot): bool => $slot !== \UPLOAD_ERR_NO_FILE) === [] + : $error === \UPLOAD_ERR_NO_FILE && ($nameValue ?? '') === ''; + + return $empty ? new MissingValue() : $file; + } + + /** + * @param list $consumes + */ + private static function loadBody(array $consumes, bool $bodyRequired): void + { + $header = $_SERVER['CONTENT_TYPE'] ?? null; + if (!is_string($header)) { + $header = isset($_SERVER['HTTP_CONTENT_TYPE']) && is_string($_SERVER['HTTP_CONTENT_TYPE']) ? $_SERVER['HTTP_CONTENT_TYPE'] : null; + } + $type = MediaTypes::normalize($header); + if ($type === '') { + // a body that arrives without a type is never read silently: it would be dropped without a word + $raw = self::rawBody(); + if ($bodyRequired || (is_string($raw) && $raw !== '')) { + throw UnsupportedMediaTypeException::missing($consumes); + } + + return; + } + if (!in_array($type, $consumes, true)) { + throw UnsupportedMediaTypeException::received($type, $consumes); + } + self::$mediaType = $type; + if ($type === MediaTypes::JSON) { + self::$failure = self::charsetFailure($header ?? ''); + if (self::$failure === null) { + self::loadJson(); + } + + return; + } + + self::loadForm(); + } + + /** + * JSON is UTF-8 (RFC 8259), so another charset would be decoded wrongly instead of being ignored. + */ + private static function charsetFailure(string $header): ?string + { + // parameters are read like RFC 9110 does: a quoted value may contain `;` and `charset=` + preg_match_all('/;\s*([^=;\s]+)\s*=\s*("(?:[^"\\\\]|\\\\.)*"|[^;]*)/', $header, $matches, PREG_SET_ORDER); + foreach ($matches as $match) { + if (strtolower($match[1]) !== 'charset') { + continue; + } + $charset = strtolower(trim($match[2], "\" \t")); + + // us-ascii is a subset of UTF-8, and utf8 is how many clients spell it + return in_array($charset, ['utf-8', 'utf8', 'us-ascii'], true) + ? null + : sprintf('JSON must be UTF-8; the request says charset=%s', substr($charset, 0, self::CHARSET_SHOWN)); + } + + return null; + } + + private static function loadJson(): void + { + $raw = self::rawBody(); + if ($raw === false) { + self::$failure = 'Unable to read the request body'; + return; + } + if ($raw === '') { + return; + } + + $decoded = json_decode($raw); + if (json_last_error() !== JSON_ERROR_NONE) { + self::$failure = json_last_error_msg(); + return; + } + if (!$decoded instanceof \stdClass) { + self::$failure = 'Value must be an object'; + return; + } + + self::$body = self::objectProperties($decoded); + } + + private static function loadForm(): void + { + $method = $_SERVER['REQUEST_METHOD'] ?? 'GET'; + if ($method === 'POST' || $_POST !== [] || $_FILES !== []) { + self::$body = self::stringMap($_POST); + self::$files = self::stringMap($_FILES); + // PHP drops the variables over max_input_vars without a word, so a form that was cut is found by parsing its body again + if (self::$mediaType === MediaTypes::FORM && count($_POST, COUNT_RECURSIVE) >= self::maxInputVars()) { + $raw = self::rawBody(); + if (is_string($raw) && self::parseForm($raw) === null) { + self::$failure = self::TOO_MANY_FIELDS; + self::$body = []; + } + } + + return; + } + + $raw = self::rawBody(); + $parsed = []; + if (is_string($raw) && self::$mediaType === MediaTypes::MULTIPART && $raw !== '') { + self::$failure = sprintf('multipart/form-data is only parsed by PHP for POST requests, but this one is %s. Send it with POST, or use application/json', TypeHelper::toString($method)); + } elseif (is_string($raw)) { + $parsed = self::parseForm($raw); + if ($parsed === null) { + self::$failure = self::TOO_MANY_FIELDS; + $parsed = []; + } + } + self::$body = self::stringMap($parsed); + self::$files = self::stringMap($_FILES); + } + + private static function maxInputVars(): int + { + return (int) ini_get('max_input_vars'); + } + + /** + * @return array|null null when the body has more variables than max_input_vars + */ + private static function parseForm(string $raw): ?array + { + $exceeded = false; + // PHP warns when the body has more variables than max_input_vars; that is a client mistake, not a server warning + set_error_handler(static function () use (&$exceeded): bool { + $exceeded = true; + + return true; + }, E_WARNING); + parse_str($raw, $parsed); + restore_error_handler(); + + return $exceeded ? null : $parsed; + } + + /** + * Top-level properties of a JSON object. Nested objects stay stdClass and nested arrays stay lists, + * so {} and [] remain different when a field is mapped. + * + * @return array + */ + private static function objectProperties(\stdClass $object): array + { + $mapped = []; + foreach (get_object_vars($object) as $key => $value) { + $mapped[$key] = $value; + } + + return $mapped; + } + + /** + * @param array $values + * @return array + */ + private static function stringMap(array $values): array + { + $mapped = []; + foreach ($values as $key => $value) { + $mapped[$key] = $value; + } + + return $mapped; + } + + public static function rawContents(): string|false + { + return self::rawBody(); + } + + private static function rawBody(): string|false + { + if (self::$rawOverride !== null) { + return self::$rawOverride; + } + + return file_get_contents('php://input'); + } +} diff --git a/src/Input/ScalarCoercer.php b/src/Input/ScalarCoercer.php new file mode 100644 index 000000000..b3b06a240 --- /dev/null +++ b/src/Input/ScalarCoercer.php @@ -0,0 +1,175 @@ +format($format) !== $formatted) { + throw new ConversionFailed($message); + } + + return $date; + } + + /** + * @param class-string<\BackedEnum> $enum + */ + public static function toEnum(mixed $value, string $enum): \BackedEnum + { + $intBacked = is_int(($enum::cases()[0] ?? null)?->value); + try { + $coerced = $intBacked ? self::toInt($value) : self::toString($value); + } catch (ConversionFailed) { + throw new ConversionFailed(self::enumMessage($enum)); + } + + $case = $enum::tryFrom($coerced); + if (!$case instanceof \BackedEnum) { + throw new ConversionFailed(self::enumMessage($enum)); + } + + return $case; + } + + /** + * @param class-string<\BackedEnum> $enum + * @return list + */ + public static function enumValues(string $enum): array + { + $values = []; + foreach ($enum::cases() as $case) { + $values[] = $case->value; + } + + return $values; + } + + /** + * @param class-string<\BackedEnum> $enum + */ + public static function enumMessage(string $enum): string + { + return 'Value must be one of: ' . implode(', ', self::enumValues($enum)); + } + + private static function canonicalInteger(string $value): string + { + $negative = str_starts_with($value, '-'); + $digits = ltrim(ltrim($value, '+-'), '0'); + if ($digits === '') { + $digits = '0'; + } + if ($negative && $digits !== '0') { + return '-' . $digits; + } + + return $digits; + } +} diff --git a/src/Input/SchemaBuilder.php b/src/Input/SchemaBuilder.php new file mode 100644 index 000000000..159a5b5d6 --- /dev/null +++ b/src/Input/SchemaBuilder.php @@ -0,0 +1,154 @@ +hasDefault && $field->default !== null && ($field->casterClass === null || is_scalar($field->default)); + } + + /** + * @return array + */ + public static function build(Field $field, bool $nullOnWire): array + { + if ($field->casterSchema !== null) { + $schema = $field->casterSchema; + } elseif ($field->item instanceof Field) { + $schema = ['type' => 'array', 'items' => self::build($field->item, $nullOnWire)]; + } elseif ($field->children !== []) { + $schema = self::object($field->children); + } elseif ($field->enumClass !== null) { + $schema = ['type' => $field->enumInt ? 'integer' : 'string', 'enum' => $field->enumValues]; + } elseif ($field->typeName === FileUpload::class) { + $schema = ['type' => 'string', 'format' => 'binary']; + } elseif ($field->typeName === \DateTimeImmutable::class) { + $schema = ['type' => 'string', 'format' => 'date-time']; + } else { + $schema = ['type' => self::scalarType($field->typeName)]; + } + + if ($field->casterSchema === null) { + foreach ($field->constraints as $constraint) { + if ($constraint instanceof Range) { + if ($constraint->min !== null) { + $schema['minimum'] = $constraint->min; + } + if ($constraint->max !== null) { + $schema['maximum'] = $constraint->max; + } + } elseif ($constraint instanceof Length && $field->typeName === 'array') { + if ($constraint->min !== null) { + $schema['minItems'] = $constraint->min; + } + if ($constraint->max !== null) { + $schema['maxItems'] = $constraint->max; + } + } elseif ($constraint instanceof Length) { + if ($constraint->min !== null) { + $schema['minLength'] = $constraint->min; + } + if ($constraint->max !== null) { + $schema['maxLength'] = $constraint->max; + } + } elseif ($constraint instanceof Pattern) { + // `pattern` is ECMA 262 for every validator that reads the document, so it only carries a regex that means the same there + $expression = $constraint->expression(); + $schema[$expression === null ? 'x-pattern' : 'pattern'] = $expression ?? $constraint->pattern; + } elseif ($constraint instanceof Email) { + $schema['format'] = 'email'; + } + } + } + + // null is a JSON value; a query string, a path segment or a header cannot carry it (absent is not null) + if ($field->nullable && $nullOnWire) { + $schema['nullable'] = true; + if (isset($schema['enum']) && is_array($schema['enum'])) { + // OpenAPI 3.0.3: nullable alone does not allow null in an enum, null has to be listed + $schema['enum'][] = null; + } + } + if (self::documentsDefault($field)) { + $schema['default'] = self::wire($field->default); + } + if ($field->examples !== []) { + $examples = $field->examples; + $schema['example'] = self::wire(reset($examples)); + } + + return $schema; + } + + /** + * @param list $fields + * @return array + */ + public static function object(array $fields): array + { + $properties = []; + $required = []; + foreach ($fields as $field) { + $properties[$field->externalName] = self::build($field, true); + if ($field->description !== null && $field->description !== '') { + $properties[$field->externalName]['description'] = $field->description; + } + if ($field->required()) { + $required[] = $field->externalName; + } + } + + $schema = ['type' => 'object', 'properties' => $properties]; + if ($required !== []) { + $schema['required'] = $required; + } + + return $schema; + } + + public static function wire(mixed $value): mixed + { + if ($value instanceof \BackedEnum) { + return $value->value; + } + if ($value instanceof \DateTimeInterface) { + return $value->format(\DateTimeInterface::ATOM); + } + if (is_array($value)) { + $wired = []; + foreach ($value as $key => $item) { + $wired[$key] = self::wire($item); + } + + return $wired; + } + + return $value; + } + + private static function scalarType(string $type): string + { + return match ($type) { + 'int' => 'integer', + 'float' => 'number', + 'bool' => 'boolean', + default => 'string', + }; + } +} diff --git a/src/Input/Source.php b/src/Input/Source.php new file mode 100644 index 000000000..ca7523ce2 --- /dev/null +++ b/src/Input/Source.php @@ -0,0 +1,17 @@ +separator === '') { + throw new \InvalidArgumentException("Split separator must not be empty. Use for example #[Cast(Split::class, ',')]"); + } + } + + /** + * @return list + */ + #[\Override] + public function cast(mixed $value): array + { + if (!is_string($value)) { + throw new CastException(sprintf('Value must be a string that can be split on %s', $this->separator)); + } + + return explode($this->separator, $value); + } + + /** + * @return array{type: string, example: string} + */ + #[\Override] + public function openApiSchema(): array + { + return ['type' => 'string', 'example' => implode($this->separator, ['red', 'green', 'blue'])]; + } +} diff --git a/src/Input/TypeName.php b/src/Input/TypeName.php new file mode 100644 index 000000000..29e4f4a72 --- /dev/null +++ b/src/Input/TypeName.php @@ -0,0 +1,131 @@ + $scope */ + public static function resolve(string $name, \ReflectionClass $scope): string + { + $name = trim($name); + $bare = ltrim($name, '\\'); + if (in_array(strtolower($bare), self::BUILTIN, true)) { + return strtolower($bare); + } + if (str_starts_with($name, '\\')) { + return $bare; + } + + $imports = self::imports($scope); + $first = explode('\\', $name, 2); + $imported = $imports[strtolower($first[0])] ?? null; + if ($imported !== null) { + return isset($first[1]) ? $imported . '\\' . $first[1] : $imported; + } + + $namespace = $scope->getNamespaceName(); + return $namespace === '' ? $name : $namespace . '\\' . $name; + } + + /** + * Class imports of the namespace block of the class, keyed by the lowercase alias. + * + * @param \ReflectionClass<*> $scope + * @return array + */ + private static function imports(\ReflectionClass $scope): array + { + $file = $scope->getFileName(); + $code = is_string($file) && is_file($file) ? file_get_contents($file) : ''; + + return self::importsOf(is_string($code) ? $code : '', $scope->getNamespaceName()); + } + + /** + * Top-level class imports of one namespace block in PHP code, keyed by the lowercase alias. + * + * @internal + * @return array + */ + public static function importsOf(string $code, string $namespace): array + { + $tokens = array_values(array_filter(\PhpToken::tokenize($code), static fn (\PhpToken $token): bool => !$token->isIgnorable())); + $imports = []; + $current = ''; + // braces opened inside the current namespace; a `use` at 0 is an import + $level = 0; + $count = count($tokens); + for ($i = 0; $i < $count; $i++) { + $token = $tokens[$i]; + if ($token->text === '}') { + $level--; + } elseif ($token->text === '{' || $token->is(T_DOLLAR_OPEN_CURLY_BRACES)) { + $level++; + } elseif ($token->is(T_NAMESPACE)) { + $current = ''; + for ($i++; $tokens[$i]->text !== ';' && $tokens[$i]->text !== '{'; $i++) { + $current = $tokens[$i]->text; + } + $level = 0; + } elseif ($token->is(T_USE) && $level === 0) { + $i = self::useStatement($tokens, $i, $current === $namespace, $imports); + } + } + + return $imports; + } + + /** + * Reads one `use` statement from its `use` token and returns the index of its `;`. + * + * @param list<\PhpToken> $tokens + * @param array $imports + */ + private static function useStatement(array $tokens, int $i, bool $keep, array &$imports): int + { + $prefix = ''; + $name = ''; + $alias = ''; + $skip = false; + for (; $tokens[$i]->text !== ';'; $i++) { + $token = $tokens[$i]; + if ($token->text === '{') { + $prefix = $name . '\\'; + $name = ''; + } elseif ($token->is([T_FUNCTION, T_CONST])) { + $skip = true; + } elseif ($token->text === ',' || $token->text === '}') { + self::remember($imports, $keep && !$skip, $prefix, $name, $alias); + [$name, $alias, $skip] = ['', '', $skip && $prefix === '']; + } elseif ($token->is(T_AS)) { + $alias = $tokens[++$i]->text; + } elseif (!$token->is(T_NS_SEPARATOR)) { + $name = ltrim($token->text, '\\'); + } + } + self::remember($imports, $keep && !$skip, $prefix, $name, $alias); + + return $i; + } + + /** + * @param array $imports + */ + private static function remember(array &$imports, bool $keep, string $prefix, string $name, string $alias): void + { + if (!$keep || $name === '') { + return; + } + $segments = explode('\\', $name); + $imports[strtolower($alias !== '' ? $alias : end($segments))] = $prefix . $name; + } +} diff --git a/src/Input/UnixTimestamp.php b/src/Input/UnixTimestamp.php new file mode 100644 index 000000000..bc974c241 --- /dev/null +++ b/src/Input/UnixTimestamp.php @@ -0,0 +1,32 @@ + 'integer', 'example' => 1798185600]; + } +} diff --git a/src/Input/UnsupportedMediaTypeException.php b/src/Input/UnsupportedMediaTypeException.php new file mode 100644 index 000000000..65f938117 --- /dev/null +++ b/src/Input/UnsupportedMediaTypeException.php @@ -0,0 +1,38 @@ + $accepted + */ + private function __construct(string $detail, public readonly array $accepted) + { + parent::__construct($detail); + } + + /** + * @param list $accepted + */ + public static function missing(array $accepted): self + { + return new self('Content-Type is missing. Use one of: ' . implode(', ', $accepted) . '.', $accepted); + } + + /** + * @param list $accepted + */ + public static function received(string $type, array $accepted): self + { + return new self( + "Content-Type '" . $type . "' is not supported for this endpoint. Use one of: " . implode(', ', $accepted) . '.', + $accepted, + ); + } +} diff --git a/src/Input/ValueExport.php b/src/Input/ValueExport.php new file mode 100644 index 000000000..7919e7f5a --- /dev/null +++ b/src/Input/ValueExport.php @@ -0,0 +1,58 @@ + 'enum', 'class' => $value::class, 'value' => $value->value]; + } + if (!is_array($value)) { + if (is_object($value)) { + throw new \LogicException(sprintf( + 'A %s cannot be stored in the compiled container. Use null, a scalar, an array or a backed enum as a DTO default.', + $value::class, + )); + } + + return $value; + } + + $exported = []; + foreach ($value as $key => $item) { + $exported[$key] = self::export($item); + } + + return $exported; + } + + public static function import(mixed $value): mixed + { + if (!is_array($value)) { + return $value; + } + if (($value['__netteApi'] ?? null) === 'enum' && is_string($value['class'] ?? null) && (is_int($value['value'] ?? null) || is_string($value['value'] ?? null))) { + $enum = $value['class']; + $case = $enum::tryFrom($value['value']); + if (!$case instanceof \BackedEnum) { + throw new \LogicException(sprintf("Cannot restore the default of backed enum %s from '%s'.", $enum, (string) $value['value'])); + } + + return $case; + } + + $imported = []; + foreach ($value as $key => $item) { + $imported[$key] = self::import($item); + } + + return $imported; + } +} diff --git a/src/Link/ApiLink.php b/src/Link/ApiLink.php index 6d52a3390..22e8ff49c 100644 --- a/src/Link/ApiLink.php +++ b/src/Link/ApiLink.php @@ -20,16 +20,55 @@ public function __construct(private readonly LinkGenerator $linkGenerator) /** * Create link to specified api endpoint * + * A {name} segment of a URL template stays literal, which is the OpenAPI path template. + * * @param array $params * @throws InvalidLinkException */ public function link(EndpointInterface $endpoint, $params = []): string { + $package = $endpoint->getPackage(); + $action = $endpoint->getApiAction(); + if (str_contains($package, '{') || str_contains($package, '/') || ($action !== null && (str_contains($action, '{') || str_contains($action, '/')))) { + return $this->templateLink($endpoint, $params); + } + $params = array_merge([ 'version' => $endpoint->getVersion(), - 'package' => $endpoint->getPackage(), - 'apiAction' => $endpoint->getApiAction(), + 'package' => $package, + 'apiAction' => $action, ], $params); return $this->linkGenerator->link('Api:Api:default', $params) ?: ''; } + + /** + * Keeps {name} segments literal. A normal route parameter would encode the slash and the braces. + * + * @param array $params + */ + private function templateLink(EndpointInterface $endpoint, array $params): string + { + $sample = $this->linkGenerator->link('Api:Api:default', [ + 'version' => $endpoint->getVersion(), + 'package' => 'package', + 'apiAction' => 'action', + ]) ?: ''; + $needle = sprintf('/v%s/package/action', $endpoint->getVersion()); + $position = strpos($sample, $needle); + if ($position === false) { + throw new InvalidLinkException(sprintf( + "Cannot build a link for %s %s. The router mask must contain version, package and apiAction, for example '/api/v/[/]'.", + $endpoint->getMethod(), + $endpoint->getUrl(), + )); + } + + $url = substr($sample, 0, $position) . '/' . $endpoint->getUrl(); + unset($params['version'], $params['package'], $params['apiAction']); + if ($params !== []) { + $url = sprintf('%s?%s', $url, http_build_query($params)); + } + + return $url; + } } diff --git a/src/Misc/ConsoleRequest.php b/src/Misc/ConsoleRequest.php index d370f27da..41b753ff1 100644 --- a/src/Misc/ConsoleRequest.php +++ b/src/Misc/ConsoleRequest.php @@ -7,8 +7,10 @@ use Nette\Http\FileUpload; use Tomaj\NetteApi\EndpointInterface; use Tomaj\NetteApi\Handlers\ApiHandlerInterface; +use Tomaj\NetteApi\Input\MediaTypes; use Tomaj\NetteApi\Link\ApiLink; use Tomaj\NetteApi\Params\InputParam; +use Tomaj\NetteApi\Params\MappedInputParam; use Tomaj\NetteApi\Params\ParamInterface; final readonly class ConsoleRequest @@ -27,7 +29,17 @@ public function __construct(private ApiHandlerInterface $handler, private ?Endpo */ public function makeRequest(string $url, string $method, array $values, array $additionalValues = [], ?string $token = null): ConsoleResponse { - [$postFields, $getFields, $cookieFields, $rawPost, $putFields] = $this->processValues($values); + [$postFields, $getFields, $cookieFields, $rawPost, $putFields, $pathFields, $headerFields, $bodyFields] = $this->processValues($values); + + foreach ($pathFields as $name => $value) { + if (trim($value) === '') { + // the request is not sent: the URL would have an empty segment and the server could only answer 404 + $response = new ConsoleResponse($url, $method, [], [], [], [], null); + $response->logError(0, sprintf("The path value '%s' is empty. Fill it in and send the request again.", $name), 0); + + return $response; + } + } $postFields = array_merge($postFields, $additionalValues['postFields'] ?? []); $getFields = array_merge($getFields, $additionalValues['getFields'] ?? []); @@ -39,8 +51,12 @@ public function makeRequest(string $url, string $method, array $values, array $a $putFields = $this->normalizeValues($putFields); if ($this->endpoint && $this->apiLink) { + // link() builds the URL, so an overridden link() still decides it; the path values go into the {name} segments afterwards $url = $this->apiLink->link($this->endpoint, $getFields); - } elseif ($getFields !== []) { + } + $url = self::substitutePath($url, $pathFields); + + if (!($this->endpoint && $this->apiLink) && $getFields !== []) { $parts = []; foreach ($getFields as $key => $value) { $parts[] = sprintf('%s=%s', $key, TypeHelper::toString($value)); @@ -61,6 +77,25 @@ public function makeRequest(string $url, string $method, array $values, array $a $putRawPost = implode('&', $parts); } + $headers = $additionalValues['headers'] ?? []; + foreach ($headerFields as $name => $value) { + $headers[] = sprintf('%s: %s', $name, str_replace(["\r", "\n"], '', TypeHelper::toString($value))); + } + + if ($bodyFields !== []) { + $mediaType = $postFields !== [] ? MediaTypes::MULTIPART : $this->bodyMediaType(); + if ($mediaType === MediaTypes::MULTIPART) { + // an array of fields makes curl send multipart/form-data + $postFields = array_merge($postFields, self::flatten($bodyFields)); + } elseif ($mediaType === MediaTypes::FORM) { + $rawPost = http_build_query(self::flatten($bodyFields)); + $headers[] = 'Content-Type: ' . MediaTypes::FORM; + } else { + $rawPost = json_encode($bodyFields, JSON_THROW_ON_ERROR | JSON_INVALID_UTF8_SUBSTITUTE | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION); + $headers[] = 'Content-Type: ' . MediaTypes::JSON; + } + } + $startTime = microtime(true); $curl = curl_init(); @@ -81,7 +116,6 @@ public function makeRequest(string $url, string $method, array $values, array $a curl_setopt($curl, CURLOPT_POSTFIELDS, count($postFields) ? $postFields : ($rawPost ?: $putRawPost)); } - $headers = $additionalValues['headers'] ?? []; if ($cookieFields !== []) { $parts = []; foreach ($cookieFields as $key => $value) { @@ -143,7 +177,7 @@ public function makeRequest(string $url, string $method, array $values, array $a * Process given values to POST and GET fields * * @param array $values - * @return array{0:array,1:array,2:array,3:string|null,4:array} + * @return array{0:array,1:array,2:array,3:string|null,4:array,5:array,6:array,7:array} */ private function processValues(array $values): array { @@ -154,6 +188,9 @@ private function processValues(array $values): array $getFields = []; $putFields = []; $cookieFields = []; + $pathFields = []; + $headerFields = []; + $bodyFields = []; foreach ($values as $key => $value) { if (str_contains($key, '___')) { @@ -167,7 +204,19 @@ private function processValues(array $values): array continue; } - if ($param->isMulti()) { + $type = $param->getType(); + if ($type === InputParam::TYPE_PATH) { + $pathFields[$key] = TypeHelper::toString($valueData); + } elseif ($type === InputParam::TYPE_HEADER) { + $headerFields[$key] = $valueData; + } elseif ($type === InputParam::TYPE_BODY) { + $schema = $param instanceof InputParam ? $param->getOpenApiSchema() : null; + if ($param->isMulti()) { + $bodyFields[$key] = $this->appendValue($bodyFields[$key] ?? null, self::bodyValue($valueData, $schema['items'] ?? null)); + } else { + $bodyFields[$key] = self::bodyValue($valueData, $schema); + } + } elseif ($param->isMulti()) { if (in_array($param->getType(), [InputParam::TYPE_POST, InputParam::TYPE_FILE], true)) { $postFields[$key] = $this->appendValue($postFields[$key] ?? null, $valueData); } elseif ($param->getType() === InputParam::TYPE_PUT) { @@ -191,7 +240,109 @@ private function processValues(array $values): array } } - return [$postFields, $getFields, $cookieFields, $rawPost, $putFields]; + return [$postFields, $getFields, $cookieFields, $rawPost, $putFields, $pathFields, $headerFields, $bodyFields]; + } + + /** + * A typed field that is left blank in the console is not sent. The server does not turn an empty string into + * null or an empty list item, so a blank number, date, enum, nested object or list slot would only be a 400. + * A blank optional text field is not sent either, so the server uses its default. A required text field keeps + * its empty string, so that its length and pattern constraints can be tried. + */ + private static function isBlankSlot(ParamInterface $param, mixed $value): bool + { + if (!$param instanceof MappedInputParam || $param->getType() === InputParam::TYPE_PATH || !is_string($value) || trim($value) !== '') { + return false; + } + + $schema = $param->getOpenApiSchema(); + $plainText = ($schema['type'] ?? null) === 'string' && !isset($schema['format']) && !isset($schema['enum']); + + return $param->getType() === InputParam::TYPE_HEADER || !$plainText || !$param->isRequired(); + } + + /** + * The media type the typed body is sent in: the first one the handler reads that the console can build. + * A handler that restricts itself to a form type with #[Consumes] must not receive JSON. + */ + private function bodyMediaType(): string + { + foreach ($this->handler->params() as $param) { + if (!$param instanceof InputParam) { + continue; + } + foreach ($param->getContentTypes() as $contentType) { + if (in_array($contentType, MediaTypes::ALL, true)) { + return $contentType; + } + } + } + + return MediaTypes::JSON; + } + + /** + * Replaces {name} segments with URL-encoded values. + * + * @param array $pathFields + */ + private static function substitutePath(string $url, array $pathFields): string + { + foreach ($pathFields as $name => $value) { + $url = str_replace('{' . $name . '}', rawurlencode($value), $url); + } + + return $url; + } + + /** + * Console fields are strings. A JSON body needs the declared wire type. + * + * @param mixed $schema OpenAPI schema of the field + */ + private static function bodyValue(mixed $value, mixed $schema): mixed + { + if (!is_string($value) || !is_array($schema)) { + return $value; + } + + $type = $schema['type'] ?? null; + $trimmed = trim($value); + return match (true) { + $type === 'integer' && is_int(filter_var($trimmed, FILTER_VALIDATE_INT)) => (int) $trimmed, + $type === 'number' && is_numeric($trimmed) && is_finite((float) $trimmed) => (float) $trimmed, + $type === 'boolean' && in_array($trimmed, ['true', '1'], true) => true, + $type === 'boolean' && in_array($trimmed, ['false', '0'], true) => false, + // not an associative array: the JSON text {} is an empty object, which the server accepts, and [] is a list + ($type === 'object' || $type === 'array') && json_validate($trimmed) => json_decode($trimmed), + default => $value, + }; + } + + /** + * Nested body values as multipart keys, for example profile[name]. + * + * @param array $values + * @return array + */ + private static function flatten(array $values, string $prefix = ''): array + { + $result = []; + foreach ($values as $key => $value) { + $name = $prefix === '' ? "{$key}" : "{$prefix}[{$key}]"; + if (is_object($value)) { + $value = get_object_vars($value); + } + if (is_array($value)) { + $result += self::flatten($value, $name); + } elseif (is_bool($value)) { + $result[$name] = $value ? '1' : '0'; + } elseif ($value !== null) { + $result[$name] = $value; + } + } + + return $result; } /** @@ -230,7 +381,7 @@ private function processParam(ParamInterface $param, string $key, $value) $valueData = file_get_contents('php://input'); } - return $valueData; + return self::isBlankSlot($param, $valueData) ? null : $valueData; } return null; diff --git a/src/OpenApi/ParameterBuilder.php b/src/OpenApi/ParameterBuilder.php index f70a12663..3841970a5 100644 --- a/src/OpenApi/ParameterBuilder.php +++ b/src/OpenApi/ParameterBuilder.php @@ -21,16 +21,37 @@ public function build(ApiHandlerInterface $handler): array { $parameters = []; foreach ($handler->params() as $param) { - if ($param->getType() !== InputParam::TYPE_GET && $param->getType() !== InputParam::TYPE_COOKIE) { + $in = match ($param->getType()) { + InputParam::TYPE_GET => 'query', + InputParam::TYPE_COOKIE => 'cookie', + InputParam::TYPE_PATH => 'path', + InputParam::TYPE_HEADER => 'header', + default => null, + }; + if ($in === null) { continue; } + $explicitSchema = $param instanceof InputParam ? $param->getOpenApiSchema() : null; $parameter = [ - 'name' => $param->getKey() . ($param->isMulti() ? '[]' : ''), - 'in' => $param->getType() === InputParam::TYPE_GET ? 'query' : 'cookie', - 'required' => $param->isRequired(), + // PHP reads a repeated query value only in the bracket form, for example items[]=1&items[]=2 + 'name' => $param->getKey() . ($param->isMulti() && ($explicitSchema === null || ($explicitSchema['type'] ?? null) === 'array') ? '[]' : ''), + 'in' => $in, + 'required' => $in === 'path' ? true : $param->isRequired(), ]; + if ($explicitSchema !== null) { + $parameter['schema'] = $explicitSchema; + if ($param->getDescription() !== '') { + $parameter['description'] = $param->getDescription(); + } + if ($param->getExamples() !== []) { + $parameter['example'] = $param->getExample(); + } + $parameters[] = $parameter; + continue; + } + $schema = [ 'type' => $param->isMulti() ? 'array' : 'string', ]; diff --git a/src/OpenApi/RequestBodyBuilder.php b/src/OpenApi/RequestBodyBuilder.php index 27b157b1e..d32bff4ef 100644 --- a/src/OpenApi/RequestBodyBuilder.php +++ b/src/OpenApi/RequestBodyBuilder.php @@ -28,7 +28,30 @@ public function build(ApiHandlerInterface $handler, SchemaRegistry $schemaRegist $filesInBody = false; $requestBodyExample = []; $result = []; + $typedProperties = []; + $typedRequired = []; + $typedTypes = []; + $typedAnyRequired = false; + $typedFiles = []; foreach ($handler->params() as $param) { + if ($param instanceof InputParam && $param->getOpenApiSchema() !== null && ($param->getType() === InputParam::TYPE_BODY || $param->getType() === InputParam::TYPE_FILE)) { + $schema = $param->getOpenApiSchema(); + if ($param->getDescription() !== '' && !isset($schema['description'])) { + $schema['description'] = $param->getDescription(); + } + $typedProperties[$param->getKey()] = $schema; + if ($param->getType() === InputParam::TYPE_FILE) { + $typedFiles[] = $param->getKey(); + } + if ($param->isRequired()) { + $typedRequired[] = $param->getKey(); + $typedAnyRequired = true; + } + if ($param->getContentTypes() !== []) { + $typedTypes = $param->getContentTypes(); + } + continue; + } if ($param instanceof JsonInputParam) { $schema = TypeHelper::toArray(json_decode($param->getSchema(), true)); if (!empty($examples = $param->getExamples())) { @@ -145,6 +168,34 @@ public function build(ApiHandlerInterface $handler, SchemaRegistry $schemaRegist ]; } + if ($typedProperties !== []) { + $typedSchema = [ + 'type' => 'object', + 'properties' => $typedProperties, + ]; + if ($typedRequired !== []) { + $typedSchema['required'] = $typedRequired; + } + // files can only be sent as multipart/form-data, so the other media types do not list them + $withoutFiles = ['type' => 'object']; + $propertiesWithoutFiles = array_diff_key($typedProperties, array_flip($typedFiles)); + if ($propertiesWithoutFiles !== []) { + $withoutFiles['properties'] = $propertiesWithoutFiles; + } + // the other media types are advertised only when no file is required, so `typedRequired` has none + if ($typedRequired !== []) { + $withoutFiles['required'] = $typedRequired; + } + $result['required'] = $typedAnyRequired; + // a required file cannot be sent as JSON, so such a request could only be answered with 400: only multipart is advertised + $advertised = array_intersect($typedRequired, $typedFiles) !== [] + ? ['multipart/form-data'] + : ($typedTypes === [] ? ['application/json', 'application/x-www-form-urlencoded'] : $typedTypes); + foreach ($advertised as $contentType) { + $result['content'][$contentType] = ['schema' => $contentType === 'multipart/form-data' ? $typedSchema : $withoutFiles]; + } + } + return $result ?: null; } } diff --git a/src/OpenApi/ResponseBuilder.php b/src/OpenApi/ResponseBuilder.php index 6ae8c4dd5..a640658f5 100644 --- a/src/OpenApi/ResponseBuilder.php +++ b/src/OpenApi/ResponseBuilder.php @@ -11,6 +11,8 @@ use Tomaj\NetteApi\Misc\TypeHelper; use Tomaj\NetteApi\Output\JsonOutput; use Tomaj\NetteApi\Output\RedirectOutput; +use Tomaj\NetteApi\Params\MappedInputParam; +use Tomaj\NetteApi\Params\ParamInterface; /** * Creates operation responses: default error responses and responses from handler outputs @@ -98,6 +100,11 @@ public function build(ApiHandlerInterface $handler, ApiAuthorizationInterface $a $responses[IResponse::S400_BAD_REQUEST] = $this->errorResponse('Bad request', 'ErrorWrongInput'); } + if (self::readsTypedBody($handler)) { + // a typed handler answers 415 for a body in a media type it does not read, see requestBody.content + $responses[IResponse::S415_UnsupportedMediaType] = $this->unsupportedMediaTypeResponse(); + } + if (!$authorization instanceof NoAuthorization) { $responses[IResponse::S401_Unauthorized] = $this->errorResponse('Operation forbidden', 'ErrorUnauthorized'); } @@ -150,6 +157,11 @@ public function build(ApiHandlerInterface $handler, ApiAuthorizationInterface $a return $responses; } + private static function readsTypedBody(ApiHandlerInterface $handler): bool + { + return array_any($handler->params(), static fn (ParamInterface $param): bool => $param instanceof MappedInputParam && $param->getContentTypes() !== []); + } + /** * RFC 9457 problem details object * @@ -208,6 +220,36 @@ private function errorResponse(string $description, string $legacySchema): array ]; } + /** + * The 415 answer of a typed body. Its `detail` is a sentence (shown only when error details are on), + * unlike the field map of a 400, so it has its own inline schema. + * + * @return array + */ + private function unsupportedMediaTypeResponse(): array + { + if ($this->problemDetails) { + return $this->errorResponse('Unsupported media type', 'ErrorWrongInput'); + } + + return [ + 'description' => 'Unsupported media type', + 'content' => [ + self::JSON_CONTENT_TYPE => [ + 'schema' => [ + 'type' => 'object', + 'properties' => [ + 'status' => ['type' => 'string', 'enum' => ['error']], + 'message' => ['type' => 'string'], + 'detail' => ['type' => 'string', 'description' => 'Which media types the endpoint reads. Sent only when error details are on.'], + ], + 'required' => ['status', 'message'], + ], + ], + ], + ]; + } + /** * Adds another schema to an already defined JSON response, wrapping the existing schema to `oneOf`. * diff --git a/src/Params/BodyInputParam.php b/src/Params/BodyInputParam.php new file mode 100644 index 000000000..c03442ff2 --- /dev/null +++ b/src/Params/BodyInputParam.php @@ -0,0 +1,51 @@ +getKey()] ?? null; + if ($value === null && MediaTypes::normalize(is_string($_SERVER['CONTENT_TYPE'] ?? null) ? $_SERVER['CONTENT_TYPE'] : null) === MediaTypes::JSON) { + $decoded = self::json(); + if (is_array($decoded)) { + $value = $decoded[$this->getKey()] ?? null; + } + } + $value ??= $this->default; + + return new InputValidator()->transformType($value, $this->valueType, $this->isRequired()); + } + + /** + * @return array|null + */ + private static function json(): ?array + { + $raw = RequestInput::rawContents(); + $raw = is_string($raw) ? $raw : ''; + $decoded = json_decode($raw); + if (json_last_error() !== JSON_ERROR_NONE || !$decoded instanceof \stdClass) { + return null; + } + $body = []; + foreach (get_object_vars($decoded) as $key => $value) { + $body[$key] = $value; + } + + return $body; + } +} diff --git a/src/Params/HeaderBag.php b/src/Params/HeaderBag.php new file mode 100644 index 000000000..49da74153 --- /dev/null +++ b/src/Params/HeaderBag.php @@ -0,0 +1,48 @@ + + */ + private static function all(): array + { + $headers = []; + foreach ($_SERVER as $key => $value) { + if (!is_string($key) || !str_starts_with($key, 'HTTP_')) { + continue; + } + $headers[strtolower(str_replace('_', '-', substr($key, 5)))] = $value; + } + // Apache with CGI/FastCGI hands the Authorization header over as REDIRECT_HTTP_AUTHORIZATION after a rewrite + if (!array_key_exists('authorization', $headers) && isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) { + $headers['authorization'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION']; + } + if (array_key_exists('CONTENT_TYPE', $_SERVER)) { + $headers['content-type'] = $_SERVER['CONTENT_TYPE']; + } + if (array_key_exists('CONTENT_LENGTH', $_SERVER)) { + $headers['content-length'] = $_SERVER['CONTENT_LENGTH']; + } + + return $headers; + } +} diff --git a/src/Params/HeaderInputParam.php b/src/Params/HeaderInputParam.php new file mode 100644 index 000000000..56d6b8e19 --- /dev/null +++ b/src/Params/HeaderInputParam.php @@ -0,0 +1,22 @@ +getKey()) ? HeaderBag::get($this->getKey()) : $this->default; + return new InputValidator()->transformType($value, $this->valueType, $this->isRequired()); + } +} diff --git a/src/Params/InputParam.php b/src/Params/InputParam.php index e4414cf43..8ccc643e8 100644 --- a/src/Params/InputParam.php +++ b/src/Params/InputParam.php @@ -22,6 +22,9 @@ abstract class InputParam implements ParamInterface public const TYPE_COOKIE = 'COOKIE'; public const TYPE_POST_RAW = 'POST_RAW'; public const TYPE_POST_JSON = 'POST_JSON'; + public const TYPE_PATH = 'PATH'; + public const TYPE_HEADER = 'HEADER'; + public const TYPE_BODY = 'BODY'; public const OPTIONAL = false; public const REQUIRED = true; @@ -54,6 +57,12 @@ abstract class InputParam implements ParamInterface /** @var string|null */ protected $valueType; + /** @var array|null */ + private ?array $openApiSchema = null; + + /** @var list */ + private array $contentTypes = []; + /** * @param InputType|string|null $valueType expected value type, see InputType */ @@ -173,6 +182,44 @@ public function addExample(string $name, $example): self return $this; } + /** + * OpenAPI schema used instead of the default string schema. Null keeps the existing schema. + * + * @param array $schema + */ + public function setOpenApiSchema(array $schema): self + { + $this->openApiSchema = $schema; + return $this; + } + + /** + * @return array|null + */ + public function getOpenApiSchema(): ?array + { + return $this->openApiSchema; + } + + /** + * Media types of a body or file parameter. Empty means the historical single form content type. + * + * @param list $contentTypes + */ + public function setContentTypes(array $contentTypes): self + { + $this->contentTypes = $contentTypes; + return $this; + } + + /** + * @return list + */ + public function getContentTypes(): array + { + return $this->contentTypes; + } + #[\Override] public function getExample(): mixed { @@ -195,7 +242,7 @@ public function getExamples(): array #[\Override] public function updateConsoleForm(Form $form): void { - $count = $this->isMulti() ? self::DEFAULT_MULTI_INPUT_COUNT : 1; // TODO moznost nastavit kolko inputov sa ma vygenerovat v konzole, default moze byt 5 + $count = $this->isMulti() ? self::DEFAULT_MULTI_INPUT_COUNT : 1; for ($i = 0; $i < $count; $i++) { $key = $this->getKey(); if ($this->isMulti()) { diff --git a/src/Params/MappedInputParam.php b/src/Params/MappedInputParam.php new file mode 100644 index 000000000..27d2a9736 --- /dev/null +++ b/src/Params/MappedInputParam.php @@ -0,0 +1,87 @@ +externalName); + $this->type = match ($field->source) { + Source::Query => self::TYPE_GET, + Source::Path => self::TYPE_PATH, + Source::Header => self::TYPE_HEADER, + Source::Body => self::TYPE_BODY, + Source::File => self::TYPE_FILE, + }; + if ($field->required()) { + $this->setRequired(); + } + if ($field->description !== null && $field->description !== '') { + $this->setDescription($field->description); + } + foreach ($field->examples as $name => $example) { + $this->addExample($name, $example); + } + if (SchemaBuilder::documentsDefault($field)) { + $this->setDefault(SchemaBuilder::wire($field->default)); + } + if ($field->enumValues !== []) { + $this->setAvailableValues($field->enumValues); + } + // a caster reads the whole wire value (for example Split reads "a,b"), so it is one input, not a list of inputs + if ($field->listItem !== null && $field->casterClass === null) { + $this->setMulti(); + } + $this->setOpenApiSchema(SchemaBuilder::build($field, $field->readsBody())); + if ($field->readsBody()) { + $this->setContentTypes($metadata->contentTypes); + } + } + + #[\Override] + public function validate(): ValidationResultInterface + { + $errors = $this->mapper->errors($this->field); + if ($errors === []) { + return new ValidationResult(ValidationResult::STATUS_OK); + } + + return new FieldErrors($errors); + } + + #[\Override] + public function getValue(): mixed + { + return $this->mapper->value($this->field); + } + + #[\Override] + protected function addFormInput(Form $form, string $key): BaseControl + { + if ($this->getType() === self::TYPE_FILE) { + return $form->addUpload($key, $this->getParamLabel()); + } + + return parent::addFormInput($form, $key); + } +} diff --git a/src/Params/ParamType.php b/src/Params/ParamType.php index 0b37852ed..12e91ef20 100644 --- a/src/Params/ParamType.php +++ b/src/Params/ParamType.php @@ -16,4 +16,7 @@ enum ParamType: string case Cookie = InputParam::TYPE_COOKIE; case PostRaw = InputParam::TYPE_POST_RAW; case PostJson = InputParam::TYPE_POST_JSON; + case Path = InputParam::TYPE_PATH; + case Header = InputParam::TYPE_HEADER; + case Body = InputParam::TYPE_BODY; } diff --git a/src/Params/ParamsProcessor.php b/src/Params/ParamsProcessor.php index 20dccbdd0..a2b07ede9 100644 --- a/src/Params/ParamsProcessor.php +++ b/src/Params/ParamsProcessor.php @@ -4,6 +4,8 @@ namespace Tomaj\NetteApi\Params; +use Tomaj\NetteApi\ValidationResult\FieldErrors; + final class ParamsProcessor { /** @var array */ @@ -21,6 +23,12 @@ public function isError(): bool foreach ($this->params as $param) { $validationResult = $param->validate(); if (!$validationResult->isOk()) { + if ($validationResult instanceof FieldErrors) { + foreach ($validationResult->fieldErrors() as $path => $messages) { + $this->errors[$path] = $messages; + } + continue; + } $this->errors[$param->getKey()] = $validationResult->getErrors(); } } diff --git a/src/Params/PathInputParam.php b/src/Params/PathInputParam.php new file mode 100644 index 000000000..fd5387019 --- /dev/null +++ b/src/Params/PathInputParam.php @@ -0,0 +1,32 @@ +setRequired(); + } + + #[\Override] + public function getValue(): mixed + { + $value = PathValues::has($this->getKey()) ? PathValues::get($this->getKey()) : $this->default; + return new InputValidator()->transformType($value, $this->valueType, $this->isRequired()); + } +} diff --git a/src/Params/PathValues.php b/src/Params/PathValues.php new file mode 100644 index 000000000..d34408f2d --- /dev/null +++ b/src/Params/PathValues.php @@ -0,0 +1,37 @@ + */ + private static array $values = []; + + public static function reset(): void + { + self::$values = []; + } + + /** + * @param array $values + */ + public static function set(array $values): void + { + self::$values = $values; + } + + public static function has(string $name): bool + { + return array_key_exists($name, self::$values); + } + + public static function get(string $name): ?string + { + return self::$values[$name] ?? null; + } +} diff --git a/src/Presenters/ApiPresenter.php b/src/Presenters/ApiPresenter.php index 708caa196..13683c230 100644 --- a/src/Presenters/ApiPresenter.php +++ b/src/Presenters/ApiPresenter.php @@ -9,6 +9,7 @@ use Nette\Application\Request; use Nette\DI\Attributes\Inject; use Nette\DI\Container; +use Nette\Http\IRequest; use Nette\Http\Response; use Throwable; use Tracy\Debugger; @@ -34,6 +35,9 @@ use Tomaj\NetteApi\Misc\IpDetectorInterface; use Tomaj\NetteApi\Misc\TypeHelper; use Tomaj\NetteApi\Output\Configurator\ConfiguratorInterface; +use Tomaj\NetteApi\Input\RequestInput; +use Tomaj\NetteApi\Params\PathValues; +use Tomaj\NetteApi\Input\UnsupportedMediaTypeException; use Tomaj\NetteApi\Params\ParamsProcessor; use Tomaj\NetteApi\RateLimit\RateLimitContext; use Tomaj\NetteApi\RateLimit\RateLimiterInterface; @@ -289,6 +293,8 @@ private function logMasking(): LogMasking #[\Override] public function run(Request $request): IResponse { + RequestInput::reset(); + PathValues::reset(); $start = microtime(true); $this->sendCorsHeaders(); @@ -315,8 +321,18 @@ public function run(Request $request): IResponse return $rateLimitResponse; } - $paramsProcessor = new ParamsProcessor($handler->params()); - $params = $paramsProcessor->isError() ? [] : $paramsProcessor->getValues(); + // a body in a media type the typed handler does not accept is answered with 415 after the authorization, + // so a client without access learns nothing about the endpoint + $unsupportedMediaType = ''; + $paramsProcessor = null; + $params = []; + try { + $paramsProcessor = new ParamsProcessor($handler->params()); + $params = $paramsProcessor->isError() ? [] : $paramsProcessor->getValues(); + } catch (UnsupportedMediaTypeException $exception) { + $unsupportedMediaType = $exception->getMessage(); + $paramsProcessor = null; + } $authResponse = $this->checkAuth($authorization, $params); if ($authResponse !== null) { @@ -335,6 +351,13 @@ public function run(Request $request): IResponse return $rateLimitResponse; } + if ($paramsProcessor === null) { + $response = $this->errorHandler->handleUnsupportedMediaType($unsupportedMediaType); + $this->logResponse($request, $response->getCode(), $start, $ip); + $this->response->setCode($response->getCode()); + return $response; + } + if ($paramsProcessor->isError()) { $response = $this->errorHandler->handleInputParams($paramsProcessor->getErrors()); $this->response->setCode($response->getCode()); @@ -371,32 +394,51 @@ public function run(Request $request): IResponse $code = $response->getCode(); } - $end = microtime(true); - - if ($this->context->findByType(ApiLoggerInterface::class)) { - /** @var ApiLoggerInterface $apiLogger */ - $apiLogger = $this->context->getByType(ApiLoggerInterface::class); - try { - $this->logRequest($request, $apiLogger, $code, $end - $start, $ip); - } catch (Throwable $throwable) { - // the handler has run, a broken logger or IP detector must not lose its response, so the error is only logged - self::logError($throwable); - } - } + $this->logResponse($request, $code, $start, $ip); // output to nette $this->response->setCode($code); return $response; } + private function logResponse(Request $request, int $code, float $start, \Closure $ip): void + { + $end = microtime(true); + if (!$this->context->findByType(ApiLoggerInterface::class)) { + return; + } + /** @var ApiLoggerInterface $apiLogger */ + $apiLogger = $this->context->getByType(ApiLoggerInterface::class); + try { + $this->logRequest($request, $apiLogger, $code, $end - $start, $ip); + } catch (Throwable $throwable) { + // the response is ready, a broken logger or IP detector must not lose it, so the error is only logged + self::logError($throwable); + } + } + private function getApi(Request $request): Api { - return $this->apiDecider->getApi( - $request->getMethod() ?? '', - TypeHelper::toString($request->getParameter('version')), - TypeHelper::toString($request->getParameter('package')), - $request->getParameter('apiAction') === null ? null : TypeHelper::toString($request->getParameter('apiAction')), - ); + $method = $request->getMethod() ?? ''; + $version = TypeHelper::toString($request->getParameter('version')); + $package = TypeHelper::toString($request->getParameter('package')); + $apiAction = $request->getParameter('apiAction') === null ? null : TypeHelper::toString($request->getParameter('apiAction')); + + $api = $this->apiDecider->getApi($method, $version, $package, $apiAction); + if ($api->getHandler() instanceof DefaultHandler) { + // a static endpoint wins; only then are the URL templates of the endpoints tried + return $this->apiDecider->matchPath($method, $version, $package, $apiAction, $this->requestPath()) ?? $api; + } + + return $api; + } + + private function requestPath(): ?string + { + // without an http request service (for example in a CLI or a test container) templates are matched without a path + $httpRequest = $this->context->getByType(IRequest::class, false); + + return $httpRequest instanceof IRequest ? $httpRequest->getUrl()->getPath() : null; } /** diff --git a/src/Validation/ConstraintContext.php b/src/Validation/ConstraintContext.php new file mode 100644 index 000000000..e36d96f05 --- /dev/null +++ b/src/Validation/ConstraintContext.php @@ -0,0 +1,43 @@ + $properties property names of the DTO, in constructor order + * @param array $values converted sibling values keyed by property name; a failed sibling is absent + */ + public function __construct( + public string $path, + public string $dtoClass, + private array $properties, + private array $values, + ) { + } + + /** + * A sibling value of the same DTO, by its PHP property name. + * A property that was omitted or failed conversion is null. An unknown name is a programmer error. + */ + public function value(string $property): mixed + { + if (!in_array($property, $this->properties, true)) { + throw new \LogicException(sprintf( + "Constraint at '%s' reads property '%s', but %s has no such property. It has: %s. Use the PHP property name, for example value('%s').", + $this->path, + $property, + $this->dtoClass, + implode(', ', $this->properties), + $this->properties[0] ?? 'startsAt', + )); + } + + return $this->values[$property] ?? null; + } +} diff --git a/src/Validation/ConstraintInterface.php b/src/Validation/ConstraintInterface.php new file mode 100644 index 000000000..f4378443a --- /dev/null +++ b/src/Validation/ConstraintInterface.php @@ -0,0 +1,15 @@ +min === null && $this->max === null) { + throw new \InvalidArgumentException('Length needs min, max or both, for example #[Length(min: 1, max: 80)].'); + } + if (($this->min !== null && $this->min < 0) || ($this->max !== null && $this->max < 0)) { + throw new \InvalidArgumentException('Length bounds must be zero or greater, for example #[Length(min: 1, max: 80)].'); + } + if ($this->min !== null && $this->max !== null && $this->min > $this->max) { + throw new \InvalidArgumentException(sprintf( + 'Length min %d is greater than max %d. Swap them, for example #[Length(min: %d, max: %d)].', + $this->min, + $this->max, + $this->max, + $this->min, + )); + } + } + + #[\Override] + public function validate(mixed $value, ConstraintContext $context): ?string + { + if (is_string($value)) { + $count = mb_strlen($value, 'UTF-8'); + $unit = 'characters'; + } elseif (is_array($value)) { + $count = count($value); + $unit = 'items'; + } else { + return 'Length applies to a string or a list'; + } + + $min = $this->min; + $max = $this->max; + if ($min !== null && $max !== null && ($count < $min || $count > $max)) { + return 'Value must have between ' . $min . ' and ' . $max . ' ' . $unit; + } + if ($min !== null && $count < $min) { + return 'Value must have at least ' . $min . ' ' . $unit; + } + if ($max !== null && $count > $max) { + return 'Value must have at most ' . $max . ' ' . $unit; + } + + return null; + } +} diff --git a/src/Validation/Pattern.php b/src/Validation/Pattern.php new file mode 100644 index 000000000..7d69e5884 --- /dev/null +++ b/src/Validation/Pattern.php @@ -0,0 +1,79 @@ +pattern); + } catch (RegexpException $exception) { + throw new \InvalidArgumentException(sprintf( + "Pattern '%s' is not a valid PCRE pattern (%s). Use a delimited pattern, for example #[Pattern('/^[0-9]{5}$/')].", + $this->pattern, + $exception->getMessage(), + ), previous: $exception); + } + } + + /** + * The pattern without its delimiters when it means the same in ECMA 262 (an OpenAPI `pattern`), otherwise null. + * Only a plain subset qualifies: ASCII literals, escaped punctuation, \n \r \t, positive classes of literals and + * ranges, groups, lookahead, alternation, anchors and counted or greedy and lazy quantifiers. Only the flags u and D + * are allowed. \d \w and \b only without u, because PCRE makes them Unicode aware with u and ECMA 262 does not. + * Everything else (the dot, negated classes, \s, \D, \p, \x, back references, inline flags, possessive quantifiers + * and the rest of PCRE) reads differently or is a syntax error in a JavaScript validator. + */ + public function expression(): ?string + { + $delimiter = $this->pattern[0]; + $closing = ['(' => ')', '{' => '}', '[' => ']', '<' => '>'][$delimiter] ?? $delimiter; + $end = strrpos($this->pattern, $closing); + assert($end !== false); + $flags = substr($this->pattern, $end + 1); + if (trim($flags, 'uD') !== '') { + return null; + } + + $expression = substr($this->pattern, 1, $end - 1); + + return preg_match(self::portable(str_contains($flags, 'u')), $expression) === 1 ? $expression : null; + } + + private static function portable(bool $unicode): string + { + $punctuation = '\\\\^$.*+?()\[\]{}|\/'; + $literal = '[^\\\\.\[\](){}*+?|^$\x00-\x1F\x7F-\xFF]'; + $escape = '\\\\[' . $punctuation . 'nrt' . ($unicode ? '' : 'dw') . ']'; + $class = '\[(?!\^)(?:[^\\\\\[\]\x00-\x1F\x7F-\xFF]|\\\\[' . $punctuation . '\-nrt])+\]'; + $atom = '(?:' . $literal . '|' . $escape . '|' . $class . '|\((?:\?:)?(?&alt)\))(?:[*+?]|\{\d+(?:,\d*)?\})?\??'; + $assertion = '\^|\$|\((?:\?[=!])(?&alt)\)' . ($unicode ? '' : '|\\\\b'); + + return '/\A(?(?(?:' . $atom . '|' . $assertion . ')*)(?:\|(?&seq))*)\z/'; + } + + #[\Override] + public function validate(mixed $value, ConstraintContext $context): ?string + { + if (!is_string($value)) { + return 'Pattern applies to a string'; + } + // D: `$` matches only at the very end, so "81101\n" does not pass /^[0-9]{5}$/ (as in an OpenAPI pattern) + if (preg_match($this->pattern . 'D', $value) !== 1) { + return 'Value must match the pattern ' . $this->pattern; + } + + return null; + } +} diff --git a/src/Validation/Range.php b/src/Validation/Range.php new file mode 100644 index 000000000..4db13591b --- /dev/null +++ b/src/Validation/Range.php @@ -0,0 +1,58 @@ +min === null && $this->max === null) { + throw new \InvalidArgumentException('Range needs min, max or both, for example #[Range(min: 1, max: 100)].'); + } + if ($this->min !== null && $this->max !== null && $this->min > $this->max) { + throw new \InvalidArgumentException(sprintf( + 'Range min %s is greater than max %s. Swap them, for example #[Range(min: %s, max: %s)].', + $this->number($this->min), + $this->number($this->max), + $this->number($this->max), + $this->number($this->min), + )); + } + } + + #[\Override] + public function validate(mixed $value, ConstraintContext $context): ?string + { + if (!is_int($value) && !is_float($value)) { + return 'Range applies to an integer or a float'; + } + + $min = $this->min; + $max = $this->max; + if ($min !== null && $max !== null && ($value < $min || $value > $max)) { + return 'Value must be between ' . $this->number($min) . ' and ' . $this->number($max); + } + if ($min !== null && $value < $min) { + return 'Value must be at least ' . $this->number($min); + } + if ($max !== null && $value > $max) { + return 'Value must be at most ' . $this->number($max); + } + + return null; + } + + private function number(int|float $value): string + { + // shortest readable form: 0.5, 100, 1.0E-12 (a fixed number of decimals would print a tiny bound as 0) + return is_int($value) ? (string) $value : sprintf('%.15G', $value + 0.0); + } +} diff --git a/src/ValidationResult/FieldErrors.php b/src/ValidationResult/FieldErrors.php new file mode 100644 index 000000000..b29d79e0c --- /dev/null +++ b/src/ValidationResult/FieldErrors.php @@ -0,0 +1,41 @@ +> $errors + */ + public function __construct(private array $errors) + { + } + + #[\Override] + public function isOk(): bool + { + return $this->errors === []; + } + + /** + * @return array> + */ + #[\Override] + public function getErrors(): array + { + return $this->errors; + } + + /** + * @return array> + */ + public function fieldErrors(): array + { + return $this->errors; + } +} diff --git a/tests/Authorization/BearerTokenAuthorizationTest.php b/tests/Authorization/BearerTokenAuthorizationTest.php index 7a07fe802..f26926b32 100644 --- a/tests/Authorization/BearerTokenAuthorizationTest.php +++ b/tests/Authorization/BearerTokenAuthorizationTest.php @@ -13,6 +13,38 @@ final class BearerTokenAuthorizationTest extends TestCase { + protected function tearDown(): void + { + unset($_SERVER['HTTP_AUTHORIZATION'], $_SERVER['REDIRECT_HTTP_AUTHORIZATION']); + } + + public function testTheTokenThatApacheHandsOverAfterARewriteIsRead(): void + { + unset($_SERVER['HTTP_AUTHORIZATION']); + $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] = 'Bearer sad0f98uwegoihweg09i4hergy'; + $authorization = new BearerTokenAuthorization(new StaticTokenRepository(['sad0f98uwegoihweg09i4hergy' => '*']), new StaticIpDetector('34.24.126.44')); + + $this->assertTrue($authorization->authorized()); + } + + public function testWithoutAnyAuthorizationHeaderThereIsNoToken(): void + { + unset($_SERVER['HTTP_AUTHORIZATION'], $_SERVER['REDIRECT_HTTP_AUTHORIZATION']); + $authorization = new BearerTokenAuthorization(new StaticTokenRepository(['x' => '*']), new StaticIpDetector('34.24.126.44')); + + $this->assertFalse($authorization->authorized()); + $this->assertSame('Authorization header HTTP_Authorization is not set', $authorization->getErrorMessage()); + } + + public function testTheHeaderWinsOverTheRewrittenOne(): void + { + $_SERVER['HTTP_AUTHORIZATION'] = 'Bearer wrong'; + $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] = 'Bearer sad0f98uwegoihweg09i4hergy'; + $authorization = new BearerTokenAuthorization(new StaticTokenRepository(['sad0f98uwegoihweg09i4hergy' => '*']), new StaticIpDetector('34.24.126.44')); + + $this->assertFalse($authorization->authorized()); + } + public function testAuthorizedToken(): void { $_SERVER['HTTP_AUTHORIZATION'] = 'Bearer sad0f98uwegoihweg09i4hergy'; diff --git a/tests/DI/TypedBad/BadHandler.php b/tests/DI/TypedBad/BadHandler.php new file mode 100644 index 000000000..4c4e24efd --- /dev/null +++ b/tests/DI/TypedBad/BadHandler.php @@ -0,0 +1,19 @@ +getByType(ApiDecider::class)->getApis() as $api) { + $handlers[$api->getEndpoint()->getUrl()] = $api->getHandler()::class; + } + $this->assertSame(ListUsersHandler::class, $handlers['v1/users/list']); + + RequestInput::reset(); + $_GET = ['page' => '3', 'status' => 'active']; + $handler = $container->getByType(ListUsersHandler::class); + $processor = new ParamsProcessor($handler->params()); + $this->assertFalse($processor->isError()); + $this->assertSame(3, $handler->handle($processor->getValues())->getPayload()['page']); + } + + public function testABadDtoFailsContainerCompilation(): void + { + $dir = dirname(__DIR__) . '/DI/TypedBad'; + $this->expectException(\LogicException::class); + $this->expectExceptionMessage('no contract to validate'); + ContainerFactory::create(<<expectException(\LogicException::class); + $this->expectExceptionMessage('do not match'); + ContainerFactory::create(<<<'NEON' +api: + endpoints: + - {method: GET, version: 1, package: users, action: detail, handler: Tomaj\NetteApi\Test\Input\Fixtures\UserDetailHandler} +NEON); + } +} diff --git a/tests/Error/UnsupportedMediaTypeTest.php b/tests/Error/UnsupportedMediaTypeTest.php new file mode 100644 index 000000000..fedb8c46f --- /dev/null +++ b/tests/Error/UnsupportedMediaTypeTest.php @@ -0,0 +1,57 @@ +handleUnsupportedMediaType("Content-Type 'text/csv' is not supported for this endpoint. Use one of: application/json."); + $this->assertSame(415, $response->getCode()); + $this->assertSame(['status' => 'error', 'message' => 'unsupported media type'], $response->getPayload()); + + $shown = new DefaultErrorHandler(new DebuggerConfigurator()); + $payload = $shown->handleUnsupportedMediaType("Content-Type 'text/csv' is not supported for this endpoint. Use one of: application/json.")->getPayload(); + $this->assertSame('unsupported media type', $payload['message']); + $this->assertStringContainsString('text/csv', (string) $payload['detail']); + } + + public function testProblemDetailsUses415AndTheSameDetail(): void + { + $handler = new ProblemDetailsErrorHandler(new DebuggerConfigurator(), 'https://api.example.com/problems'); + $response = $handler->handleUnsupportedMediaType('Content-Type is missing. Use one of: application/json.'); + $this->assertSame(415, $response->getCode()); + $this->assertSame('application/problem+json', $response->getContentType()); + $payload = $response->getPayload()->toArray(); + $this->assertSame(415, $payload['status']); + $this->assertSame('Unsupported Media Type', $payload['title']); + $this->assertSame('https://api.example.com/problems/unsupported-media-type', $payload['type']); + $this->assertSame('Content-Type is missing. Use one of: application/json.', $payload['detail']); + } + + public function testNegotiationSelectsProblemDetailsForTheAcceptHeader(): void + { + $http = new Response(); + $handler = new NegotiatingErrorHandler( + new DefaultErrorHandler(new StaticConfigurator(true)), + new ProblemDetailsErrorHandler(new StaticConfigurator(true)), + new Request(new UrlScript('http://localhost/'), headers: ['Accept' => 'application/problem+json']), + $http, + ); + $response = $handler->handleUnsupportedMediaType('Content-Type is missing. Use one of: application/json.'); + $this->assertSame('application/problem+json', $response->getContentType()); + } +} diff --git a/tests/Input/BehaviorPinTest.php b/tests/Input/BehaviorPinTest.php new file mode 100644 index 000000000..1c245bb46 --- /dev/null +++ b/tests/Input/BehaviorPinTest.php @@ -0,0 +1,827 @@ +export(); + $files = $export['files']; + unset($export['files']); + $expected = json_decode((string) file_get_contents(__DIR__ . '/Fixtures/create-order-export.json'), true); + $this->assertSame($expected, $export); + $this->assertTrue(array_is_list($files)); + $this->assertContains(realpath(__DIR__ . '/Fixtures/Handlers.php') ?: '', array_map(realpath(...), $files)); + } + + public function testImportedMetadataRoundTrips(): void + { + $compiled = DtoCompiler::compile(CreateOrderHandler::class); + $export = $compiled->export(); + $export['contentTypes'][] = 5; + $export['files'] = [2 => '/tmp/a.php', 4 => '/tmp/b.php']; + $imported = DtoMetadata::import($export); + $this->assertSame($compiled->handler, $imported->handler); + $this->assertSame($compiled->class, $imported->class); + $this->assertSame($compiled->contentTypes, $imported->contentTypes); + $this->assertTrue(array_is_list($imported->files)); + $this->assertSame(['/tmp/a.php', '/tmp/b.php'], $imported->files); + $again = $imported->export(); + unset($export['files'], $again['files'], $export['contentTypes'], $again['contentTypes']); + $this->assertEquals($export, $again); + + $examples = DtoCompiler::compile(TwoExamplesHandler::class); + $restored = DtoMetadata::import($examples->export()); + $this->assertSame(['one' => 1, 'two' => 2], $restored->fields[0]->examples); + $this->assertSame([1, 2], DtoCompiler::compile(ListUsersHandler::class)->fields[3]->enumValues); + $priority = DtoMetadata::import(DtoCompiler::compile(ListUsersHandler::class)->export()); + $this->assertSame([1, 2], $priority->fields[3]->enumValues); + } + + public function testQueryOnlyHandlerDoesNotReadABody(): void + { + $metadata = DtoCompiler::compile(ListUsersHandler::class); + $this->assertFalse($metadata->readsBody); + $this->assertFalse($metadata->bodyRequired); + $this->assertNull($metadata->firstBody); + $this->assertFalse($metadata->fields[0]->listItemBuiltin); + $this->assertFalse($metadata->fields[0]->enumInt); + $this->assertTrue($metadata->fields[3]->enumInt); + $this->assertSame([1, 2], $metadata->fields[3]->enumValues); + } + + public function testSameInstanceIsReusedUntilReset(): void + { + $first = DtoMetadataRegistry::forHandler(ListUsersHandler::class); + $again = DtoMetadataRegistry::forHandler(ListUsersHandler::class); + $this->assertSame($first, $again); + + $export = $first->export(); + $export['firstBody'] = 'from-install'; + DtoMetadataRegistry::reset(); + DtoMetadataRegistry::install([ListUsersHandler::class => $export]); + $this->assertTrue(DtoMetadataRegistry::installs(ListUsersHandler::class)); + $this->assertSame('from-install', DtoMetadataRegistry::forHandler(ListUsersHandler::class)->firstBody); + $this->assertFalse(DtoMetadataRegistry::installs(CreateOrderHandler::class)); + $this->assertSame(CreateOrderHandler::class, DtoMetadataRegistry::forHandler(CreateOrderHandler::class)->handler); + } + + public function testMissingHandlerNamesTheClass(): void + { + $this->expectException(\LogicException::class); + $this->expectExceptionMessage("Typed handler 'Missing\\Handler' does not exist. Check the class name and the autoload section of composer.json."); + DtoCompiler::compile('Missing\\Handler'); + } + + public function testCycleNamesEveryStep(): void + { + try { + DtoCompiler::compile(CyclePinHandler::class); + $this->fail('cycle'); + } catch (\LogicException $exception) { + $this->assertSame( + sprintf( + 'DTO %s refers to itself (%s -> %s). Nested DTOs cannot form a cycle; keep the nesting one way.', + CyclePinInput::class, + CyclePinInput::class, + CyclePinInput::class, + ), + $exception->getMessage(), + ); + } + } + + public function testDeclarationsThatCannotBeMapped(): void + { + $cases = [ + PrivateHandler::class => 'must be a public instance method', + StaticHandler::class => 'must be a public instance method', + StdClassReturnHandler::class => 'must return', + AbstractDtoHandler::class => 'cannot be an input DTO', + EnumDtoHandler::class => 'cannot be an input DTO', + InterfaceDtoHandler::class => 'cannot be an input DTO', + IterableHandler::class => 'has type iterable', + FileOnQueryHandler::class => 'needs #[File]', + BareFileUploadHandler::class => 'needs #[File]', + ]; + foreach ($cases as $handler => $needle) { + try { + DtoCompiler::compile($handler); + $this->fail($handler); + } catch (\LogicException $exception) { + $this->assertStringContainsString($needle, $exception->getMessage(), $handler); + } + } + + $examples = DtoCompiler::compile(TwoExamplesHandler::class)->fields[0]->examples; + $this->assertSame(['one' => 1, 'two' => 2], $examples); + + $twin = DtoCompiler::compile(TwinHandler::class); + $this->assertSame('left', $twin->firstBody); + $this->assertTrue($twin->readsBody); + $address = realpath(new \ReflectionClass(AddressInput::class)->getFileName() ?: ''); + $this->assertCount(1, array_filter($twin->files, static fn (string $file): bool => realpath($file) === $address)); + $this->assertSame(['id', 'slug'], DtoCompiler::compile(TwoPathsHandler::class)->pathNames()); + $this->assertSame( + [MediaTypes::JSON, MediaTypes::MULTIPART], + DtoCompiler::compile(AvatarHandler::class)->contentTypes, + ); + $described = DtoCompiler::compile(DescribedHandler::class); + $this->assertFalse($described->bodyRequired); + $this->assertTrue($described->readsBody); + $this->assertSame([MediaTypes::JSON], $described->contentTypes); + } + + public function testBoundsAcceptTheInclusiveEdge(): void + { + $range = new Range(min: 1, max: 1); + $this->assertNull($range->validate(1, new ConstraintContext('n', 'Dto', ['n'], ['n' => 1]))); + $this->assertSame('1.5', new Range(min: 1.5, max: 2.5)->validate(1.5, new ConstraintContext('n', 'Dto', ['n'], ['n' => 1.5])) === null ? '1.5' : 'rejected'); + new Length(min: 2, max: 2); + new Length(max: 0); + $length = new Length(min: 0, max: 2); + $this->assertNull($length->validate('', new ConstraintContext('s', 'Dto', ['s'], ['s' => '']))); + $this->assertNull($length->validate('ab', new ConstraintContext('s', 'Dto', ['s'], ['s' => 'ab']))); + $this->assertSame('Value must have between 0 and 2 characters', $length->validate('abc', new ConstraintContext('s', 'Dto', ['s'], ['s' => 'abc']))); + $this->assertSame('Value must have at most 2 characters', new Length(max: 2)->validate('abc', new ConstraintContext('s', 'Dto', ['s'], ['s' => 'abc']))); + $this->assertSame('^[0-9]{5}$', new Pattern('/^[0-9]{5}$/')->expression()); + try { + new Length(max: -1); + $this->fail('negative'); + } catch (\InvalidArgumentException $exception) { + $this->assertStringContainsString('zero or greater', $exception->getMessage()); + } + $this->assertSame('Value must be at least 1.5', new Range(min: 1.5)->validate(1, new ConstraintContext('n', 'Dto', ['n'], ['n' => 1]))); + + try { + new ConstraintContext('page', 'Dto', ['page'], [])->value('missing'); + $this->fail('unknown'); + } catch (\LogicException $exception) { + $this->assertStringContainsString("value('page')", $exception->getMessage()); + } + } + + public function testDateAndEnumMessages(): void + { + $date = new DateFormat('d.m.Y')->cast('24.12.2026'); + $this->assertSame('2026-12-24T00:00:00+00:00', $date->format('c')); + $parsed = ScalarCoercer::toDateTime('2026-12-24T00:00:00.1Z'); + $this->assertSame('100000', $parsed->format('u')); + $longer = ScalarCoercer::toDateTime('2026-12-24T00:00:00.1234567Z'); + $this->assertSame('123456', $longer->format('u')); + $this->assertSame('Value must be one of: 1, 2', ScalarCoercer::enumMessage(Priority::class)); + $this->assertSame( + ['__netteApi' => 'enum', 'class' => Priority::class, 'value' => 1.5], + ValueExport::import(['__netteApi' => 'enum', 'class' => Priority::class, 'value' => 1.5]), + ); + $this->assertSame('application/json', MediaTypes::normalize(' Application/JSON ; charset=utf-8')); + } + + public function testSchemaObjectCopiesDescription(): void + { + $field = DtoCompiler::compile(ListUsersHandler::class)->fields[0]; + $schema = SchemaBuilder::object([$field]); + $this->assertSame('Page number', $schema['properties']['page']['description']); + $this->assertSame('integer', $schema['properties']['page']['type']); + $this->assertArrayNotHasKey('required', $schema); + $id = DtoCompiler::compile(UserDetailHandler::class)->fields[0]; + $required = SchemaBuilder::object([$id]); + $this->assertSame(['id'], $required['required']); + $this->assertSame('integer', $required['properties']['id']['type']); + } + + public function testHeadersIgnoreServerInternals(): void + { + $_SERVER['HTTP_X_REQUEST_ID'] = 'abc'; + $_SERVER['HTTP_X_TRACE'] = 'xyz'; + $_SERVER['SCRIPT_NAME'] = '/index.php'; + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $this->assertSame('abc', HeaderBag::get('x-request-id')); + $this->assertSame('xyz', HeaderBag::get('X-Trace')); + $this->assertFalse(HeaderBag::has('t-name')); + $this->assertSame('application/json', HeaderBag::get('Content-Type')); + } + + public function testFileUploadReplacesNonStrings(): void + { + $file = FileUpload::fromFile(['name' => 1, 'type' => 2, 'tmp_name' => 3, 'size' => '12']); + $this->assertSame('', $file->originalName); + $this->assertSame('', $file->clientContentType); + $this->assertSame('', $file->temporaryPath); + $this->assertSame(0, $file->size); + $this->assertSame(\UPLOAD_ERR_NO_FILE, $file->error); + } + + public function testNestedDefaultsRoundTrip(): void + { + $exported = ValueExport::export(['flag' => true, 'nested' => ['n' => 2], 'status' => Priority::High]); + $this->assertSame(2, ValueExport::import($exported)['nested']['n']); + $this->assertSame(Priority::High, ValueExport::import($exported)['status']); + } + + public function testPathCaptureDoesNotLeakIntoTheNextEndpoint(): void + { + $decider = new ApiDecider(new Container()); + $decider->enableGlobalPreflight(); + $decider->addApi(new EndpointIdentifier('GET', 1, 'users', 'list'), new AlwaysOkHandler(), new NoAuthorization()); + $decider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), new UserDetailHandler(), new NoAuthorization()); + $decider->addApi(new EndpointIdentifier('GET', 2, 'users', '{id}/detail'), new UserDetailHandler(), new NoAuthorization()); + + $matched = self::resolve($decider, 'GET', '1', 'users', '42', '/api/v1/users/42/detail'); + $id = null; + foreach ($matched->getHandler()->params() as $param) { + if ($param->getKey() === 'id') { + $id = $param->getValue(); + } + } + $this->assertSame(42, $id); + + $static = self::resolve($decider, 'GET', '1', 'users', 'list', '/api/v1/users/list'); + $this->assertInstanceOf(AlwaysOkHandler::class, $static->getHandler()); + foreach (new UserDetailHandler()->params() as $param) { + if ($param->getKey() === 'id') { + $this->assertNull($param->getValue()); + } + } + + $post = self::resolve($decider, 'POST', '1', 'users', '42', '/api/v1/users/42/detail'); + $this->assertInstanceOf(DefaultHandler::class, $post->getHandler()); + $withPreflight = self::resolve($decider, 'GET', '1', 'users', '7', '/api/v1/users/7/detail'); + $this->assertInstanceOf(UserDetailHandler::class, $withPreflight->getHandler()); + $otherVersion = self::resolve($decider, 'GET', '1', 'users', '7', '/api/v2/users/7/detail'); + $this->assertInstanceOf(DefaultHandler::class, $otherVersion->getHandler()); + + $decider->addApi(new EndpointIdentifier('GET', 1, 'users', 'detail'), new UserDetailHandler(), new NoAuthorization()); + $this->expectException(\LogicException::class); + $decider->getApi('GET', '1', 'users', 'detail'); + } + + private static function resolve(ApiDecider $decider, string $method, string $version, string $package, string $apiAction, string $path): Api + { + $api = $decider->getApi($method, $version, $package, $apiAction); + + return $api->getHandler() instanceof DefaultHandler ? ($decider->matchPath($method, $version, $package, $apiAction, $path) ?? $api) : $api; + } + + public function testPresenterDropsAStaleBody(): void + { + RequestInput::setRawBody('{"customerEmail":"ada@example.com","address":{"street":"Main","postalCode":"81101"},"items":[{"sku":"A","quantity":1}]}'); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + $decider = new ApiDecider(new Container()); + $decider->addApi(new EndpointIdentifier('POST', 1, 'orders'), new CreateOrderHandler(), new NoAuthorization()); + $presenter = new ApiPresenter(); + $presenter->apiDecider = $decider; + $presenter->response = new HttpResponse(); + $presenter->context = new Container(); + $presenter->outputConfigurator = new DebuggerConfigurator(); + $presenter->errorHandler = new DefaultErrorHandler($presenter->outputConfigurator); + $result = $presenter->run(new Request('Api:Api:default', 'POST', ['version' => '1', 'package' => 'orders'])); + $this->assertSame(400, $result->getCode()); + } + + public function testASecondBootOfTheSameHandlerKeepsTheFirstRead(): void + { + $_GET = ['page' => '4']; + $first = $this->payload(new ListUsersHandler()); + $_GET = ['page' => '9']; + $second = $this->payload(new ListUsersHandler()); + $this->assertSame(4, $first['page']); + $this->assertSame(4, $second['page']); + + RequestInput::reset(); + $_GET = ['page' => '9']; + $this->assertSame(9, $this->payload(new ListUsersHandler())['page']); + } + + public function testFieldErrorsStayOnTheirOwnName(): void + { + $params = new PrefixHandler()->params(); + $byName = []; + foreach ($params as $param) { + $result = $param->validate(); + $this->assertFalse($result->isOk()); + $byName[$param->getKey()] = $result->getErrors(); + } + $this->assertSame(['a' => ['Field is required']], $byName['a']); + $this->assertSame(['ab' => ['Field is required']], $byName['ab']); + $this->assertSame('', $params[0]->getDescription()); + $page = new ListUsersHandler()->params()[0]; + $this->assertSame('Page number', $page->getDescription()); + $this->assertFalse($page->isMulti()); + $items = new CreateOrderHandler()->params()[2]; + $this->assertTrue($items->isMulti()); + $this->assertNotSame([], $items->getContentTypes()); + } + + public function testMalformedJsonStillChecksQueryFields(): void + { + $_GET = ['page' => '1a']; + RequestInput::setRawBody('{"email":'); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + $errors = $this->errors(new QueryAfterBodyHandler()); + $this->assertStringStartsWith('Syntax error', $errors['body'][0]); + $this->assertSame(['Value must be an integer'], $errors['page']); + } + + public function testInvalidIntegerKeepsTheDefaultForTheValue(): void + { + $_GET = ['page' => '1a']; + $page = new ListUsersHandler()->params()[0]; + $page->validate(); + $this->assertSame(1, $page->getValue()); + } + + public function testEveryNestedErrorIsReported(): void + { + $this->json([ + 'customerEmail' => 'ada@example.com', + 'address' => ['street' => '', 'postalCode' => 'abc'], + 'items' => [ + ['sku' => 'A', 'quantity' => 0], + ['sku' => 'B', 'quantity' => 0], + ], + ]); + $errors = $this->errors(new CreateOrderHandler()); + $this->assertArrayHasKey('address.street', $errors); + $this->assertArrayHasKey('address.postalCode', $errors); + $this->assertArrayHasKey('items[0].quantity', $errors); + $this->assertArrayHasKey('items[1].quantity', $errors); + + RequestInput::reset(); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + RequestInput::setRawBody('{"customerEmail":"ada@example.com","address":{},"items":[{"sku":"A","quantity":1}]}'); + $emptyObject = $this->errors(new CreateOrderHandler()); + $this->assertSame(['Field is required'], $emptyObject['address.street']); + $this->assertArrayNotHasKey('address', $emptyObject); + + RequestInput::reset(); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + RequestInput::setRawBody('{"customerEmail":"ada@example.com","address":[],"items":[{"sku":"A","quantity":1}]}'); + $this->assertSame(['Value must be an object'], $this->errors(new CreateOrderHandler())['address']); + + RequestInput::reset(); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + RequestInput::setRawBody('{"customerEmail":"ada@example.com","address":{"street":"Main 1","postalCode":"81101"},"items":{}}'); + $this->assertSame(['Value must be a list'], $this->errors(new CreateOrderHandler())['items']); + + RequestInput::reset(); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + RequestInput::setRawBody('[]'); + $this->assertSame(['body' => ['Value must be an object']], $this->errors(new CreateOrderHandler())); + } + + public function testEmptyObjectAndFloat(): void + { + RequestInput::setRawBody('{}'); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + $errors = $this->errors(new CreateOrderHandler()); + $this->assertArrayNotHasKey('body', $errors); + $this->assertSame(['Field is required'], $errors['customerEmail']); + + RequestInput::reset(); + $_GET = ['ratio' => '1.5']; + $this->assertEqualsWithDelta(1.5, $this->payload(new FloatHandler())['ratio'], PHP_FLOAT_EPSILON); + } + + public function testUploadErrorShapes(): void + { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_SERVER['CONTENT_TYPE'] = 'multipart/form-data'; + $_FILES = ['avatar' => ['name' => '', 'type' => '', 'tmp_name' => '', 'error' => \UPLOAD_ERR_NO_FILE, 'size' => 0]]; + $_POST = ['displayName' => 'Ada']; + $this->assertSame(['avatar' => ['Field is required']], $this->errors(new AvatarHandler())); + + RequestInput::reset(); + $_FILES = ['avatar' => ['name' => 'a.png', 'type' => '', 'tmp_name' => '/tmp/a', 'error' => \UPLOAD_ERR_NO_FILE, 'size' => 4]]; + $this->assertSame('a.png', $this->payload(new AvatarHandler())['file']); + + RequestInput::reset(); + $_FILES = ['avatar' => ['error' => \UPLOAD_ERR_NO_FILE, 'size' => 0]]; + $this->assertSame(['avatar' => ['Field is required']], $this->errors(new AvatarHandler())); + } + + public function testBodyParamReadsJsonObjectsOnly(): void + { + RequestInput::setRawBody('{"note":"hi","1":"n"}'); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $param = new BodyInputParam('note'); + $this->assertSame('hi', $param->getValue()); + $numeric = new BodyInputParam('1'); + $this->assertSame('n', $numeric->getValue()); + + RequestInput::reset(); + RequestInput::setRawBody('[1, 2]'); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $this->assertNull(new BodyInputParam('note')->getValue()); + + RequestInput::reset(); + RequestInput::setRawBody(''); + $this->assertNull(new BodyInputParam('note')->getValue()); + } + + public function testOpenApiUsesTheDeclaredBodyMediaTypeAndDescription(): void + { + $builder = new RequestBodyBuilder(); + $body = $builder->build(new DescribedHandler(), new SchemaRegistry()); + $this->assertIsArray($body); + $this->assertSame(['application/json'], array_keys($body['content'])); + $this->assertSame('Customer email', $body['content']['application/json']['schema']['properties']['email']['description']); + $this->assertFalse($body['required']); + } + + public function testLinkKeepsASlashInThePackage(): void + { + $link = ApiFixtures::apiLink()->link(new EndpointIdentifier('GET', 1, 'acme/widgets', 'show'), ['q' => 'a b']); + $this->assertSame('https://example.com/api/v1/acme/widgets/show?q=a+b', $link); + } + + public function testExtensionInstallsTypedHandlersAndTheirFiles(): void + { + $container = ContainerFactory::create(<<<'NEON' +services: + listUsers: Tomaj\NetteApi\Test\Input\Fixtures\ListUsersHandler +api: + endpoints: + - {method: GET, version: 1, package: people, handler: @listUsers} + - {method: POST, version: 1, package: orders, handler: Tomaj\NetteApi\Test\Input\Fixtures\CreateOrderHandler()} +NEON); + $container->initialize(); + $this->assertTrue(DtoMetadataRegistry::installed()); + $this->assertTrue(DtoMetadataRegistry::installs(ListUsersHandler::class)); + $this->assertTrue(DtoMetadataRegistry::installs(CreateOrderHandler::class)); + $urls = []; + foreach ($container->getByType(ApiDecider::class)->getApis() as $api) { + $urls[] = $api->getEndpoint()->getUrl(); + } + $this->assertContains('v1/people/', $urls); + $this->assertContains('v1/orders/', $urls); + + DtoMetadataRegistry::reset(); + $empty = ContainerFactory::create("api:\n endpoints: []\n"); + $empty->initialize(); + $this->assertFalse(DtoMetadataRegistry::installed()); + + $compiler = new Compiler(); + $compiler->addExtension('api', new NetteApiExtension()); + $compiler->addConfig([ + 'api' => [ + 'endpoints' => [[ + 'method' => 'POST', + 'version' => 1, + 'package' => 'orders', + 'handler' => CreateOrderHandler::class, + ]], + ], + ]); + $compiler->compile(); + $this->assertStringContainsString('Handlers.php', serialize($compiler->exportDependencies())); + } + + public function testBackslashHandlerIsInstalledUnderItsRealName(): void + { + $container = ContainerFactory::create(<<<'NEON' +api: + endpoints: + - {method: GET, version: 1, package: people, action: list, handler: \Tomaj\NetteApi\Test\Input\Fixtures\ListUsersHandler} +NEON); + $container->initialize(); + $this->assertTrue(DtoMetadataRegistry::installs(ListUsersHandler::class)); + } + + /** + * @param array $body + */ + private function json(array $body): void + { + RequestInput::reset(); + RequestInput::setRawBody((string) json_encode($body)); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_GET = []; + $_POST = []; + } + + /** + * @return array + */ + private function payload(object $handler): array + { + $processor = new ParamsProcessor($handler->params()); + $this->assertFalse($processor->isError(), (string) json_encode($processor->getErrors())); + + return $handler->handle($processor->getValues())->getPayload(); + } + + /** + * @return array> + */ + private function errors(object $handler): array + { + $processor = new ParamsProcessor($handler->params()); + $this->assertTrue($processor->isError()); + + return $processor->getErrors(); + } +} + +final readonly class CyclePinInput +{ + public function __construct(#[Body] public CyclePinInput $child) + { + } +} + +final class CyclePinHandler extends TypedHandler +{ + public function handleDto(CyclePinInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final class PrivateHandler extends TypedHandler +{ + private function handleDto(CyclePinInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final class StaticHandler extends TypedHandler +{ + public static function handleDto(CyclePinInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final class StdClassReturnHandler extends TypedHandler +{ + public function handleDto(CyclePinInput $input): \stdClass + { + return new \stdClass(); + } +} + +abstract readonly class AbstractPinInput +{ + public function __construct(#[Query] public string $name) + { + } +} + +final class AbstractDtoHandler extends TypedHandler +{ + public function handleDto(AbstractPinInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final class EnumDtoHandler extends TypedHandler +{ + public function handleDto(Priority $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +interface PinContract +{ +} + +final class InterfaceDtoHandler extends TypedHandler +{ + public function handleDto(PinContract $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class IterableInput +{ + public function __construct(#[Query] public iterable $name) + { + } +} + +final class IterableHandler extends TypedHandler +{ + public function handleDto(IterableInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class FileOnQueryInput +{ + public function __construct(#[Query] public FileUpload $file) + { + } +} + +final class FileOnQueryHandler extends TypedHandler +{ + public function handleDto(FileOnQueryInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BareFileUploadInput +{ + /** @param list $files */ + public function __construct(#[Query] public array $files) + { + } +} + +final class BareFileUploadHandler extends TypedHandler +{ + public function handleDto(BareFileUploadInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class TwoExamplesInput +{ + public function __construct(#[Query(examples: ['one' => 1, 'two' => 2])] public int $page = 1) + { + } +} + +final class TwoExamplesHandler extends TypedHandler +{ + public function handleDto(TwoExamplesInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class TwinInput +{ + public function __construct( + #[Body] public AddressInput $left, + #[Body] public AddressInput $right, + ) { + } +} + +final class TwinHandler extends TypedHandler +{ + public function handleDto(TwinInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['street' => $input->left->street]); + } +} + +final readonly class TwoPathsInput +{ + public function __construct( + #[Path] public string $id, + #[Path] public string $slug, + ) { + } +} + +final class TwoPathsHandler extends TypedHandler +{ + public function handleDto(TwoPathsInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class PrefixInput +{ + public function __construct( + #[Query(description: '')] public string $a, + #[Query] public string $ab, + ) { + } +} + +final class PrefixHandler extends TypedHandler +{ + public function handleDto(PrefixInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class QueryAfterBodyInput +{ + public function __construct( + #[Body] public string $email, + #[Query] public int $page = 1, + ) { + } +} + +final class QueryAfterBodyHandler extends TypedHandler +{ + public function handleDto(QueryAfterBodyInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['page' => $input->page]); + } +} + +final readonly class FloatInput +{ + public function __construct(#[Query] public float $ratio) + { + } +} + +final class FloatHandler extends TypedHandler +{ + public function handleDto(FloatInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['ratio' => $input->ratio]); + } +} + +final readonly class DescribedInput +{ + public function __construct( + #[Body(description: 'Customer email')] public ?string $email = null, + ) { + } +} + +#[Consumes('application/json')] +final class DescribedHandler extends TypedHandler +{ + public function handleDto(DescribedInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} diff --git a/tests/Input/CasterTest.php b/tests/Input/CasterTest.php new file mode 100644 index 000000000..a41a95413 --- /dev/null +++ b/tests/Input/CasterTest.php @@ -0,0 +1,68 @@ +cast('24.12.2026'); + $this->assertSame('2026-12-24 00:00:00', $date->format('Y-m-d H:i:s')); + $this->assertSame(['type' => 'string', 'example' => '24.12.2026'], $caster->openApiSchema(), 'format: date means Y-m-d only'); + $this->assertSame(['type' => 'string', 'format' => 'date', 'example' => '2026-12-24'], new DateFormat('Y-m-d')->openApiSchema()); + + foreach (['31.02.2026', '24.12.2026 ', '2026-12-24', 1, ''] as $value) { + try { + $caster->cast($value); + $this->fail('accepted ' . var_export($value, true)); + } catch (CastException $exception) { + $this->assertSame('Date must match d.m.Y, for example 24.12.2026', $exception->getMessage()); + } + } + } + + public function testDateFormatRejectsAnEmptyFormat(): void + { + $this->expectException(\InvalidArgumentException::class); + new DateFormat(''); + } + + public function testUnixTimestamp(): void + { + $caster = new UnixTimestamp(); + $this->assertSame('2026-12-24T00:00:00+00:00', $caster->cast('1798070400')->format('c')); + $this->assertSame('2026-12-24T00:00:00+00:00', $caster->cast(1798070400)->format('c')); + $this->assertSame(['type' => 'integer', 'example' => 1798185600], $caster->openApiSchema()); + + $this->expectException(CastException::class); + $caster->cast('1798070400abc'); + } + + public function testSplitKeepsEmptyPieces(): void + { + $caster = new Split(','); + $this->assertSame(['red', 'green', 'blue'], $caster->cast('red,green,blue')); + $this->assertSame([''], $caster->cast('')); + $this->assertSame(['a', '', 'b'], $caster->cast('a,,b')); + $this->assertSame(['type' => 'string', 'example' => 'red,green,blue'], $caster->openApiSchema()); + $this->assertSame('red|green|blue', new Split('|')->openApiSchema()['example']); + + $this->expectException(CastException::class); + $caster->cast(['red']); + } + + public function testSplitRejectsAnEmptySeparator(): void + { + $this->expectException(\InvalidArgumentException::class); + new Split(''); + } +} diff --git a/tests/Input/CompilerBranchTest.php b/tests/Input/CompilerBranchTest.php new file mode 100644 index 000000000..a704e075c --- /dev/null +++ b/tests/Input/CompilerBranchTest.php @@ -0,0 +1,1122 @@ +assertTrue($metadata->readsBody); + $this->assertTrue($metadata->bodyRequired); + $this->assertSame('email', $metadata->firstBody); + } + + public function testHandlerAndDtoFilesAreBothRecorded(): void + { + $files = array_map(realpath(...), DtoCompiler::compile(NoteHandler::class)->files); + $this->assertContains(realpath(new \ReflectionClass(NoteHandler::class)->getFileName() ?: ''), $files); + $this->assertContains(realpath(new \ReflectionClass(NoteInput::class)->getFileName() ?: ''), $files); + } + + public function testCompileFailuresNameTheExactProblem(): void + { + $this->assertCompileFails(MissingDtoHandler::class, "DTO 'MissingDto\\Nope' does not exist"); + $this->assertCompileFails(UnionReturnHandler::class, 'must return'); + try { + DtoCompiler::compile(CycleLeftHandler::class); + $this->fail('cycle'); + } catch (\LogicException $exception) { + $this->assertStringContainsString(CycleRight::class, $exception->getMessage()); + $this->assertStringContainsString(CycleLeft::class . ' -> ' . CycleRight::class . ' -> ' . CycleLeft::class, $exception->getMessage()); + } + $this->assertCompileFails(ParentQueryListHandler::class, 'Nested properties are part of the body'); + $this->assertCompileFails(UnknownListItemHandler::class, 'documents list,'); + $this->assertCompileFails(IntCasterHandler::class, 'must return string'); + $this->assertCompileFails(AbstractCasterHandler::class, 'must be a concrete class'); + $this->assertCompileFails(ExtraSchemaHandler::class, 'Return only type, format and example'); + $this->assertCompileFails(NullableReturnCasterHandler::class, '(string)'); + $this->assertCompileFails(ListDocCasterHandler::class, '@return list'); + } + + public function testAcceptedShapes(): void + { + $nullable = DtoCompiler::compile(NullableIntHandler::class); + $this->assertTrue($nullable->fields[0]->nullable); + $child = DtoCompiler::compile(ChildPinHandler::class); + $this->assertSame(PinBase::class, $child->fields[0]->typeName); + $this->assertSame('string', DtoCompiler::compile(StringChildHandler::class)->fields[0]->typeName); + $this->assertSame('name', DtoCompiler::compile(BoomThenQueryHandler::class)->fields[0]->externalName); + $varList = DtoCompiler::compile(VarListHandler::class)->fields[0]; + $this->assertSame('string', $varList->listItem); + $this->assertTrue($varList->listItemBuiltin); + $priorities = DtoCompiler::compile(PriorityListHandler::class)->fields[0]->item; + $this->assertInstanceOf(Field::class, $priorities); + $this->assertSame(Priority::class, $priorities->enumClass); + $this->assertTrue($priorities->enumInt); + $this->assertSame([1, 2], $priorities->enumValues); + $float = DtoCompiler::compile(FloatRangeHandler::class); + $this->assertInstanceOf(Range::class, $float->fields[0]->constraints[0]); + $this->assertInstanceOf(Length::class, DtoCompiler::compile(StringLengthHandler::class)->fields[0]->constraints[0]); + $this->assertInstanceOf(Pattern::class, DtoCompiler::compile(PatternHandler::class)->fields[0]->constraints[0]); + $this->assertInstanceOf(Email::class, DtoCompiler::compile(EmailHandler::class)->fields[0]->constraints[0]); + $this->assertCompileFails(NestedFileHandler::class, 'NestedUploadInput::$avatar uses #[File]. Uploads are read only on the root DTO'); + $hint = DtoCompiler::compile(DateHintHandler::class)->fields[0]->casterSchema; + $this->assertIsArray($hint); + $this->assertSame('string', $hint['type']); + $this->assertArrayNotHasKey('format', $hint, 'd.m.Y is not the OpenAPI full-date'); + $emptyHint = DtoCompiler::compile(EmptyHintHandler::class)->fields[0]->casterSchema; + $this->assertSame(['type' => 'string'], $emptyHint); + $plain = DtoCompiler::compile(PlainCasterHandler::class)->fields[0]; + $this->assertSame(['type' => 'string'], $plain->casterSchema, 'without a hint the wire value is a string'); + } + + public function testSchemaTypes(): void + { + $float = SchemaBuilder::build(DtoCompiler::compile(FloatRangeHandler::class)->fields[0], true); + $this->assertSame('number', $float['type']); + $bool = SchemaBuilder::build(DtoCompiler::compile(BoolHandler::class)->fields[0], true); + $this->assertSame('boolean', $bool['type']); + $date = SchemaBuilder::build(DtoCompiler::compile(DateHintHandler::class)->fields[0], true); + $this->assertSame('string', $date['type']); + $this->assertArrayNotHasKey('format', $date); + } + + public function testImportDropsNonStringsAndReindexes(): void + { + $export = DtoCompiler::compile(ListUsersHandler::class)->export(); + $export['contentTypes'] = [0 => MediaTypes::JSON, 2 => MediaTypes::FORM]; + $export['files'] = [0 => '/tmp/a.php', 1 => 5, 2 => '/tmp/b.php']; + $imported = DtoMetadata::import($export); + $this->assertSame([MediaTypes::JSON, MediaTypes::FORM], $imported->contentTypes); + $this->assertTrue(array_is_list($imported->contentTypes)); + $this->assertSame(['/tmp/a.php', '/tmp/b.php'], $imported->files); + } + + public function testEnumRoundTripRejectsAForeignMarker(): void + { + $restored = ValueExport::import(['__netteApi' => 'enum', 'class' => Priority::class, 'value' => 2]); + $this->assertSame(Priority::High, $restored); + $notAnEnum = ValueExport::import(['__netteApi' => 'other', 'class' => Priority::class, 'value' => 2]); + $this->assertIsArray($notAnEnum); + } + + public function testEndpointMessagesUseTheRealUrl(): void + { + $this->assertSame('v1/users', EndpointTemplate::normalize('/api/v1/users/', '1')); + foreach (['v1/x{id}', 'v1/{id}x'] as $url) { + try { + EndpointTemplate::assert($url, [], 'Handler'); + $this->fail($url); + } catch (\LogicException $exception) { + $this->assertStringContainsString($url, $exception->getMessage()); + } + } + try { + EndpointTemplate::assert('v1/users/{id}/', [], 'Handler'); + $this->fail('slash'); + } catch (\LogicException $exception) { + $this->assertStringContainsString("endpoint URL 'v1/users/{id}'", $exception->getMessage()); + $this->assertStringNotContainsString("endpoint URL 'v1/users/{id}/'", $exception->getMessage()); + } + try { + EndpointTemplate::assert('v1/{id}/x/{id}/y/{id}/', ['id'], 'Handler'); + $this->fail('duplicate'); + } catch (\LogicException $exception) { + $this->assertStringContainsString('repeats {id}.', $exception->getMessage()); + $this->assertStringContainsString("endpoint URL 'v1/{id}/x/{id}/y/{id}'", $exception->getMessage()); + } + try { + EndpointTemplate::assert('v1/users/{id-1}/', [], 'Handler'); + $this->fail('malformed'); + } catch (\LogicException $exception) { + $this->assertStringContainsString("endpoint URL 'v1/users/{id-1}'", $exception->getMessage()); + $this->assertStringNotContainsString('{id-1}/', $exception->getMessage()); + } + EndpointTemplate::assertDisjoint(['GET' => ['v1/static', 'v1/users/{id}', 'v1/orders/{id}']]); + try { + EndpointTemplate::assertDisjoint(['GET' => ['v1/users/{id}/', 'v1/users/{slug}/']]); + $this->fail('overlap'); + } catch (\LogicException $exception) { + $this->assertStringContainsString("endpoints 'v1/users/{id}' and 'v1/users/{slug}'", $exception->getMessage()); + } + } + + public function testContainerKeepsTypedHandlersAfterAPlainOneAndRejectsOverlap(): void + { + $container = ContainerFactory::create(<<<'NEON' +services: + listUsers: Tomaj\NetteApi\Test\Input\Fixtures\ListUsersHandler +api: + endpoints: + - {method: GET, version: 1, package: ping, handler: Tomaj\NetteApi\Handlers\AlwaysOkHandler} + - {method: GET, version: 1, package: people, action: list, handler: @listUsers} + - {method: POST, version: 1, package: notes, handler: \Tomaj\NetteApi\Test\Input\Fixtures\Separate\NoteHandler()} +NEON); + $container->initialize(); + $this->assertTrue(DtoMetadataRegistry::installs(ListUsersHandler::class)); + $this->assertTrue(DtoMetadataRegistry::installs(NoteHandler::class)); + $this->assertInstanceOf(AlwaysOkHandler::class, $container->getByType(AlwaysOkHandler::class)); + + $compiler = new Compiler(); + $compiler->addExtension('api', new NetteApiExtension()); + $compiler->addConfig([ + 'api' => [ + 'endpoints' => [[ + 'method' => 'POST', + 'version' => 1, + 'package' => 'notes', + 'handler' => NoteHandler::class, + ]], + ], + ]); + $compiler->compile(); + $this->assertStringContainsString('NoteInput.php', serialize($compiler->exportDependencies())); + + $this->expectException(\LogicException::class); + $this->expectExceptionMessage('can match the same request'); + ContainerFactory::create(<<<'NEON' +api: + endpoints: + - {method: GET, version: 1, package: users, action: '{id}', handler: Tomaj\NetteApi\Test\Input\IdOnlyHandler} + - {method: GET, version: 1, package: users, action: '{slug}', handler: Tomaj\NetteApi\Test\Input\SlugOnlyHandler} +NEON); + } + + public function testWrongConstraintHintsAndFileListTypes(): void + { + $this->assertCompileFails(BadFileListHandler::class, 'list'); + $this->assertCompileFails(PatternOnIntHandler::class, 'Use it on a string.'); + $this->assertCompileFails(EmailOnIntHandler::class, 'Use it on a string.'); + $this->assertCompileFails(LengthOnIntHandler::class, 'Use it on string (characters) or a list (items).'); + $this->assertCompileFails(RangeOnStringPinHandler::class, 'Use it on int or float.'); + DtoCompiler::compile(NullRangeHandler::class); + $statuses = DtoCompiler::compile(StatusListHandler::class)->fields[0]->item; + $this->assertInstanceOf(Field::class, $statuses); + $this->assertFalse($statuses->enumInt); + $schema = DtoCompiler::compile(FormatOnlyHandler::class)->fields[0]->casterSchema; + $this->assertIsArray($schema); + $this->assertSame('string', $schema['type']); + $this->assertSame('date', $schema['format']); + DtoCompiler::compile(GoodListCasterHandler::class); + DtoCompiler::compile(SeesItselfHandler::class); + $this->assertCompileFails(FileListHandler::class, 'Uploads are read only on the root DTO'); + } + + public function testConstraintAndBodyErrorsStayOnTheirFields(): void + { + $_GET = []; + RequestInput::reset(); + $ok = new ListUsersHandler()->params()[0]->validate(); + $this->assertInstanceOf(ValidationResult::class, $ok); + + RequestInput::reset(); + $_GET = ['page' => '1a', 'limit' => '0']; + $errors = $this->errors(new ListUsersHandler()); + $this->assertSame(['Value must be an integer'], $errors['page']); + $this->assertSame(['Value must be between 1 and 100'], $errors['limit']); + + RequestInput::reset(); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + RequestInput::setRawBody('{"customerEmail":'); + $bodyErrors = []; + foreach (new CreateOrderHandler()->params() as $param) { + $result = $param->validate(); + if (!$result->isOk()) { + $bodyErrors[$param->getKey()] = $result->getErrors(); + } + } + $this->assertArrayHasKey('body', $bodyErrors['customerEmail']); + $this->assertArrayNotHasKey('body', $bodyErrors['address'] ?? []); + + RequestInput::reset(); + RequestInput::reset(); + $_GET = ['page' => '1a']; + $both = $this->errors(new QueryThenBodyHandler()); + $this->assertArrayHasKey('page', $both); + $this->assertArrayHasKey('email', $both); + + RequestInput::reset(); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_POST = []; + RequestInput::setRawBody(''); + $emptyBody = $this->errors(new CreateOrderHandler()); + $this->assertArrayHasKey('customerEmail', $emptyBody); + $this->assertArrayNotHasKey('body', $emptyBody); + + RequestInput::reset(); + $_SERVER['REQUEST_METHOD'] = 'GET'; + $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; + $_POST = ['customerEmail' => 'ada@example.com', 'address' => ['street' => 'Main 1', 'postalCode' => '81101'], 'items' => [['sku' => 'A', 'quantity' => 1]]]; + RequestInput::setRawBody(''); + $this->assertSame('ada@example.com', $this->payload(new CreateOrderHandler())['email']); + + $_GET = ['name' => 'ab']; + $_SERVER['REQUEST_METHOD'] = 'GET'; + unset($_SERVER['CONTENT_TYPE']); + $length = $this->errors(new TwoConstraintHandler()); + $this->assertCount(2, $length['name']); + } + + public function testGeneratedParamsExposeDefaultEnumAndExamples(): void + { + $params = new ListUsersHandler()->params(); + $this->assertSame(1, $params[0]->getDefault()); + $values = $params[2]->getAvailableValues(); + $this->assertIsArray($values); + $this->assertContains('active', $values); + $this->assertContains('disabled', $values); + $this->assertTrue($params[0]->validate()->isOk()); + $examples = new TwoExampleParamHandler()->params()[0]->getExamples(); + $this->assertCount(2, $examples); + $this->assertArrayHasKey('one', $examples); + $this->assertArrayHasKey('two', $examples); + } + + /** + * @return array + */ + private function payload(object $handler): array + { + $processor = new ParamsProcessor($handler->params()); + $this->assertFalse($processor->isError(), (string) json_encode($processor->getErrors())); + + return $handler->handle($processor->getValues())->getPayload(); + } + + /** + * @return array> + */ + private function errors(object $handler): array + { + $processor = new ParamsProcessor($handler->params()); + $this->assertTrue($processor->isError()); + + return $processor->getErrors(); + } + + private function assertCompileFails(string $handler, string $needle): void + { + try { + DtoCompiler::compile($handler); + $this->fail($handler); + } catch (\LogicException $exception) { + $this->assertStringContainsString($needle, $exception->getMessage(), $handler); + } + } +} + +final readonly class QueryThenBodyInput +{ + public function __construct( + #[Query] public int $page, + #[Body] public string $email, + ) { + } +} + +final class QueryThenBodyHandler extends TypedHandler +{ + public function handleDto(QueryThenBodyInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final class MissingDtoHandler extends TypedHandler +{ + public function handleDto(Nope $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class UnionPlainInput +{ + public function __construct(#[Query] public string $name) + { + } +} + +final class UnionReturnHandler extends TypedHandler +{ + public function handleDto(UnionPlainInput $input): ResponseInterface|\stdClass + { + return new JsonApiResponse(200, []); + } +} + +final readonly class CycleLeft +{ + public function __construct(#[Body] public CycleRight $right) + { + } +} + +final readonly class CycleRight +{ + public function __construct(#[Body] public CycleLeft $left) + { + } +} + +final class CycleLeftHandler extends TypedHandler +{ + public function handleDto(CycleLeft $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class NullableIntInput +{ + public function __construct(#[Query] public int|null $page = null) + { + } +} + +final class NullableIntHandler extends TypedHandler +{ + public function handleDto(NullableIntInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +readonly class PinBase +{ + public function __construct(#[Body] private string $name) + { + } +} + +final readonly class ChildPin extends PinBase +{ + public function __construct(#[Body] public parent $item) + { + parent::__construct('x'); + } +} + +final readonly class StringChildInput extends PinBase +{ + public function __construct(#[Query] public string $name) + { + parent::__construct('x'); + } +} + +final class StringChildHandler extends TypedHandler +{ + public function handleDto(StringChildInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final class ChildPinHandler extends TypedHandler +{ + public function handleDto(ChildPin $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +#[\Attribute(\Attribute::TARGET_PROPERTY)] +final class BoomAttribute +{ + public function __construct() + { + throw new \RuntimeException('boom'); + } +} + +final readonly class BoomThenQueryInput +{ + public function __construct( + #[BoomAttribute] + #[Query] + public string $name, + ) { + } +} + +final class BoomThenQueryHandler extends TypedHandler +{ + public function handleDto(BoomThenQueryInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class VarListInput +{ + public function __construct( + #[Query] + /** @var list */ + public array $columns, + ) { + } +} + +final class VarListHandler extends TypedHandler +{ + public function handleDto(VarListInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class PriorityListInput +{ + /** @param list $priorities */ + public function __construct(#[Query] public array $priorities) + { + } +} + +final class PriorityListHandler extends TypedHandler +{ + public function handleDto(PriorityListInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class QueryItemInput +{ + public function __construct(#[Query] public string $name) + { + } +} + +final readonly class ParentQueryListInput +{ + /** @param list $items */ + public function __construct(#[Body] public array $items) + { + } +} + +final class ParentQueryListHandler extends TypedHandler +{ + public function handleDto(ParentQueryListInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class UnknownListItemInput +{ + /** @param list $items */ + public function __construct(#[Query] public array $items) + { + } +} + +final class UnknownListItemHandler extends TypedHandler +{ + public function handleDto(UnknownListItemInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class FloatRangeInput +{ + public function __construct(#[Query] #[Range(min: 0.5, max: 2.5)] public float $ratio = 1.0) + { + } +} + +final class FloatRangeHandler extends TypedHandler +{ + public function handleDto(FloatRangeInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class StringLengthInput +{ + public function __construct(#[Query] #[Length(min: 1, max: 3)] public string $name = 'ab') + { + } +} + +final class StringLengthHandler extends TypedHandler +{ + public function handleDto(StringLengthInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class PatternPinInput +{ + public function __construct(#[Query] #[Pattern('/^a+$/')] public string $name = 'a') + { + } +} + +final class PatternHandler extends TypedHandler +{ + public function handleDto(PatternPinInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class EmailPinInput +{ + public function __construct(#[Query] #[Email] public string $email = 'a@b.c') + { + } +} + +final class EmailHandler extends TypedHandler +{ + public function handleDto(EmailPinInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BoolPinInput +{ + public function __construct(#[Query] public bool $flag = false) + { + } +} + +final class BoolHandler extends TypedHandler +{ + public function handleDto(BoolPinInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final class IntForString implements CasterInterface +{ + public function cast(mixed $value): int + { + return 1; + } +} + +final readonly class IntCasterInput +{ + public function __construct(#[Query] #[Cast(IntForString::class)] public string $name) + { + } +} + +final class IntCasterHandler extends TypedHandler +{ + public function handleDto(IntCasterInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +abstract class AbstractCaster implements CasterInterface +{ + public function cast(mixed $value): string + { + return ''; + } +} + +final readonly class AbstractCasterInput +{ + public function __construct(#[Query] #[Cast(AbstractCaster::class)] public string $name) + { + } +} + +final class AbstractCasterHandler extends TypedHandler +{ + public function handleDto(AbstractCasterInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final class ExtraSchemaCaster implements CasterInterface, OpenApiCasterInterface +{ + public function cast(mixed $value): string + { + return is_string($value) ? $value : ''; + } + + public function openApiSchema(): array + { + return ['type' => 'string', 'minLength' => 1]; + } +} + +final readonly class ExtraSchemaInput +{ + public function __construct(#[Query] #[Cast(ExtraSchemaCaster::class)] public string $name) + { + } +} + +final class ExtraSchemaHandler extends TypedHandler +{ + public function handleDto(ExtraSchemaInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final class NullableReturnCaster implements CasterInterface +{ + public function cast(mixed $value): ?string + { + return is_string($value) ? $value : null; + } +} + +final readonly class NullableReturnCasterInput +{ + public function __construct(#[Query] #[Cast(NullableReturnCaster::class)] public string $name) + { + } +} + +final class NullableReturnCasterHandler extends TypedHandler +{ + public function handleDto(NullableReturnCasterInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final class ListDocCaster implements CasterInterface +{ + public function cast(mixed $value): array + { + return []; + } +} + +final readonly class ListDocCasterInput +{ + /** @param list $columns */ + public function __construct(#[Query] #[Cast(ListDocCaster::class)] public array $columns) + { + } +} + +final class ListDocCasterHandler extends TypedHandler +{ + public function handleDto(ListDocCasterInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class DateHintInput +{ + public function __construct(#[Query] #[Cast(DateFormat::class, 'd.m.Y')] public \DateTimeImmutable $day) + { + } +} + +final class DateHintHandler extends TypedHandler +{ + public function handleDto(DateHintInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final class EmptyHintCaster implements CasterInterface, OpenApiCasterInterface +{ + public function cast(mixed $value): string + { + return is_string($value) ? $value : ''; + } + + public function openApiSchema(): array + { + return []; + } +} + +final readonly class EmptyHintInput +{ + public function __construct(#[Query] #[Cast(EmptyHintCaster::class)] public string $name = 'a') + { + } +} + +final class EmptyHintHandler extends TypedHandler +{ + public function handleDto(EmptyHintInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final class PlainStringCaster implements CasterInterface +{ + public function cast(mixed $value): string + { + return is_string($value) ? $value : ''; + } +} + +final readonly class PlainCasterInput +{ + public function __construct(#[Query] #[Cast(PlainStringCaster::class)] public string $name = 'a') + { + } +} + +final class PlainCasterHandler extends TypedHandler +{ + public function handleDto(PlainCasterInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class NestedUploadInput +{ + public function __construct(#[File] public FileUpload $avatar) + { + } +} + +final readonly class NestedFileInput +{ + public function __construct(#[Body] public NestedUploadInput $upload) + { + } +} + +final class NestedFileHandler extends TypedHandler +{ + public function handleDto(NestedFileInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class TwoExampleParamInput +{ + public function __construct(#[Query(examples: ['one' => 1, 'two' => 2])] public int $page = 1) + { + } +} + +final class TwoExampleParamHandler extends TypedHandler +{ + public function handleDto(TwoExampleParamInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class IdOnlyInput +{ + public function __construct(#[Path] public string $id) + { + } +} + +final class IdOnlyHandler extends TypedHandler +{ + public function handleDto(IdOnlyInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class SlugOnlyInput +{ + public function __construct(#[Path] public string $slug) + { + } +} + +final class SlugOnlyHandler extends TypedHandler +{ + public function handleDto(SlugOnlyInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class RangeOnStringPinInput +{ + public function __construct(#[Query] #[Range(min: 1)] public string $name) + { + } +} + +final class RangeOnStringPinHandler extends TypedHandler +{ + public function handleDto(RangeOnStringPinInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BadFileListInput +{ + /** @param list $files */ + public function __construct(#[File] public array $files) + { + } +} + +final class BadFileListHandler extends TypedHandler +{ + public function handleDto(BadFileListInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class PatternOnIntInput +{ + public function __construct(#[Query] #[Pattern('/^1$/')] public int $page) + { + } +} + +final class PatternOnIntHandler extends TypedHandler +{ + public function handleDto(PatternOnIntInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class EmailOnIntInput +{ + public function __construct(#[Query] #[Email] public int $page) + { + } +} + +final class EmailOnIntHandler extends TypedHandler +{ + public function handleDto(EmailOnIntInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class LengthOnIntInput +{ + public function __construct(#[Query] #[Length(min: 1)] public int $page) + { + } +} + +final class LengthOnIntHandler extends TypedHandler +{ + public function handleDto(LengthOnIntInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class NullRangeInput +{ + public function __construct(#[Query] #[Range(min: 1)] public ?int $page = null) + { + } +} + +final class NullRangeHandler extends TypedHandler +{ + public function handleDto(NullRangeInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class StatusListInput +{ + /** @param list $statuses */ + public function __construct(#[Query] public array $statuses) + { + } +} + +final class StatusListHandler extends TypedHandler +{ + public function handleDto(StatusListInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final class FormatOnlyCaster implements CasterInterface, OpenApiCasterInterface +{ + public function cast(mixed $value): string + { + return is_string($value) ? $value : ''; + } + + public function openApiSchema(): array + { + return ['format' => 'date']; + } +} + +final readonly class FormatOnlyInput +{ + public function __construct(#[Query] #[Cast(FormatOnlyCaster::class)] public string $name = 'a') + { + } +} + +final class FormatOnlyHandler extends TypedHandler +{ + public function handleDto(FormatOnlyInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final class GoodListCaster implements CasterInterface +{ + /** @return list */ + public function cast(mixed $value): array + { + return []; + } +} + +final readonly class GoodListCasterInput +{ + /** @param list $columns */ + public function __construct(#[Query] #[Cast(GoodListCaster::class)] public array $columns = []) + { + } +} + +final class GoodListCasterHandler extends TypedHandler +{ + public function handleDto(GoodListCasterInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +#[\Attribute(\Attribute::TARGET_PROPERTY)] +final class SeesItself implements ConstraintInterface +{ + public function validate(mixed $value, ConstraintContext $context): ?string + { + return $context->value('page') === 1 ? null : 'sibling missing'; + } +} + +final readonly class SeesItselfInput +{ + public function __construct(#[Query] #[SeesItself] public int $page = 1) + { + } +} + +final class SeesItselfHandler extends TypedHandler +{ + public function handleDto(SeesItselfInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class FileListInput +{ + /** @param list $uploads */ + public function __construct(#[Body] public array $uploads) + { + } +} + +final class FileListHandler extends TypedHandler +{ + public function handleDto(FileListInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class TwoConstraintInput +{ + public function __construct( + #[Query] + #[Length(min: 3)] + #[Pattern('/^z+$/')] + public string $name, + ) { + } +} + +final class TwoConstraintHandler extends TypedHandler +{ + public function handleDto(TwoConstraintInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} diff --git a/tests/Input/ConstraintTest.php b/tests/Input/ConstraintTest.php new file mode 100644 index 000000000..53bcfc589 --- /dev/null +++ b/tests/Input/ConstraintTest.php @@ -0,0 +1,121 @@ +context = new ConstraintContext('page', 'Dto', ['page', 'name'], ['page' => 1, 'name' => 'ada']); + } + + public function testRangeBounds(): void + { + $both = new Range(min: 1, max: 10); + $this->assertNull($both->validate(1, $this->context)); + $this->assertNull($both->validate(10, $this->context)); + $this->assertSame('Value must be between 1 and 10', $both->validate(0, $this->context)); + $this->assertSame('Value must be between 1 and 10', $both->validate(11, $this->context)); + $this->assertSame('Value must be at least 1', new Range(min: 1)->validate(0, $this->context)); + $this->assertSame('Value must be at most 10', new Range(max: 10)->validate(11, $this->context)); + $this->assertSame('Range applies to an integer or a float', $both->validate('1', $this->context)); + $this->assertNull(new Range(min: 1.5, max: 2.5)->validate(1.5, $this->context)); + $this->assertSame('Value must be between 1.5 and 2.5', new Range(min: 1.5, max: 2.5)->validate(3, $this->context)); + } + + public function testRangeConstructorRejectsEmptyAndInvertedBounds(): void + { + try { + new Range(); + $this->fail('empty range'); + } catch (\InvalidArgumentException $exception) { + $this->assertStringContainsString('min, max or both', $exception->getMessage()); + } + $this->expectException(\InvalidArgumentException::class); + new Range(min: 5, max: 1); + } + + public function testLengthCountsCharactersAndItems(): void + { + $text = new Length(min: 1, max: 3); + $this->assertNull($text->validate('áé', $this->context)); + $this->assertSame('Value must have between 1 and 3 characters', $text->validate('', $this->context)); + $this->assertSame('Value must have between 1 and 3 characters', $text->validate('abcd', $this->context)); + $this->assertSame('Value must have at least 2 characters', new Length(min: 2)->validate('a', $this->context)); + $this->assertSame('Value must have at most 2 items', new Length(max: 2)->validate([1, 2, 3], $this->context)); + $this->assertNull(new Length(min: 1, max: 2)->validate([1], $this->context)); + $this->assertSame('Value must have between 1 and 2 items', new Length(min: 1, max: 2)->validate([], $this->context)); + $this->assertSame('Length applies to a string or a list', $text->validate(1, $this->context)); + } + + public function testLengthConstructorRejectsBadBounds(): void + { + try { + new Length(); + $this->fail('empty'); + } catch (\InvalidArgumentException $exception) { + $this->assertStringContainsString('min, max or both', $exception->getMessage()); + } + try { + new Length(min: -1); + $this->fail('negative'); + } catch (\InvalidArgumentException $exception) { + $this->assertStringContainsString('zero or greater', $exception->getMessage()); + } + $this->expectException(\InvalidArgumentException::class); + new Length(min: 4, max: 1); + } + + public function testPatternAndEmail(): void + { + $pattern = new Pattern('/^[0-9]{5}$/'); + $this->assertSame('^[0-9]{5}$', $pattern->expression()); + $this->assertNull($pattern->validate('81101', $this->context)); + $this->assertSame('Value must match the pattern /^[0-9]{5}$/', $pattern->validate('abc', $this->context)); + $this->assertSame('Pattern applies to a string', $pattern->validate(81101, $this->context)); + + $email = new Email(); + $this->assertNull($email->validate('ada@example.com', $this->context)); + $this->assertSame('Email must be a valid email address', $email->validate('nope', $this->context)); + $this->assertSame('Email must be a valid email address', $email->validate(1, $this->context)); + } + + public function testPatternDollarDoesNotAcceptATrailingNewline(): void + { + $pattern = new Pattern('/^[0-9]{5}$/'); + $this->assertSame('Value must match the pattern /^[0-9]{5}$/', $pattern->validate("81101\n", $this->context)); + $this->assertNull(new Pattern('/^[0-9]{5}$/D')->validate('81101', $this->context)); + $this->assertNull(new Pattern('/^a$/m')->validate("a\nb", $this->context), 'the m flag keeps its meaning'); + } + + public function testPatternConstructorRejectsInvalidRegex(): void + { + $this->expectException(\InvalidArgumentException::class); + new Pattern('/['); + } + + public function testContextReadsSiblingsAndRejectsUnknownNames(): void + { + $this->assertSame('ada', $this->context->value('name')); + $this->assertNull($this->context->value('page') === 1 ? null : 'x'); + $this->assertSame(1, $this->context->value('page')); + $missing = new ConstraintContext('endsAt', 'Schedule', ['startsAt', 'endsAt'], ['endsAt' => 1]); + $this->assertNull($missing->value('startsAt')); + $this->assertSame('endsAt', $missing->path); + $this->assertSame('Schedule', $missing->dtoClass); + + $this->expectException(\LogicException::class); + $this->context->value('nope'); + } +} diff --git a/tests/Input/DtoCompilerTest.php b/tests/Input/DtoCompilerTest.php new file mode 100644 index 000000000..f09d27b57 --- /dev/null +++ b/tests/Input/DtoCompilerTest.php @@ -0,0 +1,454 @@ + + */ + public static function invalidHandlers(): \Iterator + { + yield 'missing method' => [MissingMethodHandler::class, 'must implement public function handleDto']; + yield 'two parameters' => [TwoParameterHandler::class, 'exactly one parameter']; + yield 'nullable parameter' => [NullableDtoHandler::class, 'non-nullable DTO']; + yield 'no return type' => [NoReturnHandler::class, 'must return']; + yield 'not a dto class' => [ScalarHandler::class, 'type-hinted with the DTO class']; + yield 'no source' => [NoSourceHandler::class, 'no source attribute']; + yield 'two sources' => [TwoSourceHandler::class, 'more than one source']; + yield 'union' => [UnionHandler::class, 'not a union']; + yield 'mixed' => [MixedHandler::class, 'no contract to validate']; + yield 'untyped array' => [UntypedArrayHandler::class, 'without an item type']; + yield 'associative array' => [AssociativeArrayHandler::class, 'not a list']; + yield 'nullable path' => [NullablePathHandler::class, 'cannot be nullable']; + yield 'path default' => [DefaultPathHandler::class, 'cannot have a default']; + yield 'file type' => [BadFileHandler::class, 'Use FileUpload']; + yield 'nested query' => [NestedQueryHandler::class, 'Nested properties are part of the body']; + yield 'bad name' => [BadNameHandler::class, 'Dots and brackets']; + yield 'duplicate name' => [DuplicateNameHandler::class, 'both use the external name']; + yield 'range on string' => [RangeOnStringHandler::class, 'does not apply to string']; + yield 'bad default' => [BadDefaultHandler::class, 'default does not satisfy']; + yield 'unknown caster' => [UnknownCasterHandler::class, 'does not exist']; + yield 'json only file' => [JsonFileHandler::class, 'multipart/form-data']; + yield 'unknown consumes' => [CsvConsumesHandler::class, 'cannot read']; + yield 'duplicate consumes' => [DuplicateConsumesHandler::class, 'twice']; + yield 'not readonly' => [WritableHandler::class, 'must be readonly']; + yield 'empty dto' => [EmptyDtoHandler::class, 'needs a constructor']; + yield 'empty examples' => [ListExamplesHandler::class, 'must be a map']; + yield 'cycle' => [CycleHandler::class, 'refers to itself']; + } + + /** + * @param class-string $handler + */ + #[DataProvider('invalidHandlers')] + public function testCompileTimeMessage(string $handler, string $needle): void + { + $this->expectException(\LogicException::class); + $this->expectExceptionMessage($needle); + DtoCompiler::compile($handler); + } + + public function testMissingClass(): void + { + $this->expectException(\LogicException::class); + DtoCompiler::compile('Missing\\Handler'); + } +} + +final class MissingMethodHandler extends TypedHandler +{ +} + +final readonly class PlainInput +{ + public function __construct(#[Query] public string $name) + { + } +} + +final class TwoParameterHandler extends TypedHandler +{ + public function handleDto(PlainInput $input, string $extra): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final class NullableDtoHandler extends TypedHandler +{ + public function handleDto(?PlainInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final class NoReturnHandler extends TypedHandler +{ + public function handleDto(PlainInput $input): string + { + return ''; + } +} + +final class ScalarHandler extends TypedHandler +{ + public function handleDto(string $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class NoSourceInput +{ + public function __construct(public string $name) + { + } +} + +final class NoSourceHandler extends TypedHandler +{ + public function handleDto(NoSourceInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class TwoSourceInput +{ + public function __construct( + #[Query] + #[Body] + public string $name, + ) { + } +} + +final class TwoSourceHandler extends TypedHandler +{ + public function handleDto(TwoSourceInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class UnionInput +{ + public function __construct(#[Query] public int|string $value) + { + } +} + +final class UnionHandler extends TypedHandler +{ + public function handleDto(UnionInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class MixedInput +{ + public function __construct(#[Query] public mixed $value) + { + } +} + +final class MixedHandler extends TypedHandler +{ + public function handleDto(MixedInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class UntypedArrayInput +{ + public function __construct(#[Query] public array $items) + { + } +} + +final class UntypedArrayHandler extends TypedHandler +{ + public function handleDto(UntypedArrayInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class AssociativeArrayInput +{ + /** @param array $items */ + public function __construct(#[Query] public array $items) + { + } +} + +final class AssociativeArrayHandler extends TypedHandler +{ + public function handleDto(AssociativeArrayInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class NullablePathInput +{ + public function __construct(#[Path] public ?int $id) + { + } +} + +final class NullablePathHandler extends TypedHandler +{ + public function handleDto(NullablePathInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class DefaultPathInput +{ + public function __construct(#[Path] public int $id = 1) + { + } +} + +final class DefaultPathHandler extends TypedHandler +{ + public function handleDto(DefaultPathInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BadFileInput +{ + public function __construct(#[File] public string $avatar) + { + } +} + +final class BadFileHandler extends TypedHandler +{ + public function handleDto(BadFileInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class NestedQueryChild +{ + public function __construct(#[Query] public string $street) + { + } +} + +final readonly class NestedQueryInput +{ + public function __construct(#[Body] public NestedQueryChild $address) + { + } +} + +final class NestedQueryHandler extends TypedHandler +{ + public function handleDto(NestedQueryInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BadNameInput +{ + public function __construct(#[Query('a.b')] public string $name) + { + } +} + +final class BadNameHandler extends TypedHandler +{ + public function handleDto(BadNameInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class DuplicateNameInput +{ + public function __construct( + #[Query('name')] public string $first, + #[Query] public string $name, + ) { + } +} + +final class DuplicateNameHandler extends TypedHandler +{ + public function handleDto(DuplicateNameInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class RangeOnStringInput +{ + public function __construct(#[Query] #[Range(min: 1)] public string $name) + { + } +} + +final class RangeOnStringHandler extends TypedHandler +{ + public function handleDto(RangeOnStringInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BadDefaultInput +{ + public function __construct(#[Query] #[Range(min: 5)] public int $page = 1) + { + } +} + +final class BadDefaultHandler extends TypedHandler +{ + public function handleDto(BadDefaultInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class UnknownCasterInput +{ + public function __construct(#[Query] #[Cast('NotACaster')] public string $value) + { + } +} + +final class UnknownCasterHandler extends TypedHandler +{ + public function handleDto(UnknownCasterInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +#[Consumes('application/json')] +final readonly class JsonFileInput +{ + public function __construct(#[File] public FileUpload $avatar) + { + } +} + +#[Consumes('application/json')] +final class JsonFileHandler extends TypedHandler +{ + public function handleDto(JsonFileInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +#[Consumes('text/csv')] +final class CsvConsumesHandler extends TypedHandler +{ + public function handleDto(PlainForConsumes $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +#[Consumes('application/json', 'application/json')] +final class DuplicateConsumesHandler extends TypedHandler +{ + public function handleDto(PlainForConsumes $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class PlainForConsumes +{ + public function __construct(#[Body] public string $name) + { + } +} + +final class WritableInput +{ + public function __construct(#[Query] public string $name) + { + } +} + +final class WritableHandler extends TypedHandler +{ + public function handleDto(WritableInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class EmptyInput +{ +} + +final class EmptyDtoHandler extends TypedHandler +{ + public function handleDto(EmptyInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class ListExamplesInput +{ + public function __construct(#[Query(examples: ['a', 'b'])] public string $name) + { + } +} + +final class ListExamplesHandler extends TypedHandler +{ + public function handleDto(ListExamplesInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class CycleInput +{ + public function __construct(#[Body] public CycleInput $child) + { + } +} + +final class CycleHandler extends TypedHandler +{ + public function handleDto(CycleInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} diff --git a/tests/Input/DtoHandlerTest.php b/tests/Input/DtoHandlerTest.php new file mode 100644 index 000000000..76faa5528 --- /dev/null +++ b/tests/Input/DtoHandlerTest.php @@ -0,0 +1,340 @@ + 'active', 'priority' => '2', 'remember' => '1']; + $payload = $this->payload(new ListUsersHandler()); + $this->assertSame(['page' => 1, 'limit' => 20, 'status' => 'active', 'priority' => 2, 'remember' => true], $payload); + + $_GET = ['page' => '1a']; + RequestInput::reset(); + $errors = $this->errors(new ListUsersHandler()); + $this->assertSame(['page' => ['Value must be an integer']], $errors); + } + + public function testQueryRejectsLooseBooleanAndEmptyString(): void + { + $_GET = ['remember' => 'yes']; + $this->assertSame(['remember' => ['Value must be a boolean']], $this->errors(new ListUsersHandler())); + + $_GET = ['page' => '']; + RequestInput::reset(); + $this->assertSame(['page' => ['Value must be an integer']], $this->errors(new ListUsersHandler())); + } + + public function testPathHeaderAndQueryTogether(): void + { + $_GET = ['limit' => '10', 'status' => 'disabled']; + $_SERVER['HTTP_X_REQUEST_ID'] = 'req-01'; + PathValues::set(['id' => '42']); + $payload = $this->payload(new UserDetailHandler()); + $this->assertSame(['id' => 42, 'limit' => 10, 'status' => 'disabled', 'requestId' => 'req-01'], $payload); + } + + public function testHeaderLookupIsCaseInsensitiveAndOptional(): void + { + $_SERVER['HTTP_X_REQUEST_ID'] = ''; + PathValues::set(['id' => '7']); + $payload = $this->payload(new UserDetailHandler()); + $this->assertSame('', $payload['requestId']); + + unset($_SERVER['HTTP_X_REQUEST_ID']); + RequestInput::reset(); + PathValues::set(['id' => '7']); + $payload = $this->payload(new UserDetailHandler()); + $this->assertNull($payload['requestId']); + } + + public function testNestedJsonCollectsEveryFieldPath(): void + { + $this->json([ + 'customerEmail' => 'nope', + 'address' => ['street' => '', 'postalCode' => 'abc'], + 'items' => [ + ['sku' => 'BOOK-1', 'quantity' => 2], + ['sku' => 'PEN-2', 'quantity' => 0], + ], + ]); + $this->assertSame([ + 'customerEmail' => ['Email must be a valid email address'], + 'address.street' => ['Value must have between 1 and 120 characters'], + 'address.postalCode' => ['Value must match the pattern /^[0-9]{5}$/'], + 'items[1].quantity' => ['Value must be at least 1'], + ], $this->errors(new CreateOrderHandler())); + } + + public function testJsonSuccessIgnoresUnknownFieldsAndParsesRfc3339(): void + { + $this->json([ + 'customerEmail' => 'ada@example.com', + 'address' => ['street' => 'Main 1', 'postalCode' => '81101', 'extra' => true], + 'items' => [['sku' => 'BOOK-1', 'quantity' => 2]], + 'deliveryAt' => '2026-11-06T14:30:00+01:00', + 'coupon' => 'FREE', + ]); + $payload = $this->payload(new CreateOrderHandler()); + $this->assertSame('ada@example.com', $payload['email']); + $this->assertSame('Main 1', $payload['street']); + $this->assertSame(2, $payload['quantity']); + $this->assertSame('2026-11-06T14:30:00+01:00', $payload['deliveryAt']); + } + + public function testExplicitNullAndMissingNestedObject(): void + { + $this->json([ + 'customerEmail' => 'ada@example.com', + 'address' => null, + 'items' => [['sku' => 'BOOK-1', 'quantity' => 1]], + ]); + $this->assertSame(['address' => ['Value must not be null']], $this->errors(new CreateOrderHandler())); + + $this->json([ + 'customerEmail' => 'ada@example.com', + 'items' => [['sku' => 'BOOK-1', 'quantity' => 1]], + ]); + $this->assertSame(['address' => ['Field is required']], $this->errors(new CreateOrderHandler())); + } + + public function testMalformedJsonUsesTheParserMessage(): void + { + RequestInput::reset(); + RequestInput::setRawBody('{"customerEmail":'); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + $errors = $this->errors(new CreateOrderHandler()); + $this->assertArrayHasKey('body', $errors); + $this->assertStringStartsWith('Syntax error', $errors['body'][0]); + } + + public function testJsonRootMustBeAnObject(): void + { + RequestInput::reset(); + RequestInput::setRawBody('[1]'); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $this->assertSame(['body' => ['Value must be an object']], $this->errors(new CreateOrderHandler())); + } + + public function testFormBracketNotationUsesTheSameRules(): void + { + $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_POST = [ + 'customerEmail' => 'ada@example.com', + 'address' => ['street' => 'Main 1', 'postalCode' => '81101'], + 'items' => [['sku' => 'BOOK-1', 'quantity' => '2']], + ]; + $payload = $this->payload(new CreateOrderHandler()); + $this->assertSame(2, $payload['quantity']); + $this->assertNull($payload['deliveryAt']); + } + + public function testFormDoesNotTreatTheWordNullAsNull(): void + { + $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_POST = [ + 'customerEmail' => 'ada@example.com', + 'address' => ['street' => 'Main 1', 'postalCode' => '81101'], + 'items' => [['sku' => 'BOOK-1', 'quantity' => '2pcs']], + 'deliveryAt' => 'null', + ]; + $errors = $this->errors(new CreateOrderHandler()); + $this->assertSame(['items[0].quantity' => ['Value must be an integer']], ['items[0].quantity' => $errors['items[0].quantity']]); + $this->assertArrayHasKey('deliveryAt', $errors); + } + + public function testPutFormBodyIsParsedFromTheRawBody(): void + { + $_SERVER['REQUEST_METHOD'] = 'PUT'; + $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; + RequestInput::setRawBody('customerEmail=ada%40example.com&address[street]=Main+1&address[postalCode]=81101&items[0][sku]=BOOK-1&items[0][quantity]=2'); + $payload = $this->payload(new CreateOrderHandler()); + $this->assertSame(2, $payload['quantity']); + } + + public function testUnsupportedAndMissingContentType(): void + { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_SERVER['CONTENT_TYPE'] = 'text/csv; charset=utf-8'; + try { + $this->errors(new CreateOrderHandler()); + $this->fail('csv was accepted'); + } catch (UnsupportedMediaTypeException $exception) { + $this->assertSame("Content-Type 'text/csv' is not supported for this endpoint. Use one of: application/json, application/x-www-form-urlencoded.", $exception->getMessage()); + } + + unset($_SERVER['CONTENT_TYPE']); + RequestInput::reset(); + try { + $this->errors(new CreateOrderHandler()); + $this->fail('missing type was accepted'); + } catch (UnsupportedMediaTypeException $exception) { + $this->assertSame('Content-Type is missing. Use one of: application/json, application/x-www-form-urlencoded.', $exception->getMessage()); + } + } + + public function testCharsetOnJsonIsIgnored(): void + { + $this->json([ + 'customerEmail' => 'ada@example.com', + 'address' => ['street' => 'Main 1', 'postalCode' => '81101'], + 'items' => [['sku' => 'BOOK-1', 'quantity' => 1]], + ]); + $_SERVER['CONTENT_TYPE'] = 'Application/JSON; charset=utf-8'; + $this->assertFalse($this->processor(new CreateOrderHandler())->isError()); + } + + public function testTooLongListIsRejectedBeforeItsItemsAreMapped(): void + { + $this->json([ + 'customerEmail' => 'ada@example.com', + 'address' => ['street' => 'Main 1', 'postalCode' => '81101'], + 'items' => array_fill(0, 51, ['sku' => 'BOOK-1', 'quantity' => 'not a number']), + ]); + $this->assertSame(['items' => ['Value must have between 1 and 50 items']], $this->errors(new CreateOrderHandler())); + $this->json([ + 'customerEmail' => 'ada@example.com', + 'address' => ['street' => 'Main 1', 'postalCode' => '81101'], + 'items' => array_fill(0, 50, ['sku' => 'BOOK-1', 'quantity' => 1]), + ]); + $this->assertFalse($this->processor(new CreateOrderHandler())->isError()); + } + + public function testDateCasterThenConstraintMessage(): void + { + $this->json(['issuedOn' => '31.02.2026']); + $this->assertSame(['issuedOn' => ['Date must match d.m.Y, for example 24.12.2026']], $this->errors(new IssueHandler())); + + $this->json(['issuedOn' => '24.12.2026']); + $this->assertSame(['issuedOn' => '2026-12-24'], $this->payload(new IssueHandler())); + } + + public function testSplitCasterOnAQueryList(): void + { + $_GET = ['columns' => 'id,createdAt,total']; + $this->assertSame(['columns' => ['id', 'createdAt', 'total']], $this->payload(new ReportHandler())); + + $_GET = ['columns' => '']; + RequestInput::reset(); + $this->assertSame(['columns' => ['']], $this->payload(new ReportHandler())); + } + + public function testCrossFieldConstraint(): void + { + $this->json([ + 'startsAt' => '2026-11-06T10:00:00Z', + 'endsAt' => '2026-11-06T09:00:00Z', + ]); + $this->assertSame(['endsAt' => ['Must be later than startsAt']], $this->errors(new ScheduleHandler())); + + $this->json([ + 'startsAt' => '2026-11-06T10:00:00Z', + 'endsAt' => '2026-11-06T11:00:00Z', + ]); + $this->assertSame(['ok' => true], $this->payload(new ScheduleHandler())); + } + + public function testSingleAndMultipleUploads(): void + { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_SERVER['CONTENT_TYPE'] = 'multipart/form-data; boundary=x'; + $_POST = ['displayName' => 'Ada']; + $_FILES = ['avatar' => ['name' => 'a.png', 'type' => 'image/png', 'tmp_name' => '/tmp/a', 'error' => UPLOAD_ERR_OK, 'size' => 12]]; + $payload = $this->payload(new AvatarHandler()); + $this->assertSame('a.png', $payload['file']); + $this->assertSame(12, $payload['size']); + $this->assertSame(UPLOAD_ERR_OK, $payload['error']); + + $_POST = []; + $_FILES = ['files' => [ + 'name' => ['a.txt', 'b.txt'], + 'type' => ['text/plain', 'text/plain'], + 'tmp_name' => ['/tmp/a', '/tmp/b'], + 'error' => [UPLOAD_ERR_OK, UPLOAD_ERR_INI_SIZE], + 'size' => [1, 2], + ]]; + RequestInput::reset(); + $payload = $this->payload(new FilesHandler()); + $this->assertSame(2, $payload['count']); + $this->assertSame('a.txt', $payload['name']); + } + + public function testMissingFileIsRequired(): void + { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_SERVER['CONTENT_TYPE'] = 'multipart/form-data'; + $_POST = ['displayName' => 'Ada']; + $this->assertSame(['avatar' => ['Field is required']], $this->errors(new AvatarHandler())); + } + + /** + * @param array $body + */ + private function json(array $body): void + { + RequestInput::reset(); + RequestInput::setRawBody((string) json_encode($body)); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_POST = []; + } + + /** + * @return array + */ + private function payload(object $handler): array + { + $processor = $this->processor($handler); + $this->assertFalse($processor->isError(), (string) json_encode($processor->getErrors())); + $response = $handler->handle($processor->getValues()); + + return $response->getPayload(); + } + + /** + * @return array + */ + private function errors(object $handler): array + { + $processor = $this->processor($handler); + $this->assertTrue($processor->isError()); + + return $processor->getErrors(); + } + + private function processor(object $handler): ParamsProcessor + { + return new ParamsProcessor($handler->params()); + } +} diff --git a/tests/Input/EndpointTemplateTest.php b/tests/Input/EndpointTemplateTest.php new file mode 100644 index 000000000..56e3196e8 --- /dev/null +++ b/tests/Input/EndpointTemplateTest.php @@ -0,0 +1,75 @@ +assertSame(['id' => '42'], EndpointTemplate::match('v1/users/{id}/detail', 'v1/users/42/detail')); + $this->assertSame(['id' => '42'], EndpointTemplate::match('v1/users/{id}/detail/', EndpointTemplate::normalize('/api/v1/users/42/detail?x=1', '1'))); + $this->assertNull(EndpointTemplate::match('v1/users/{id}/detail', 'v1/users/42')); + $this->assertNull(EndpointTemplate::match('v1/users/{id}', 'v1/orders/42')); + $this->assertSame('v1/users/42', EndpointTemplate::normalize('v1/users/42', '1')); + $this->assertNull(EndpointTemplate::normalize('/api/v2/users', '1')); + $this->assertSame(['id'], EndpointTemplate::placeholders('v1/users/{id}/detail')); + $this->assertSame([], EndpointTemplate::placeholders('v1/users/x{id}')); + $this->assertSame([], EndpointTemplate::placeholders('v1/users/{id}x')); + $this->assertNull(EndpointTemplate::match('v1/x{id}', 'v1/99')); + $this->assertNull(EndpointTemplate::match('v1/{id}x', 'v1/99')); + $this->assertNull(EndpointTemplate::match('v1/{id}/detail', 'v1/1/other')); + $this->assertFalse(EndpointTemplate::isComposite("{id}/ detail")); + $this->assertFalse(EndpointTemplate::overlaps('v1/x{id}', 'v1/x{name}')); + $this->assertFalse(EndpointTemplate::overlaps('v1/{id}x', 'v1/{name}x')); + $this->assertSame(['id' => 'x42'], EndpointTemplate::match('v1/users/{id}', 'v1/users/x42')); + $this->assertNull(EndpointTemplate::match('v1/users/{id}/detail', 'prefix/v1/users/42/detail')); + $this->assertTrue(EndpointTemplate::isComposite('{id}/detail')); + $this->assertFalse(EndpointTemplate::isComposite('users/detail')); + $this->assertFalse(EndpointTemplate::isComposite('{id-1}/detail')); + $this->assertFalse(EndpointTemplate::isComposite('{id}/detail ')); + $this->assertNull(EndpointTemplate::normalize('/api/v12/users', '1')); + $this->assertSame('v12/users', EndpointTemplate::normalize('/api/v12/users', '12')); + $this->assertSame('v1', EndpointTemplate::normalize('/v1', '1')); + $this->assertNull(EndpointTemplate::normalize('/api/v1extra', '1')); + } + + public function testAssertNamesTheMismatch(): void + { + EndpointTemplate::assert('v1/users/{id}/detail', ['id'], 'UserDetailHandler'); + + $this->expectException(\LogicException::class); + $this->expectExceptionMessage('UserDetailHandler'); + EndpointTemplate::assert('v1/users/{id}/detail', [], 'UserDetailHandler'); + } + + public function testAssertRejectsRepeatedAndMalformedPlaceholders(): void + { + try { + EndpointTemplate::assert('v1/users/{id}/orders/{id}', ['id'], 'Handler'); + $this->fail('duplicate'); + } catch (\LogicException $exception) { + $this->assertStringContainsString('repeats {id}', $exception->getMessage()); + } + $this->expectException(\LogicException::class); + EndpointTemplate::assert('v1/users/{id-1}', [], 'Handler'); + } + + public function testOverlap(): void + { + $this->assertTrue(EndpointTemplate::overlaps('v1/users/{id}', 'v1/users/{slug}')); + $this->assertFalse(EndpointTemplate::overlaps('v1/users/{id}', 'v1/orders/{id}')); + $this->assertFalse(EndpointTemplate::overlaps('v1/users/{id}', 'v1/users/{id}/detail')); + $this->assertFalse(EndpointTemplate::overlaps('v1/users/list', 'v1/users/{id}')); + $this->assertFalse(EndpointTemplate::overlaps('v1/users/{id}', 'v1/orders/static')); + $this->assertTrue(EndpointTemplate::overlaps('v1/{package}/item', 'v1/users/{id}')); + + EndpointTemplate::assertDisjoint(['GET' => ['v1/users/list', 'v1/users/{id}/detail']]); + $this->expectException(\LogicException::class); + EndpointTemplate::assertDisjoint(['GET' => ['v1/users/{id}', 'v1/users/{slug}']]); + } +} diff --git a/tests/Input/EscapeTest.php b/tests/Input/EscapeTest.php new file mode 100644 index 000000000..aec04ba1e --- /dev/null +++ b/tests/Input/EscapeTest.php @@ -0,0 +1,350 @@ +export(); + $field = $export['fields'][0]; + $field['casterArguments'] = [0 => 'd.m.Y', 2 => 'ignored']; + $imported = Field::import($field); + $this->assertSame([0 => 'd.m.Y', 2 => 'ignored'], $imported->casterArguments, 'keys survive so named caster arguments work'); + $this->assertCount(2, $imported->casterArguments); + $this->assertSame('d.m.Y', $imported->casterArguments[0]); + + $field['enumClass'] = \stdClass::class; + $this->expectException(\LogicException::class); + Field::import($field); + } + + public function testImportedFieldRejectsABadCasterAndConstraint(): void + { + $export = DtoCompiler::compile(ListUsersHandler::class)->export(); + $field = $export['fields'][0]; + $field['casterClass'] = \stdClass::class; + try { + Field::import($field); + $this->fail('caster'); + } catch (\LogicException $exception) { + $this->assertStringContainsString('caster', $exception->getMessage()); + } + + $field = $export['fields'][0]; + $field['property'] = ''; + try { + Field::import($field); + $this->fail('property'); + } catch (\LogicException $exception) { + $this->assertStringContainsString('property', $exception->getMessage()); + } + + $field = $export['fields'][0]; + $field['constraintSpecs'] = [new FakeConstraintSpec()]; + try { + Field::import($field); + $this->fail('constraint shape'); + } catch (\LogicException $exception) { + $this->assertStringContainsString('constraint', $exception->getMessage()); + } + + $field = $export['fields'][0]; + $field['constraintSpecs'] = [['class' => Range::class, 'args' => 'nope']]; + try { + Field::import($field); + $this->fail('constraint args'); + } catch (\LogicException $exception) { + $this->assertStringContainsString('constraint', $exception->getMessage()); + } + + $field = $export['fields'][0]; + $field['constraintSpecs'] = [['class' => \stdClass::class, 'args' => []]]; + try { + Field::import($field); + $this->fail('constraint'); + } catch (\LogicException $exception) { + $this->assertStringContainsString('constraint', $exception->getMessage()); + } + + $field = $export['fields'][3]; + $field['enumValues'] = [1, 1.5]; + try { + Field::import($field); + $this->fail('enum'); + } catch (\LogicException $exception) { + $this->assertStringContainsString('enum values', $exception->getMessage()); + } + } + + public function testRequiredHeaderAndPathAreMissingRatherThanNull(): void + { + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + $errors = $this->errors(new RequiredHeaderHandler()); + $this->assertSame(['Field is required'], $errors['trace']); + + $errors = $this->errors(new RequiredPathHandler()); + $this->assertSame(['Field is required'], $errors['id']); + } + + public function testStringFileIsNotAMissingUpload(): void + { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_SERVER['CONTENT_TYPE'] = 'multipart/form-data'; + $_POST = ['displayName' => 'Ada']; + $_FILES = ['avatar' => 'nope']; + $this->assertSame(['Field is required'], $this->errors(new AvatarHandler())['avatar']); + + RequestInput::reset(); + $_FILES = ['avatar' => ['name' => '', 'type' => '', 'tmp_name' => '', 'error' => \UPLOAD_ERR_OK, 'size' => 1]]; + $this->assertSame('', $this->payload(new AvatarHandler())['file']); + + RequestInput::reset(); + $_FILES = ['avatar' => [ + 'name' => ['a.png', 'b.png'], + 'type' => ['image/png', 'image/png'], + 'tmp_name' => ['/tmp/a', '/tmp/b'], + 'error' => [\UPLOAD_ERR_OK, \UPLOAD_ERR_OK], + 'size' => [1, 2], + ]]; + $this->assertSame(['Value must be a file upload'], $this->errors(new AvatarHandler())['avatar']); + } + + public function testJsonContentTypeCanComeFromTheHttpHeader(): void + { + unset($_SERVER['CONTENT_TYPE']); + $_SERVER['HTTP_CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + RequestInput::setRawBody('{"customerEmail":"ada@example.com","address":{"street":"Main 1","postalCode":"81101"},"items":[{"sku":"A","quantity":1}]}'); + $this->assertSame('ada@example.com', $this->payload(new CreateOrderHandler())['email']); + } + + public function testPostWithAnEmptySuperglobalDoesNotReadTheRawForm(): void + { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; + $_POST = []; + RequestInput::setRawBody('customerEmail=ada%40example.com'); + $this->assertArrayHasKey('customerEmail', $this->errors(new CreateOrderHandler())); + } + + public function testUnknownSourceAttributeIsRejected(): void + { + $compiler = new \ReflectionClass(DtoCompiler::class)->newInstanceWithoutConstructor(); + $method = new \ReflectionMethod(DtoCompiler::class, 'sourceAttribute'); + $this->expectException(\LogicException::class); + $method->invoke($compiler, new \stdClass()); + } + + public function testAMissingNestedFieldDoesNotHideTheNextError(): void + { + RequestInput::setRawBody('{"customerEmail":"ada@example.com","address":{"postalCode":"abc"},"items":[{"sku":"A","quantity":1}]}'); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + $errors = $this->errors(new CreateOrderHandler()); + $this->assertArrayHasKey('address.street', $errors); + $this->assertArrayHasKey('address.postalCode', $errors); + } + + public function testNestedConstraintCanReadASibling(): void + { + RequestInput::setRawBody('{"inner":{"left":"a","right":"b"}}'); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + $this->assertSame('b', $this->payload(new SiblingHandler())['right']); + } + + public function testOpenApiKeepsQueryFieldsOutOfTheBody(): void + { + $body = new RequestBodyBuilder()->build(new OpenApiMixedHandler(), new SchemaRegistry()); + $this->assertIsArray($body); + $this->assertSame(['email'], array_keys($body['content']['application/json']['schema']['properties'])); + $this->assertArrayHasKey('application/json', $body['content']); + + $loose = new RequestBodyBuilder()->build(new LooseBodyHandler(), new SchemaRegistry()); + $this->assertIsArray($loose); + $this->assertSame( + ['application/json', 'application/x-www-form-urlencoded'], + array_keys($loose['content']), + ); + } + + /** + * @return array> + */ + private function errors(object $handler): array + { + $processor = new ParamsProcessor($handler->params()); + $this->assertTrue($processor->isError()); + + return $processor->getErrors(); + } + + /** + * @return array + */ + private function payload(object $handler): array + { + $processor = new ParamsProcessor($handler->params()); + $this->assertFalse($processor->isError(), (string) json_encode($processor->getErrors())); + + return $handler->handle($processor->getValues())->getPayload(); + } +} + +final class RequiredHeaderHandler extends TypedHandler +{ + public function handleDto(RequiredHeaderInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class RequiredHeaderInput +{ + public function __construct(#[Header] public string $trace) + { + } +} + +final class RequiredPathHandler extends TypedHandler +{ + public function handleDto(RequiredPathInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class RequiredPathInput +{ + public function __construct(#[Path] public string $id) + { + } +} + +final readonly class OpenApiMixedInput +{ + public function __construct( + #[Body] public string $email, + #[Query] public int $page = 1, + ) { + } +} + +final class OpenApiMixedHandler extends TypedHandler +{ + public function handleDto(OpenApiMixedInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +#[\Attribute(\Attribute::TARGET_PROPERTY)] +final readonly class ReadsSibling implements ConstraintInterface +{ + public function __construct(private string $other) + { + } + + public function validate(mixed $value, ConstraintContext $context): ?string + { + return is_string($context->value($this->other)) ? null : 'sibling missing'; + } +} + +final readonly class SiblingInner +{ + public function __construct( + #[Body] public string $left, + #[Body] + #[ReadsSibling('left')] + public string $right, + ) { + } +} + +final readonly class SiblingOuter +{ + public function __construct(#[Body] public SiblingInner $inner) + { + } +} + +final class SiblingHandler extends TypedHandler +{ + public function handleDto(SiblingOuter $input): ResponseInterface + { + return new JsonApiResponse(200, ['right' => $input->inner->right]); + } +} + +final class FakeConstraintSpec implements \ArrayAccess +{ + public function offsetExists(mixed $offset): bool + { + return true; + } + + public function offsetGet(mixed $offset): mixed + { + return $offset === 'class' ? Range::class : ['min' => 1]; + } + + public function offsetSet(mixed $offset, mixed $value): void + { + } + + public function offsetUnset(mixed $offset): void + { + } +} + +final class LooseBodyHandler extends BaseHandler +{ + public function params(): array + { + return [ + new BodyInputParam('note')->setOpenApiSchema(['type' => 'string']), + ]; + } + + public function handle(array $params): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} diff --git a/tests/Input/FileUploadTest.php b/tests/Input/FileUploadTest.php new file mode 100644 index 000000000..20e8b6c9e --- /dev/null +++ b/tests/Input/FileUploadTest.php @@ -0,0 +1,380 @@ +assertSame(['multipart/form-data'], array_keys($this->requestBody(new AvatarHandler())['content'])); + $this->assertSame(['application/json', 'multipart/form-data'], array_keys($this->requestBody(new DocumentHandler())['content'])); + } + + public function testUrlEncodedFormIsRejectedWhenTheDtoHasAFile(): void + { + $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; + $_POST = ['displayName' => 'Ada']; + try { + $this->processor(new AvatarHandler())->isError(); + $this->fail('form was accepted'); + } catch (UnsupportedMediaTypeException $exception) { + $this->assertSame("Content-Type 'application/x-www-form-urlencoded' is not supported for this endpoint. Use one of: application/json, multipart/form-data.", $exception->getMessage()); + } + } + + public function testOtherContentTypeIsRejected(): void + { + $_SERVER['CONTENT_TYPE'] = 'text/plain'; + $this->expectException(UnsupportedMediaTypeException::class); + $this->expectExceptionMessage("Content-Type 'text/plain' is not supported for this endpoint. Use one of: application/json, multipart/form-data."); + $this->processor(new AvatarHandler())->isError(); + } + + public function testOpenApiListsFilesOnlyInMultipart(): void + { + $content = $this->requestBody(new AvatarHandler())['content']; + $multipart = $content['multipart/form-data']['schema']; + $this->assertSame(['type' => 'string', 'format' => 'binary', 'description' => 'PNG or JPEG image'], $multipart['properties']['avatar']); + $this->assertSame(['displayName', 'avatar'], $multipart['required']); + $this->assertSame('object', $multipart['type']); + + // optional files: JSON stays advertised, without them + $json = $this->requestBody(new DocumentHandler())['content']['application/json']['schema']; + $this->assertSame(['issuedOn', 'copies'], array_keys($json['properties'])); + $this->assertSame(['issuedOn', 'copies'], $json['required']); + } + + public function testOpenApiFileListIsAnArrayOfBinaries(): void + { + $content = $this->requestBody(new FilesHandler())['content']; + $this->assertSame(['type' => 'array', 'items' => ['type' => 'string', 'format' => 'binary']], $content['multipart/form-data']['schema']['properties']['files']); + $this->assertSame(['files'], $content['multipart/form-data']['schema']['required']); + $this->assertSame(['multipart/form-data'], array_keys($content)); + } + + public function testOpenApiOfARequiredFileListsRequiredFieldsInMultipartOnly(): void + { + $content = $this->requestBody(new ScanFirstHandler())['content']; + $this->assertSame(['multipart/form-data'], array_keys($content)); + $this->assertSame(['scan', 'title'], $content['multipart/form-data']['schema']['required']); + + $_POST = ['title' => 'Invoice']; + $_FILES = ['scan' => self::file('s.pdf', 3)]; + $this->assertSame(['title' => 'Invoice', 'scan' => 's.pdf'], $this->payload(new ScanFirstHandler())); + } + + public function testListEntryWithoutErrorsIsPassedOn(): void + { + $_FILES = ['files' => ['name' => ['a.txt'], 'tmp_name' => ['/tmp/a']]]; + $this->assertSame(['count' => 1, 'name' => 'a.txt'], $this->payload(new FilesHandler())); + + $_FILES = ['files' => ['name' => ['b.txt'], 'error' => []]]; + RequestInput::reset(); + $this->assertSame(['count' => 1, 'name' => 'b.txt'], $this->payload(new FilesHandler())); + } + + public function testListKeepsLaterKeysWhenOneKeyIsMissing(): void + { + $_POST = ['issuedOn' => '24.12.2026', 'copies' => '1']; + $_FILES = ['attachments' => ['name' => ['a.txt'], 'error' => [UPLOAD_ERR_PARTIAL]]]; + $this->assertSame([['a.txt', UPLOAD_ERR_PARTIAL]], $this->payload(new DocumentHandler())['attachments']); + } + + public function testWireConvertsNestedValues(): void + { + $this->assertSame( + ['status' => 'active', 'dates' => ['at' => '2026-01-02T03:04:05+00:00'], 'n' => 1], + SchemaBuilder::wire(['status' => UserStatus::Active, 'dates' => ['at' => new \DateTimeImmutable('2026-01-02T03:04:05Z')], 'n' => 1]), + ); + } + + public function testOpenApiOptionalFilesAreNotRequired(): void + { + $content = $this->requestBody(new DocumentHandler())['content']; + $this->assertSame(['issuedOn', 'copies'], $content['multipart/form-data']['schema']['required']); + $this->assertSame(['issuedOn', 'copies', 'scan', 'attachments'], array_keys($content['multipart/form-data']['schema']['properties'])); + $this->assertSame(['issuedOn', 'copies'], array_keys($content['application/json']['schema']['properties'])); + $this->assertSame(['issuedOn', 'copies'], $content['application/json']['schema']['required']); + } + + public function testSingleRequiredFileWithScalarField(): void + { + $_POST = ['displayName' => 'Ada']; + $_FILES = ['avatar' => self::file('a.png', 12)]; + $payload = $this->payload(new AvatarHandler()); + $this->assertSame(['name' => 'Ada', 'file' => 'a.png', 'size' => 12, 'error' => UPLOAD_ERR_OK, 'type' => 'image/png', 'path' => '/tmp/php-a.png'], $payload); + } + + public function testMissingRequiredFileIs400WithFieldPath(): void + { + $_POST = ['displayName' => 'Ada']; + $this->assertSame(['avatar' => ['Field is required']], $this->errors(new AvatarHandler())); + } + + public function testEmptyFileInputCountsAsMissing(): void + { + $_POST = ['displayName' => 'Ada']; + $_FILES = ['avatar' => ['name' => '', 'type' => '', 'tmp_name' => '', 'error' => UPLOAD_ERR_NO_FILE, 'size' => 0]]; + $this->assertSame(['avatar' => ['Field is required']], $this->errors(new AvatarHandler())); + } + + public function testRequiredFileAndInvalidSiblingReportBothPaths(): void + { + $_POST = ['displayName' => '']; + $this->assertSame(['displayName' => ['Value must have between 1 and 80 characters'], 'avatar' => ['Field is required']], $this->errors(new AvatarHandler())); + } + + public function testJsonRequestToADtoWithARequiredFileExplainsMultipart(): void + { + $_SERVER['CONTENT_TYPE'] = 'application/json'; + RequestInput::setRawBody('{"displayName":"Ada","avatar":"aGVsbG8="}'); + $this->assertSame( + ['avatar' => ['File is required and can only be uploaded as multipart/form-data, but the request is application/json']], + $this->errors(new AvatarHandler()), + ); + } + + public function testMissingContentTypeWithARequiredFileIs415(): void + { + unset($_SERVER['CONTENT_TYPE']); + $this->expectException(UnsupportedMediaTypeException::class); + $this->expectExceptionMessage('Content-Type is missing. Use one of: application/json, multipart/form-data.'); + $this->processor(new FilesHandler())->isError(); + } + + public function testJsonRequestWithOptionalFilesSucceeds(): void + { + $_SERVER['CONTENT_TYPE'] = 'application/json'; + RequestInput::setRawBody('{"issuedOn":"24.12.2026","copies":2}'); + $this->assertSame(['issuedOn' => '2026-12-24', 'copies' => 2, 'scan' => null, 'attachments' => []], $this->payload(new DocumentHandler())); + } + + public function testOptionalFileMissingAndCastAndConstraintOnSiblings(): void + { + $_POST = ['issuedOn' => '24.12.2026', 'copies' => '3']; + $this->assertSame(['issuedOn' => '2026-12-24', 'copies' => 3, 'scan' => null, 'attachments' => []], $this->payload(new DocumentHandler())); + + $_POST = ['issuedOn' => '31.02.2026', 'copies' => '11']; + $_FILES = ['scan' => self::file('s.pdf', 5)]; + RequestInput::reset(); + $this->assertSame([ + 'issuedOn' => ['Date must match d.m.Y, for example 24.12.2026'], + 'copies' => ['Value must be between 1 and 10'], + ], $this->errors(new DocumentHandler())); + + $_POST = ['issuedOn' => '24.12.2026', 'copies' => '1a']; + RequestInput::reset(); + $this->assertSame(['copies' => ['Value must be an integer']], $this->errors(new DocumentHandler())); + } + + public function testOptionalFileAndListTogether(): void + { + $_POST = ['issuedOn' => '24.12.2026', 'copies' => '1']; + $_FILES = [ + 'scan' => self::file('s.pdf', 5), + 'attachments' => self::files(['a.txt', 'b.txt'], [UPLOAD_ERR_OK, UPLOAD_ERR_OK]), + ]; + $this->assertSame( + ['issuedOn' => '2026-12-24', 'copies' => 1, 'scan' => 's.pdf', 'attachments' => [['a.txt', UPLOAD_ERR_OK], ['b.txt', UPLOAD_ERR_OK]]], + $this->payload(new DocumentHandler()), + ); + } + + public function testListWithOnlyEmptySlotsCountsAsMissing(): void + { + $_FILES = ['files' => self::files(['', ''], [UPLOAD_ERR_NO_FILE, UPLOAD_ERR_NO_FILE])]; + $this->assertSame(['files' => ['Field is required']], $this->errors(new FilesHandler())); + + $_POST = ['issuedOn' => '24.12.2026', 'copies' => '1']; + $_FILES = ['attachments' => self::files([''], [UPLOAD_ERR_NO_FILE])]; + RequestInput::reset(); + $this->assertSame([], $this->payload(new DocumentHandler())['attachments']); + } + + public function testListWithOneFileIsAList(): void + { + $_FILES = ['files' => self::file('only.txt', 1)]; + $this->assertSame(['count' => 1, 'name' => 'only.txt'], $this->payload(new FilesHandler())); + } + + public function testListKeepsAMixOfEmptyAndRealSlots(): void + { + $_POST = ['issuedOn' => '24.12.2026', 'copies' => '1']; + $_FILES = ['attachments' => self::files(['', 'b.txt'], [UPLOAD_ERR_NO_FILE, UPLOAD_ERR_OK])]; + $this->assertSame([['', UPLOAD_ERR_NO_FILE], ['b.txt', UPLOAD_ERR_OK]], $this->payload(new DocumentHandler())['attachments']); + } + + /** + * @return iterable + */ + public static function uploadErrors(): iterable + { + yield 'ini size' => [UPLOAD_ERR_INI_SIZE]; + yield 'form size' => [UPLOAD_ERR_FORM_SIZE]; + yield 'partial' => [UPLOAD_ERR_PARTIAL]; + yield 'no tmp dir' => [UPLOAD_ERR_NO_TMP_DIR]; + yield 'cant write' => [UPLOAD_ERR_CANT_WRITE]; + yield 'extension' => [UPLOAD_ERR_EXTENSION]; + } + + #[DataProvider('uploadErrors')] + public function testUploadErrorsReachTheHandler(int $error): void + { + $_POST = ['displayName' => 'Ada']; + $_FILES = ['avatar' => ['name' => 'big.png', 'type' => 'image/png', 'tmp_name' => '', 'error' => $error, 'size' => 0]]; + $payload = $this->payload(new AvatarHandler()); + $this->assertSame($error, $payload['error']); + $this->assertSame('big.png', $payload['file']); + } + + public function testNoFileErrorWithANameIsPassedOn(): void + { + $_POST = ['displayName' => 'Ada']; + $_FILES = ['avatar' => ['name' => 'x.png', 'error' => UPLOAD_ERR_NO_FILE]]; + $this->assertSame(UPLOAD_ERR_NO_FILE, $this->payload(new AvatarHandler())['error']); + } + + public function testUploadErrorInsideAList(): void + { + $_FILES = ['files' => self::files(['a.txt', 'b.txt'], [UPLOAD_ERR_OK, UPLOAD_ERR_PARTIAL])]; + $this->assertSame(['count' => 2, 'name' => 'a.txt'], $this->payload(new FilesHandler())); + $processor = $this->processor(new FilesHandler()); + $files = $processor->getValues()['files']; + $this->assertIsArray($files); + $this->assertInstanceOf(FileUpload::class, $files[1]); + $this->assertSame(['b.txt', UPLOAD_ERR_PARTIAL], [$files[1]->originalName, $files[1]->error]); + $this->assertSame(UPLOAD_ERR_OK, $files[0]->error); + } + + public function testArrayOfFilesForASingleFileIsRejected(): void + { + $_POST = ['displayName' => 'Ada']; + $_FILES = ['avatar' => self::files(['a.png', 'b.png'], [UPLOAD_ERR_OK, UPLOAD_ERR_OK])]; + $this->assertSame(['avatar' => ['Value must be a file upload']], $this->errors(new AvatarHandler())); + } + + public function testMalformedFileEntriesAreMissing(): void + { + $_POST = ['displayName' => 'Ada']; + $_FILES = ['avatar' => 'not-an-array']; + $this->assertSame(['avatar' => ['Field is required']], $this->errors(new AvatarHandler())); + } + + public function testFileUploadFromIncompleteEntryUsesSafeDefaults(): void + { + $upload = FileUpload::fromFile([]); + $this->assertSame(['', '', '', 0, UPLOAD_ERR_NO_FILE], [$upload->originalName, $upload->clientContentType, $upload->temporaryPath, $upload->size, $upload->error]); + + $upload = FileUpload::fromFile(['name' => 1, 'type' => [], 'tmp_name' => null, 'size' => '5', 'error' => '0']); + $this->assertSame(['', '', '', 0, UPLOAD_ERR_NO_FILE], [$upload->originalName, $upload->clientContentType, $upload->temporaryPath, $upload->size, $upload->error]); + } + + public function testMediaTypeIsTrackedPerRequest(): void + { + $_POST = ['displayName' => 'Ada']; + $_FILES = ['avatar' => self::file('a.png', 1)]; + $this->assertFalse($this->processor(new AvatarHandler())->isError()); + $this->assertSame('multipart/form-data', RequestInput::mediaType()); + + RequestInput::reset(); + $this->assertNull(RequestInput::mediaType()); + } + + /** + * @return array + */ + private static function file(string $name, int $size): array + { + return ['name' => $name, 'type' => 'image/png', 'tmp_name' => '/tmp/php-' . $name, 'error' => UPLOAD_ERR_OK, 'size' => $size]; + } + + /** + * @param list $names + * @param list $errors + * @return array> + */ + private static function files(array $names, array $errors): array + { + return [ + 'name' => $names, + 'type' => array_fill(0, count($names), 'text/plain'), + 'tmp_name' => array_map(static fn (string $name): string => $name === '' ? '' : '/tmp/php-' . $name, $names), + 'error' => $errors, + 'size' => array_fill(0, count($names), 1), + ]; + } + + /** + * @return array + */ + private function requestBody(BaseHandler $handler): array + { + $operation = new PathBuilder()->buildOperation( + new Api(new EndpointIdentifier('POST', 1, 'upload'), $handler, new NoAuthorization()), + new SchemaRegistry(), + ); + + return $operation['requestBody']; + } + + /** + * @return array + */ + private function payload(BaseHandler $handler): array + { + $processor = $this->processor($handler); + $this->assertFalse($processor->isError(), (string) json_encode($processor->getErrors())); + + return $handler->handle($processor->getValues())->getPayload(); + } + + /** + * @return array + */ + private function errors(BaseHandler $handler): array + { + $processor = $this->processor($handler); + $this->assertTrue($processor->isError()); + + return $processor->getErrors(); + } + + private function processor(BaseHandler $handler): ParamsProcessor + { + return new ParamsProcessor($handler->params()); + } +} diff --git a/tests/Input/Fixtures/Dependency/DependencyCaster.php b/tests/Input/Fixtures/Dependency/DependencyCaster.php new file mode 100644 index 000000000..7096309d0 --- /dev/null +++ b/tests/Input/Fixtures/Dependency/DependencyCaster.php @@ -0,0 +1,15 @@ + $input->name]); + } +} diff --git a/tests/Input/Fixtures/Dependency/DependencyInput.php b/tests/Input/Fixtures/Dependency/DependencyInput.php new file mode 100644 index 000000000..ce56662fb --- /dev/null +++ b/tests/Input/Fixtures/Dependency/DependencyInput.php @@ -0,0 +1,10 @@ + $levels */ + public function __construct( + #[Body] #[Cast(DependencyCaster::class)] public string $name, + #[Body] public DependencyEnum $kind, + #[Body] public array $levels, + #[Body] #[DependencyConstraint] public string $note = '', + ) { + } +} diff --git a/tests/Input/Fixtures/Dependency/DependencyParentTrait.php b/tests/Input/Fixtures/Dependency/DependencyParentTrait.php new file mode 100644 index 000000000..25924ffd9 --- /dev/null +++ b/tests/Input/Fixtures/Dependency/DependencyParentTrait.php @@ -0,0 +1,13 @@ +value($this->otherProperty); + if ($value instanceof \DateTimeImmutable && $other instanceof \DateTimeImmutable && $value <= $other) { + return sprintf('Must be later than %s', $this->otherProperty); + } + + return null; + } +} + +final readonly class AddressInput +{ + public function __construct( + #[Body] + #[Length(min: 1, max: 120)] + public string $street, + #[Body] + #[Pattern('/^[0-9]{5}$/')] + public string $postalCode, + ) { + } +} + +final readonly class ItemInput +{ + public function __construct( + #[Body] + public string $sku, + #[Body] + #[Range(min: 1)] + public int $quantity, + ) { + } +} + +final readonly class CreateOrderInput +{ + /** @param list $items */ + public function __construct( + #[Body] + #[Email] + public string $customerEmail, + #[Body] + public AddressInput $address, + #[Body] + #[Length(min: 1, max: 50)] + public array $items, + #[Body] + public ?\DateTimeImmutable $deliveryAt = null, + ) { + } +} + +#[Post(1, 'orders')] +final class CreateOrderHandler extends TypedHandler +{ + public function handleDto(CreateOrderInput $input): ResponseInterface + { + return new JsonApiResponse(200, [ + 'email' => $input->customerEmail, + 'street' => $input->address->street, + 'items' => count($input->items), + 'quantity' => $input->items[0]->quantity, + 'deliveryAt' => $input->deliveryAt?->format(\DateTimeInterface::ATOM), + ]); + } +} + +final readonly class ListUsersInput +{ + public function __construct( + #[Query(description: 'Page number')] + #[Range(min: 1)] + public int $page = 1, + #[Query] + #[Range(min: 1, max: 100)] + public int $limit = 20, + #[Query] + public ?UserStatus $status = null, + #[Query] + public ?Priority $priority = null, + #[Query] + public bool $remember = false, + ) { + } +} + +#[Get(1, 'users', 'list')] +final class ListUsersHandler extends TypedHandler +{ + public function handleDto(ListUsersInput $input): ResponseInterface + { + return new JsonApiResponse(200, [ + 'page' => $input->page, + 'limit' => $input->limit, + 'status' => $input->status?->value, + 'priority' => $input->priority?->value, + 'remember' => $input->remember, + ]); + } +} + +final readonly class UserDetailInput +{ + public function __construct( + #[Path] + #[Range(min: 1)] + public int $id, + #[Query] + #[Range(min: 1, max: 100)] + public int $limit = 20, + #[Query] + public ?UserStatus $status = null, + #[Header('X-Request-Id')] + public ?string $requestId = null, + ) { + } +} + +#[Get(1, 'users', '{id}/detail')] +final class UserDetailHandler extends TypedHandler +{ + public function handleDto(UserDetailInput $input): ResponseInterface + { + return new JsonApiResponse(200, [ + 'id' => $input->id, + 'limit' => $input->limit, + 'status' => $input->status?->value, + 'requestId' => $input->requestId, + ]); + } +} + +final readonly class AvatarInput +{ + public function __construct( + #[Body] + #[Length(min: 1, max: 80)] + public string $displayName, + #[File(description: 'PNG or JPEG image')] + public FileUpload $avatar, + ) { + } +} + +#[Post(1, 'avatar')] +final class AvatarHandler extends TypedHandler +{ + public function handleDto(AvatarInput $input): ResponseInterface + { + return new JsonApiResponse(200, [ + 'name' => $input->displayName, + 'file' => $input->avatar->originalName, + 'size' => $input->avatar->size, + 'error' => $input->avatar->error, + 'type' => $input->avatar->clientContentType, + 'path' => $input->avatar->temporaryPath, + ]); + } +} + +final readonly class IssueInput +{ + public function __construct( + #[Body] + #[Cast(DateFormat::class, 'd.m.Y')] + public \DateTimeImmutable $issuedOn, + ) { + } +} + +final class IssueHandler extends TypedHandler +{ + public function handleDto(IssueInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['issuedOn' => $input->issuedOn->format('Y-m-d')]); + } +} + +final readonly class ReportInput +{ + /** @param list $columns */ + public function __construct( + #[Query] + #[Cast(Split::class, ',')] + public array $columns, + ) { + } +} + +final class ReportHandler extends TypedHandler +{ + public function handleDto(ReportInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['columns' => $input->columns]); + } +} + +final readonly class ScheduleInput +{ + public function __construct( + #[Body] + public \DateTimeImmutable $startsAt, + #[Body] + #[LaterThan('startsAt')] + public \DateTimeImmutable $endsAt, + ) { + } +} + +final class ScheduleHandler extends TypedHandler +{ + public function handleDto(ScheduleInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['ok' => true]); + } +} + +final readonly class FilesInput +{ + /** @param list $files */ + public function __construct( + #[File] + public array $files, + ) { + } +} + +final class FilesHandler extends TypedHandler +{ + public function handleDto(FilesInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['count' => count($input->files), 'name' => $input->files[0]->originalName]); + } +} + +final readonly class DocumentInput +{ + /** @param list $attachments */ + public function __construct( + #[Body] + #[Cast(DateFormat::class, 'd.m.Y')] + public \DateTimeImmutable $issuedOn, + #[Body] + #[Range(min: 1, max: 10)] + public int $copies, + #[File] + public ?FileUpload $scan = null, + #[File] + public array $attachments = [], + ) { + } +} + +final class DocumentHandler extends TypedHandler +{ + public function handleDto(DocumentInput $input): ResponseInterface + { + return new JsonApiResponse(200, [ + 'issuedOn' => $input->issuedOn->format('Y-m-d'), + 'copies' => $input->copies, + 'scan' => $input->scan?->originalName, + 'attachments' => array_map(static fn (FileUpload $file): array => [$file->originalName, $file->error], $input->attachments), + ]); + } +} + +final readonly class ScanFirstInput +{ + public function __construct( + #[File] + public FileUpload $scan, + #[Body] + public string $title, + ) { + } +} + +final class ScanFirstHandler extends TypedHandler +{ + public function handleDto(ScanFirstInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['title' => $input->title, 'scan' => $input->scan->originalName]); + } +} diff --git a/tests/Input/Fixtures/ImportScope.php b/tests/Input/Fixtures/ImportScope.php new file mode 100644 index 000000000..7d92b787e --- /dev/null +++ b/tests/Input/Fixtures/ImportScope.php @@ -0,0 +1,31 @@ + $input->text]); + } +} diff --git a/tests/Input/Fixtures/Separate/NoteInput.php b/tests/Input/Fixtures/Separate/NoteInput.php new file mode 100644 index 000000000..676a65372 --- /dev/null +++ b/tests/Input/Fixtures/Separate/NoteInput.php @@ -0,0 +1,14 @@ +json(['price' => '12.50', 'prices' => ['1.00', '2.25']]); + $handler = new MoneyHandler(); + $processor = new ParamsProcessor($handler->params()); + $this->assertFalse($processor->isError(), (string) json_encode($processor->getErrors())); + $this->assertSame(['price' => 1250, 'prices' => [100, 225]], $handler->handle($processor->getValues())->getPayload()); + + $fields = DtoCompiler::compile(MoneyHandler::class)->fields; + $this->assertSame([], $fields[0]->children); + $this->assertSame(['type' => 'string', 'example' => '12.50'], SchemaBuilder::build($fields[0], true)); + $this->assertNull($fields[1]->item); + + $this->json(['price' => 'abc', 'prices' => []]); + $this->assertSame(['price' => ['Use a decimal amount, for example 12.50']], $this->errors(new MoneyHandler())); + } + + public function testNamedCasterArgumentsSurviveTheCompiledContainer(): void + { + $_GET = ['value' => 'X', 'other' => 'Y']; + $this->assertSame(['value' => 'STARTXEND', 'other' => 'AYB'], $this->payload(new NamedCasterHandler())); + $compiled = DtoCompiler::compile(WireSchemaHandler::class); + $imported = DtoMetadata::import($compiled->export()); + $this->assertSame($compiled->fields[0]->casterSchema, $imported->fields[0]->casterSchema); + $this->assertSame('integer', $imported->fields[0]->casterSchema['type'] ?? null); + + $export = $compiled->fields[0]->export(); + $export['casterSchema'] = [0 => 'stray', 'type' => 'integer']; + $this->assertSame(['type' => 'integer'], Field::import($export)->casterSchema); + + DtoMetadataRegistry::install([NamedCasterHandler::class => DtoCompiler::compile(NamedCasterHandler::class)->export()]); + $this->assertTrue(DtoMetadataRegistry::installs(NamedCasterHandler::class)); + $this->assertSame(['value' => 'STARTXEND', 'other' => 'AYB'], $this->payload(new NamedCasterHandler())); + } + + public function testNulByteIsAFieldError(): void + { + try { + new DateFormat('d.m.Y')->cast("24.12.2026\0"); + $this->fail('NUL byte was accepted'); + } catch (CastException $exception) { + $this->assertSame('Date must match d.m.Y, for example 24.12.2026', $exception->getMessage()); + } + + $this->json(['day' => "24.12.2026\u{0}"]); + $this->assertSame(['day' => ['Date must match d.m.Y, for example 24.12.2026']], $this->errors(new NulDateHandler())); + } + + public function testCompiledCasterSchemaUsesTheWireType(): void + { + $fields = DtoCompiler::compile(WireSchemaHandler::class)->fields; + $this->assertSame('integer', SchemaBuilder::build($fields[0], true)['type']); + $this->assertSame(new UnixTimestamp()->openApiSchema()['example'], SchemaBuilder::build($fields[0], true)['example']); + $this->assertSame(['type' => 'string'], SchemaBuilder::build($fields[1], true)); + } + + public function testSiblingDefaultsAreVisibleToConstraints(): void + { + $this->assertCount(2, DtoCompiler::compile(SiblingDefaultsHandler::class)->fields); + $this->assertCompileFails(BadSiblingDefaultsHandler::class, 'BadSiblingDefaultsInput::$right default does not satisfy #[SameAs]: Must equal left'); + } + + public function testDefaultsAfterARequiredFieldAreChecked(): void + { + $this->assertCompileFails(RequiredThenBadDefaultHandler::class, 'RequiredThenBadDefaultInput::$right default does not satisfy #[SameAs]'); + } + + public function testValidListDefaultsOfEveryItemType(): void + { + $fields = DtoCompiler::compile(ListDefaultsHandler::class)->fields; + $this->assertSame([[1, 2.5], [true], ['a'], [UserStatus::Active], ['x']], array_map(static fn (Field $field): mixed => $field->default, $fields)); + $this->assertCompileFails(BadFloatListDefaultHandler::class, 'default item 1 is string, but the property is list'); + $this->assertCompileFails(BadBoolListDefaultHandler::class, 'default item 0 is int, but the property is list'); + $this->assertCompileFails(BadStringListDefaultHandler::class, 'default item 0 is int, but the property is list'); + $this->assertCompileFails(BadEnumListDefaultHandler::class, 'default item 0 is string, but the property is list<' . UserStatus::class . '>'); + $this->assertCompileFails(BadCastListDefaultHandler::class, 'default item 0 is int, but the property is list'); + } + + public function testLengthOnAListIsCheckedBeforeItsItems(): void + { + $_GET = ['ids' => ['x', 'y', 'z']]; + $this->assertSame(['ids' => ['Value must have between 1 and 2 items']], $this->errors(new LengthListHandler())); + RequestInput::reset(); + $_GET = ['ids' => []]; + $this->assertSame(['ids' => ['Value must have between 1 and 2 items']], $this->errors(new LengthListHandler())); + RequestInput::reset(); + $_GET = ['ids' => ['1', '2'], 'min' => ['x']]; + $this->assertSame(['min[0]' => ['Value must be an integer']], $this->errors(new LengthListHandler())); + RequestInput::reset(); + $_GET = ['ids' => ['1'], 'min' => ['4', '5', '6']]; + $this->assertSame(['ids' => [1], 'min' => [4, 5, 6]], $this->payload(new LengthListHandler())); + } + + public function testDefaultsInTheSchema(): void + { + $fields = DtoCompiler::compile(SchemaDefaultsHandler::class)->fields; + $this->assertSame('active', SchemaBuilder::build($fields[0], true)['default']); + $this->assertSame('a,b', SchemaBuilder::build($fields[1], true)['default']); + $this->assertArrayNotHasKey('default', SchemaBuilder::build($fields[2], true)); + $this->assertSame(2, SchemaBuilder::build($fields[3], true)['default']); + } + + public function testListDefaultItemsAreChecked(): void + { + $this->assertCompileFails(BadListDefaultHandler::class, "BadListDefaultInput::\$items default item 1 is string, but the property is list"); + $this->assertCompileFails(MapDefaultHandler::class, 'MapDefaultInput::$items default must be a list'); + } + + public function testConstructorParametersThatTheMapperCannotPass(): void + { + $this->assertCompileFails(SecretArgumentHandler::class, 'SecretArgumentInput::__construct() has the required parameter $secret that is not a promoted property'); + $this->assertCompileFails(VariadicArgumentHandler::class, 'VariadicArgumentInput::__construct() parameter $rest is variadic'); + $this->assertCompileFails(ReferenceArgumentHandler::class, 'ReferenceArgumentInput::__construct() parameter $page is passed by reference'); + $this->assertCount(1, DtoCompiler::compile(OptionalArgumentHandler::class)->fields); + } + + /** + * @return iterable + */ + public static function malformedIntegers(): iterable + { + foreach (['++0', '--0', '+-0', '-+000', "1\n", ' 1', '1 ', '+', '-', ''] as $value) { + yield json_encode($value, JSON_THROW_ON_ERROR) => [$value]; + } + } + + #[DataProvider('malformedIntegers')] + public function testMalformedIntegersAreRejected(string $value): void + { + $this->expectException(ConversionFailed::class); + ScalarCoercer::toInt($value); + } + + public function testSingleSignedIntegersAndAnchoredPatterns(): void + { + $this->assertSame([5, -5, 0, 7], [ScalarCoercer::toInt('+5'), ScalarCoercer::toInt('-5'), ScalarCoercer::toInt('-0'), ScalarCoercer::toInt('007')]); + foreach (["1\n", "1.5\n"] as $value) { + try { + ScalarCoercer::toFloat($value); + $this->fail('float with a newline was accepted'); + } catch (ConversionFailed) { + $this->addToAssertionCount(1); + } + } + $this->expectException(ConversionFailed::class); + ScalarCoercer::toDateTime("2026-11-06T14:30:00Z\n"); + } + + public function testEnumBackingTypeComesFromItsCases(): void + { + $this->assertSame(DependencyItemEnum::First, ScalarCoercer::toEnum('1', DependencyItemEnum::class)); + $this->expectException(ConversionFailed::class); + ScalarCoercer::toEnum('x', EmptyStringEnum::class); + } + + public function testDtoBoundaryRejectsSignedZeroGarbage(): void + { + $_GET = ['page' => '--0']; + $this->assertArrayHasKey('page', $this->errors(new OptionalArgumentHandler())); + } + + public function testPatternsAreExportedOnlyWhenPortable(): void + { + $this->assertSame('^[a-z]+$', new Pattern('{^[a-z]+$}')->expression()); + $this->assertSame('^[a-z]+$', new Pattern('(^[a-z]+$)')->expression()); + $this->assertSame('^[a-z]+$', new Pattern('[^[a-z]+$]')->expression()); + $this->assertSame('^[a-z]+$', new Pattern('<^[a-z]+$>')->expression()); + $this->assertSame('^[a-z]+$', new Pattern('#^[a-z]+$#uD')->expression()); + $this->assertNull(new Pattern('{^[a-z]+$}i')->expression()); + $this->assertNull(new Pattern('/^[a-z]+$/i')->expression()); + $this->assertNull(new Pattern('/^[a-z]+$/x')->expression()); + } + + public function testEveryReflectedDependencyRebuildsTheContainer(): void + { + $files = array_map(basename(...), DtoCompiler::compile(DependencyHandler::class)->files); + foreach (['DependencyHandler.php', 'DependencyInput.php', 'DependencyParentInput.php', 'DependencyCaster.php', 'DependencyEnum.php', 'DependencyItemEnum.php', 'DependencyConstraint.php', 'DependencyTrait.php', 'DependencyNestedTrait.php', 'DependencyParentTrait.php'] as $file) { + $this->assertContains($file, $files); + } + $this->assertSame(array_values(array_unique($files)), $files); + } + + public function testNativeListsAndObjectsCannotComeFromAPathOrHeader(): void + { + $this->assertCompileFails(HeaderListHandler::class, "HeaderListInput::\$tags reads #[Header], which is one string, so it cannot be list. Use a scalar type or split the string, for example #[Cast(Split::class, ',')]."); + } + + public function testQueryListIsAdvertisedInTheFormPhpReads(): void + { + $parameters = new ParameterBuilder()->build(new QueryListHandler()); + $this->assertSame(['ids[]', 'csv'], array_column($parameters, 'name')); + $this->assertSame(['type' => 'array', 'items' => ['type' => 'integer']], $parameters[0]['schema']); + + $name = rawurlencode((string) $parameters[0]['name']); + $query = sprintf('%s=3&%s=4&csv=a,b', $name, $name); + parse_str($query, $_GET); + $this->assertSame(['ids' => [3, 4], 'csv' => ['a', 'b']], $this->payload(new QueryListHandler())); + } + + /** + * @param array $body + */ + private function json(array $body): void + { + RequestInput::reset(); + RequestInput::setRawBody((string) json_encode($body)); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + } + + /** + * @return array + */ + private function payload(TypedHandler $handler): array + { + $processor = new ParamsProcessor($handler->params()); + $this->assertFalse($processor->isError(), (string) json_encode($processor->getErrors())); + + return $handler->handle($processor->getValues())->getPayload(); + } + + /** + * @return array + */ + private function errors(TypedHandler $handler): array + { + $processor = new ParamsProcessor($handler->params()); + $this->assertTrue($processor->isError()); + + return $processor->getErrors(); + } + + private function assertCompileFails(string $handler, string $needle): void + { + try { + DtoCompiler::compile($handler); + $this->fail($handler); + } catch (\LogicException $exception) { + $this->assertStringContainsString($needle, $exception->getMessage(), $handler); + } + } +} + +final readonly class Money +{ + private function __construct(public int $cents) + { + } + + public static function fromCents(int $cents): self + { + return new self($cents); + } +} + +final readonly class MoneyCaster implements CasterInterface, OpenApiCasterInterface +{ + public function cast(mixed $value): Money + { + if (!is_string($value) || preg_match('/^\d+\.\d{2}\z/', $value) !== 1) { + throw new CastException('Use a decimal amount, for example 12.50'); + } + + return Money::fromCents((int) str_replace('.', '', $value)); + } + + /** + * @return array{type: string, example: string} + */ + public function openApiSchema(): array + { + return ['type' => 'string', 'example' => '12.50']; + } +} + +final readonly class MoneyListCaster implements CasterInterface +{ + /** + * @return list + */ + public function cast(mixed $value): array + { + if (!is_array($value)) { + throw new CastException('Use a list of amounts'); + } + + return array_values(array_map(static fn (mixed $item): Money => new MoneyCaster()->cast($item), $value)); + } +} + +final readonly class MoneyInput +{ + /** @param list $prices */ + public function __construct( + #[Body] #[Cast(MoneyCaster::class)] public Money $price, + #[Body] #[Cast(MoneyListCaster::class)] public array $prices, + ) { + } +} + +final class MoneyHandler extends TypedHandler +{ + public function handleDto(MoneyInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['price' => $input->price->cents, 'prices' => array_map(static fn (Money $money): int => $money->cents, $input->prices)]); + } +} + +final readonly class NamedCaster implements CasterInterface +{ + public function __construct(private string $prefix = 'A', private string $suffix = 'B') + { + } + + public function cast(mixed $value): string + { + return $this->prefix . (is_string($value) ? $value : '') . $this->suffix; + } +} + +final readonly class NamedCasterInput +{ + public function __construct( + #[Query] #[Cast(NamedCaster::class, suffix: 'END', prefix: 'START')] public string $value, + #[Query] #[Cast(NamedCaster::class)] public string $other, + ) { + } +} + +final class NamedCasterHandler extends TypedHandler +{ + public function handleDto(NamedCasterInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['value' => $input->value, 'other' => $input->other]); + } +} + +final readonly class NulDateInput +{ + public function __construct(#[Body] #[Cast(DateFormat::class, 'd.m.Y')] public \DateTimeImmutable $day) + { + } +} + +final class NulDateHandler extends TypedHandler +{ + public function handleDto(NulDateInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class TextToIntCaster implements CasterInterface +{ + public function cast(mixed $value): int + { + return $value === 'one' ? 1 : 0; + } +} + +final readonly class WireSchemaInput +{ + public function __construct( + #[Query] #[Cast(UnixTimestamp::class)] public \DateTimeImmutable $at, + #[Query] #[Cast(TextToIntCaster::class)] public int $count, + ) { + } +} + +final class WireSchemaHandler extends TypedHandler +{ + public function handleDto(WireSchemaInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_PARAMETER)] +final readonly class SameAs implements ConstraintInterface +{ + public function __construct(private string $other) + { + } + + public function validate(mixed $value, ConstraintContext $context): ?string + { + return $value === $context->value($this->other) ? null : 'Must equal ' . $this->other; + } +} + +final readonly class SiblingDefaultsInput +{ + public function __construct( + #[Query] public string $left = 'same', + #[Query] #[SameAs('left')] public string $right = 'same', + ) { + } +} + +final class SiblingDefaultsHandler extends TypedHandler +{ + public function handleDto(SiblingDefaultsInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BadSiblingDefaultsInput +{ + public function __construct( + #[Query] #[SameAs('left')] public string $right = 'other', + #[Query] public string $left = 'same', + ) { + } +} + +final class BadSiblingDefaultsHandler extends TypedHandler +{ + public function handleDto(BadSiblingDefaultsInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BadListDefaultInput +{ + /** @param list $items */ + public function __construct(#[Query] public array $items = [1, 'not-an-int']) + { + } +} + +final class BadListDefaultHandler extends TypedHandler +{ + public function handleDto(BadListDefaultInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class MapDefaultInput +{ + /** @param list $items */ + public function __construct(#[Query] public array $items = ['a' => 1]) + { + } +} + +final class MapDefaultHandler extends TypedHandler +{ + public function handleDto(MapDefaultInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class SecretArgumentInput +{ + public function __construct(#[Query] public int $page, string $secret) + { + unset($secret); + } +} + +final class SecretArgumentHandler extends TypedHandler +{ + public function handleDto(SecretArgumentInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class VariadicArgumentInput +{ + public function __construct(#[Query] public int $page, string ...$rest) + { + unset($rest); + } +} + +final class VariadicArgumentHandler extends TypedHandler +{ + public function handleDto(VariadicArgumentInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final class ReferenceArgumentInput +{ + public function __construct(#[Query] public int &$page) + { + } +} + +final class ReferenceArgumentHandler extends TypedHandler +{ + public function handleDto(ReferenceArgumentInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class OptionalArgumentInput +{ + public function __construct(#[Query] public int $page = 1, string $mode = 'fast') + { + unset($mode); + } +} + +final class OptionalArgumentHandler extends TypedHandler +{ + public function handleDto(OptionalArgumentInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['page' => $input->page]); + } +} + +final readonly class HeaderListInput +{ + /** @param list $tags */ + public function __construct(#[Header('X-Tags')] public array $tags = []) + { + } +} + +final class HeaderListHandler extends TypedHandler +{ + public function handleDto(HeaderListInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class QueryListInput +{ + /** + * @param list $ids + * @param list $csv + */ + public function __construct( + #[Query] public array $ids, + #[Query] #[Cast(Split::class, ',')] public array $csv, + ) { + } +} + +final class QueryListHandler extends TypedHandler +{ + public function handleDto(QueryListInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['ids' => $input->ids, 'csv' => $input->csv]); + } +} + +final readonly class RequiredThenBadDefaultInput +{ + public function __construct( + #[Query] public string $left, + #[Query] #[SameAs('left')] public string $right = 'x', + ) { + } +} + +final class RequiredThenBadDefaultHandler extends TypedHandler +{ + public function handleDto(RequiredThenBadDefaultInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class ListDefaultsInput +{ + /** + * @param list $floats + * @param list $flags + * @param list $names + * @param list $statuses + * @param list $split + */ + public function __construct( + #[Query] public array $floats = [1, 2.5], + #[Query] public array $flags = [true], + #[Query] public array $names = ['a'], + #[Query] public array $statuses = [UserStatus::Active], + #[Query] #[Cast(Split::class, ',')] public array $split = ['x'], + ) { + } +} + +final class ListDefaultsHandler extends TypedHandler +{ + public function handleDto(ListDefaultsInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BadFloatListDefaultInput +{ + /** @param list $items */ + public function __construct(#[Query] public array $items = [1.5, 'x']) + { + } +} + +final class BadFloatListDefaultHandler extends TypedHandler +{ + public function handleDto(BadFloatListDefaultInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BadBoolListDefaultInput +{ + /** @param list $items */ + public function __construct(#[Query] public array $items = [1]) + { + } +} + +final class BadBoolListDefaultHandler extends TypedHandler +{ + public function handleDto(BadBoolListDefaultInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BadStringListDefaultInput +{ + /** @param list $items */ + public function __construct(#[Query] public array $items = [1]) + { + } +} + +final class BadStringListDefaultHandler extends TypedHandler +{ + public function handleDto(BadStringListDefaultInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BadEnumListDefaultInput +{ + /** @param list $items */ + public function __construct(#[Query] public array $items = ['active']) + { + } +} + +final class BadEnumListDefaultHandler extends TypedHandler +{ + public function handleDto(BadEnumListDefaultInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BadCastListDefaultInput +{ + /** @param list $items */ + public function __construct(#[Query] #[Cast(Split::class, ',')] public array $items = [1]) + { + } +} + +final class BadCastListDefaultHandler extends TypedHandler +{ + public function handleDto(BadCastListDefaultInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class LengthListInput +{ + /** + * @param list $ids + * @param list $min + */ + public function __construct( + #[Query] #[Length(min: 1, max: 2)] public array $ids, + #[Query] #[Length(min: 1)] public array $min = [1], + ) { + } +} + +final class LengthListHandler extends TypedHandler +{ + public function handleDto(LengthListInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['ids' => $input->ids, 'min' => $input->min]); + } +} + +final readonly class StatusCaster implements CasterInterface +{ + public function cast(mixed $value): UserStatus + { + return UserStatus::from(is_string($value) ? $value : 'active'); + } +} + +final readonly class SchemaDefaultsInput +{ + public function __construct( + #[Query] public UserStatus $status = UserStatus::Active, + #[Query] #[Cast(NamedCaster::class)] public string $text = 'a,b', + #[Query] #[Cast(StatusCaster::class)] public UserStatus $casted = UserStatus::Active, + #[Query] public Priority $priority = Priority::High, + ) { + } +} + +final class SchemaDefaultsHandler extends TypedHandler +{ + public function handleDto(SchemaDefaultsInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +enum EmptyStringEnum: string +{ +} diff --git a/tests/Input/Round10Test.php b/tests/Input/Round10Test.php new file mode 100644 index 000000000..2f6367f1a --- /dev/null +++ b/tests/Input/Round10Test.php @@ -0,0 +1,319 @@ +json(['ids' => array_fill(0, 5000, 'x')]); + $errors = $this->errors(new ManyIdsHandler()); + + $this->assertCount(DtoMapper::MAX_ERRORS + 1, $errors); + $this->assertSame(['Value must be an integer'], $errors['ids[0]']); + $this->assertSame(['Value must be an integer'], $errors['ids[99]']); + $this->assertArrayNotHasKey('ids[100]', $errors); + $this->assertSame(['Only the first 100 errors are reported, the rest of the request was not checked'], $errors['body']); + $this->assertArrayNotHasKey('ids', $errors); + } + + public function testTheBudgetIsOnePerRequestAcrossNestedLists(): void + { + $leaf = array_fill(0, 100, new \stdClass()); + $middle = array_fill(0, 100, ['cs' => $leaf]); + $outer = array_fill(0, 100, ['bs' => $middle]); + $this->json(['as' => $outer]); + + $errors = $this->errors(new NestedListsHandler()); + $messages = array_merge(...array_values($errors)); + + $this->assertLessThanOrEqual(DtoMapper::MAX_ERRORS + 1, count($messages)); + $this->assertContains('Only the first 100 errors are reported, the rest of the request was not checked', $messages); + $this->assertCount(1, array_filter($messages, static fn (string $message): bool => str_starts_with($message, 'Only the first'))); + } + + public function testTheBudgetAlsoStopsLaterFields(): void + { + $this->json(['ids' => array_fill(0, 150, 'x'), 'other' => 'y']); + $errors = $this->errors(new BudgetHandler()); + + $this->assertArrayNotHasKey('other', $errors); + $this->assertCount(101, $errors); + } + + public function testNothingIsLeftUncheckedUpToTheCapSoThereIsNoNote(): void + { + $this->json(['ids' => array_fill(0, 99, 'x')]); + $errors = $this->errors(new ManyIdsHandler()); + $this->assertCount(99, $errors); + $this->assertArrayNotHasKey('ids', $errors); + + // exactly the budget: nothing was left unchecked, so there is nothing to apologise for + $this->json(['ids' => array_fill(0, 100, 'x')]); + $errors = $this->errors(new ManyIdsHandler()); + $this->assertCount(100, $errors); + $this->assertArrayNotHasKey('body', $errors); + + $this->json(['ids' => array_fill(0, 101, 'x')]); + $errors = $this->errors(new ManyIdsHandler()); + $this->assertCount(101, $errors); + $this->assertArrayHasKey('body', $errors); + $this->assertArrayNotHasKey('ids[100]', $errors); + } + + public function testManyInvalidItemsAreCheckedInLinearTime(): void + { + $this->json(['ids' => array_merge(array_fill(0, 100, 1), array_fill(0, 60000, 'x'))]); + $start = microtime(true); + $this->errors(new ManyIdsHandler()); + $this->assertLessThan(2.0, microtime(true) - $start); + } + + public function testSplitPropertyIsOneStringInputWithoutAnArrayDefault(): void + { + $param = new SplitHandler()->params()[0]; + $this->assertFalse($param->isMulti()); + $this->assertNull($param->getDefault()); + $this->assertSame(['type' => 'string', 'example' => 'red,green,blue'], $param->getOpenApiSchema()); + + $parameters = new ParameterBuilder()->build(new SplitHandler()); + $this->assertSame(['tags', 'label'], array_column($parameters, 'name')); + $this->assertSame('plain', $parameters[1]['schema']['default']); + $this->assertSame('plain', new SplitHandler()->params()[1]->getDefault()); + + $_GET = ['tags' => 'a,b']; + $this->assertSame(['tags' => ['a', 'b']], $this->payload(new SplitHandler())); + RequestInput::reset(); + $_GET = []; + $this->assertSame(['tags' => []], $this->payload(new SplitHandler())); + } + + public function testOpenApiListsTheUnsupportedMediaTypeResponseOfATypedBody(): void + { + foreach ([false, true] as $problemDetails) { + $builder = new ResponseBuilder($problemDetails); + $withBody = $builder->build(new ManyIdsHandler(), new NoAuthorization(), true, new SchemaRegistry()); + $this->assertSame([400, 415, 500], array_keys($withBody)); + $this->assertSame('Unsupported media type', $withBody[415]['description']); + $this->assertArrayHasKey($problemDetails ? 'application/problem+json; charset=utf-8' : 'application/json; charset=utf-8', $withBody[415]['content']); + + $queryOnly = $builder->build(new SplitHandler(), new NoAuthorization(), true, new SchemaRegistry()); + $this->assertSame([400, 500], array_keys($queryOnly)); + } + + $classic = new ResponseBuilder()->build(new EchoHandler(), new NoAuthorization(), true, new SchemaRegistry()); + $this->assertArrayNotHasKey(415, $classic); + } + + public function testANullableEnumListsNullInTheBodyAndNothingNullableOnTheWire(): void + { + $params = DtoCompiler::compile(LevelHandler::class)->inputParams(); + + $this->assertSame(['type' => 'string', 'enum' => ['low', 'high', null], 'nullable' => true], $params[1]->getOpenApiSchema()); + $this->assertSame(['type' => 'string', 'enum' => ['low', 'high']], $params[2]->getOpenApiSchema()); + $this->assertSame([ + 'type' => 'object', + 'properties' => ['text' => ['type' => 'string'], 'author' => ['type' => 'string', 'nullable' => true]], + 'required' => ['text'], + 'nullable' => true, + ], $params[0]->getOpenApiSchema()); + } + + /** + * @param array $body + */ + private function json(array $body): void + { + RequestInput::reset(); + RequestInput::setRawBody((string) json_encode($body)); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + } + + /** + * @return array + */ + private function errors(TypedHandler $handler): array + { + $processor = new ParamsProcessor($handler->params()); + $this->assertTrue($processor->isError()); + + return $processor->getErrors(); + } + + /** + * @return array + */ + private function payload(TypedHandler $handler): array + { + $processor = new ParamsProcessor($handler->params()); + $this->assertFalse($processor->isError(), (string) json_encode($processor->getErrors())); + + return $handler->handle($processor->getValues())->getPayload(); + } +} + +final readonly class Round10Note +{ + public function __construct(#[Body] public string $text, #[Body] public ?string $author = null) + { + } +} + +enum Round10Level: string +{ + case Low = 'low'; + case High = 'high'; +} + +final readonly class LevelInput +{ + public function __construct( + #[Body] public ?Round10Note $note = null, + #[Body] public ?Round10Level $level = null, + #[Query] public ?Round10Level $filter = null, + ) { + } +} + +final class LevelHandler extends TypedHandler +{ + public function handleDto(LevelInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class ManyIdsInput +{ + /** @param list $ids */ + public function __construct(#[Body] public array $ids) + { + } +} + +final class ManyIdsHandler extends TypedHandler +{ + public function handleDto(ManyIdsInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['count' => count($input->ids)]); + } +} + +final readonly class SplitInput +{ + /** @param list $tags */ + public function __construct( + #[Query] #[Cast(Split::class, ',')] public array $tags = [], + #[Query] #[Cast(UpperCaster::class)] public string $label = 'plain', + ) { + } +} + +final class SplitHandler extends TypedHandler +{ + public function handleDto(SplitInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['tags' => $input->tags]); + } +} + +final readonly class UpperCaster implements CasterInterface +{ + public function cast(mixed $value): string + { + return strtoupper(is_string($value) ? $value : ''); + } +} + +final readonly class BudgetLeaf +{ + public function __construct(#[Body] public string $x) + { + } +} + +final readonly class BudgetMiddle +{ + /** @param list $cs */ + public function __construct(#[Body] public array $cs) + { + } +} + +final readonly class BudgetOuter +{ + /** @param list $bs */ + public function __construct(#[Body] public array $bs) + { + } +} + +final readonly class NestedListsInput +{ + /** @param list $as */ + public function __construct(#[Body] public array $as) + { + } +} + +final class NestedListsHandler extends TypedHandler +{ + public function handleDto(NestedListsInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BudgetInput +{ + /** @param list $ids */ + public function __construct(#[Body] public array $ids, #[Body] public int $other) + { + } +} + +final class BudgetHandler extends TypedHandler +{ + public function handleDto(BudgetInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} diff --git a/tests/Input/Round11Test.php b/tests/Input/Round11Test.php new file mode 100644 index 000000000..05dba477d --- /dev/null +++ b/tests/Input/Round11Test.php @@ -0,0 +1,1042 @@ + + */ + public static function invalidHandlers(): \Iterator + { + yield 'nested dto in query' => [R11QueryDtoHandler::class, 'reads #[Query], which carries flat values']; + yield 'list of dto in query' => [R11QueryListHandler::class, 'cannot be list<']; + yield 'object default (date)' => [R11DateDefaultHandler::class, 'has a default of type DateTimeImmutable']; + yield 'object default (dto)' => [R11DtoDefaultHandler::class, 'has a default of type Tomaj\\NetteApi\\Test\\Input\\R11Inner']; + yield 'object default inside a list' => [R11ListObjectDefaultHandler::class, 'has a default of type']; + yield 'list of nullable items' => [R11NullableItemsHandler::class, 'one non-nullable type']; + yield 'list of unions' => [R11UnionItemsHandler::class, 'one non-nullable type']; + yield 'list of lists' => [R11NestedListsHandler::class, 'one non-nullable type']; + yield 'associative array' => [R11AssocHandler::class, 'not a list']; + yield 'unreadable doc type' => [R11OtherDocHandler::class, 'Found `iterable`']; + yield 'DateTime' => [R11PlainDateTimeHandler::class, 'Use DateTimeImmutable']; + yield 'DateTimeInterface' => [R11DateInterfaceHandler::class, 'Use DateTimeImmutable']; + yield 'empty split separator' => [R11EmptySplitHandler::class, 'Its constructor is __construct(string $separator)']; + yield 'split into ints' => [R11SplitIntsHandler::class, 'Split gives list']; + yield 'list with a trailing union' => [R11TrailingUnionHandler::class, 'Found `list|string`']; + yield 'array of arrays' => [R11ArrayOfArraysHandler::class, 'not a list']; + yield 'brackets with a trailing union' => [R11BracketUnionHandler::class, 'Found `string[]|int`']; + yield 'array of lists' => [R11ArrayOfListsHandler::class, 'not a list']; + yield 'union before brackets' => [R11UnionBracketsHandler::class, 'Found `int|string[]`']; + yield 'generic of array' => [R11GenericOfArrayHandler::class, 'Found `Collection`']; + yield 'caster constructor with typed and untyped parameters' => [R11BadCasterHandler::class, 'Its constructor is __construct(string $format, $loose)']; + yield 'caster without a constructor' => [R11NoCtorCasterHandler::class, 'Its constructor is __construct()']; + yield 'dash in a path name' => [R11PathDashHandler::class, 'can only have letters, digits and underscores']; + yield 'underscore in a header name' => [R11HeaderUnderscoreHandler::class, "Use #[Header('X-Foo')]"]; + } + + /** + * @param class-string $handler + */ + #[DataProvider('invalidHandlers')] + public function testCompileTimeMessage(string $handler, string $needle): void + { + $this->expectException(\LogicException::class); + $this->expectExceptionMessage($needle); + DtoCompiler::compile($handler); + } + + /** + * @param array $body + */ + private function json(array $body): void + { + RequestInput::reset(); + RequestInput::setRawBody((string) json_encode($body)); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + } + + /** + * @return array> + */ + private function errors(TypedHandler $handler): array + { + $processor = new ParamsProcessor($handler->params()); + $this->assertTrue($processor->isError()); + + return $processor->getErrors(); + } + + public function testPathNameMessageSuggestsTheCorrectedName(): void + { + $this->expectException(\LogicException::class); + $this->expectExceptionMessage("Use for example #[Path('a_b')]."); + DtoCompiler::compile(R11PathDashHandler::class); + } + + public function testSplitSeparatorMessageHasNoDoublePeriod(): void + { + try { + DtoCompiler::compile(R11EmptySplitHandler::class); + $this->fail('compiled'); + } catch (\LogicException $exception) { + $this->assertStringNotContainsString('..', $exception->getMessage()); + $this->assertStringContainsString("#[Cast(Split::class, ',')]. Its constructor", $exception->getMessage()); + $this->assertStringNotContainsString('d.m.Y', $exception->getMessage()); + } + } + + public function testAnUntypedParamTagFallsBackToTheVarOfTheProperty(): void + { + $this->assertSame('int', DtoCompiler::compile(R11VarFallbackHandler::class)->fields[0]->listItem); + } + + public function testEveryCommonPhpDocSpellingOfAListIsRead(): void + { + $fields = DtoCompiler::compile(R11DocFormsHandler::class)->fields; + + $this->assertSame( + ['string', 'string', 'string', 'string', 'string', 'string', 'int', 'float'], + array_map(static fn (Field $field): string => (string) $field->listItem, $fields), + ); + } + + public function testABodyWithoutAContentTypeIsNotIgnoredWhenAllFieldsAreOptional(): void + { + unset($_SERVER['CONTENT_TYPE']); + $_SERVER['REQUEST_METHOD'] = 'POST'; + RequestInput::setRawBody('{"a":"x"}'); + + $this->expectException(UnsupportedMediaTypeException::class); + $this->expectExceptionMessage('Content-Type is missing'); + new ParamsProcessor(new R11OptionalHandler()->params())->isError(); + } + + public function testAnEmptyRequestWithoutAContentTypeStillSucceedsWhenAllFieldsAreOptional(): void + { + unset($_SERVER['CONTENT_TYPE']); + $_SERVER['REQUEST_METHOD'] = 'POST'; + RequestInput::setRawBody(''); + + $this->assertFalse(new ParamsProcessor(new R11OptionalHandler()->params())->isError()); + } + + public function testMultipartWithPutAnswersWithTheReasonInsteadOfMissingFields(): void + { + $_SERVER['CONTENT_TYPE'] = 'multipart/form-data; boundary=x'; + $_SERVER['REQUEST_METHOD'] = 'PUT'; + RequestInput::setRawBody("--x\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\nv\r\n--x--\r\n"); + + $processor = new ParamsProcessor(new R11MultipartHandler()->params()); + $this->assertTrue($processor->isError()); + $this->assertSame( + ['body' => ['multipart/form-data is only parsed by PHP for POST requests, but this one is PUT. Send it with POST, or use application/json']], + $processor->getErrors(), + ); + } + + public function testAnEmptyMultipartPutIsNotAnError(): void + { + $_SERVER['CONTENT_TYPE'] = 'multipart/form-data; boundary=x'; + $_SERVER['REQUEST_METHOD'] = 'PUT'; + RequestInput::setRawBody(''); + + $this->assertFalse(new ParamsProcessor(new R11MultipartHandler()->params())->isError()); + } + + public function testTooManyFormFieldsDoNotReachTheErrorHandlerOfTheApplication(): void + { + $limit = (int) ini_get('max_input_vars'); + $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; + $_SERVER['REQUEST_METHOD'] = 'PUT'; + RequestInput::setRawBody(implode('&', array_map(static fn (int $i): string => 'f' . $i . '=1', range(1, $limit + 1)))); + + $seen = []; + set_error_handler(static function (int $level, string $message) use (&$seen): bool { + $seen[] = $message; + + return true; + }); + error_clear_last(); + try { + $this->assertTrue(new ParamsProcessor(new R11FormHandler()->params())->isError()); + $afterwards = $seen; + // the handler of the application is back in place: it receives the next warning + hex2bin('abc'); + } finally { + restore_error_handler(); + } + + // PHP's own handler runs only when ours declines the warning, and it would leave it in error_get_last() + $this->assertNull(error_get_last()); + $this->assertSame([], $afterwards); + $this->assertCount(1, $seen); + } + + public function testTooManyFormFieldsAreAnErrorInsteadOfAWarning(): void + { + $limit = (int) ini_get('max_input_vars'); + $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; + $_SERVER['REQUEST_METHOD'] = 'PUT'; + RequestInput::setRawBody(implode('&', array_map(static fn (int $i): string => 'f' . $i . '=1', range(1, $limit + 1)))); + + $processor = new ParamsProcessor(new R11FormHandler()->params()); + $this->assertTrue($processor->isError()); + $this->assertSame(['body' => ['Too many form fields']], $processor->getErrors()); + } + + public function testExactlyTheLimitOfFormFieldsIsAccepted(): void + { + $limit = (int) ini_get('max_input_vars'); + $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; + $_SERVER['REQUEST_METHOD'] = 'PUT'; + RequestInput::setRawBody(implode('&', array_map(static fn (int $i): string => 'f' . $i . '=1', range(1, $limit)))); + + $this->assertFalse(new ParamsProcessor(new R11FormHandler()->params())->isError()); + } + + public function testAJsonCharsetOtherThanUtf8IsRejected(): void + { + foreach (['application/json; charset=ISO-8859-1' => 'iso-8859-1', 'application/json;charset="latin1"' => 'latin1', 'application/json; CHARSET=latin1' => 'latin1'] as $contentType => $charset) { + RequestInput::reset(); + $_SERVER['CONTENT_TYPE'] = $contentType; + $_SERVER['REQUEST_METHOD'] = 'POST'; + RequestInput::setRawBody('{"a":"x"}'); + + $processor = new ParamsProcessor(new R11FormHandler()->params()); + $this->assertTrue($processor->isError(), $contentType); + $this->assertSame(['JSON must be UTF-8; the request says charset=' . $charset], $processor->getErrors()['body']); + } + + foreach (['application/json; charset=UTF-8', 'application/json; Charset="utf-8"', 'application/json'] as $contentType) { + RequestInput::reset(); + $_SERVER['CONTENT_TYPE'] = $contentType; + RequestInput::setRawBody('{"a":"x"}'); + $this->assertFalse(new ParamsProcessor(new R11FormHandler()->params())->isError(), $contentType); + } + } + + public function testTheBudgetStopsInsideAnObjectToo(): void + { + $this->json(['ids' => array_fill(0, 99, 'x'), 'inner' => new \stdClass()]); + $errors = $this->errors(new R11BudgetObjectHandler()); + + $this->assertSame(['Field is required'], $errors['inner.a']); + $this->assertSame(['Only the first 100 errors are reported, the rest of the request was not checked'], $errors['body']); + $this->assertArrayNotHasKey('inner', $errors); + $this->assertArrayNotHasKey('inner.b', $errors); + $this->assertArrayNotHasKey('inner.c', $errors); + } + + public function testTheBudgetEndsAtTheTopLevelToo(): void + { + $this->json(['ids' => array_fill(0, 99, 'x'), 'x' => 'a', 'y' => 'b']); + $errors = $this->errors(new R11BudgetTopHandler()); + + $this->assertSame(['Value must be an integer'], $errors['x']); + $this->assertSame(['Only the first 100 errors are reported, the rest of the request was not checked'], $errors['body']); + $this->assertArrayNotHasKey('y', $errors); + } + + public function testConstraintMessagesCountTowardsTheBudget(): void + { + $this->json(['items' => array_fill(0, 150, ['name' => 'too long'])]); + $errors = $this->errors(new R11ConstraintBudgetHandler()); + + $this->assertCount(101, $errors); + $this->assertSame(['Only the first 100 errors are reported, the rest of the request was not checked'], $errors['body']); + $this->assertArrayHasKey('items[99].name', $errors); + $this->assertArrayNotHasKey('items[100].name', $errors); + } + + public function testLengthCountsUtf8CharactersWhateverTheInternalEncoding(): void + { + $encoding = mb_internal_encoding(); + mb_internal_encoding('ISO-8859-1'); + try { + $this->assertNull(new Length(max: 3)->validate('čšž', new ConstraintContext('x', self::class, [], []))); + } finally { + mb_internal_encoding($encoding); + } + } + + public function testASmallRangeBoundIsNotPrintedAsZero(): void + { + $context = new ConstraintContext('x', self::class, [], []); + $this->assertSame('Value must be at most 1.0E-12', new Range(max: 1.0E-12)->validate(1.0, $context)); + $this->assertSame('Value must be at least -2.0E-11', new Range(min: -2.0E-11)->validate(-1.0, $context)); + $this->assertSame('Value must be at most 0.5', new Range(max: 0.5)->validate(1.0, $context)); + $this->assertSame('Value must be at least 0', new Range(min: 0)->validate(-1, $context)); + $this->assertSame('Value must be at most 0', new Range(max: 0.0)->validate(1, $context)); + $this->assertSame('Value must be at most 100', new Range(max: 100.0)->validate(101, $context)); + $this->assertSame('Value must be at most 9223372036854775806', new Range(max: PHP_INT_MAX - 1)->validate(PHP_INT_MAX, $context)); + } + + public function testRfc3339AcceptsLowercaseSeparators(): void + { + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + foreach (['2024-05-01t10:00:00z' => '2024-05-01T10:00:00+00:00', '2024-05-01t10:00:00.5+02:00' => '2024-05-01T10:00:00+02:00'] as $input => $expected) { + RequestInput::reset(); + RequestInput::setRawBody((string) json_encode(['at' => $input])); + $processor = new ParamsProcessor(new R11DateHandler()->params()); + $this->assertFalse($processor->isError(), $input); + $at = $processor->getValues()['at']; + $this->assertInstanceOf(\DateTimeImmutable::class, $at); + $this->assertSame($expected, $at->format('c')); + } + + RequestInput::reset(); + RequestInput::setRawBody('{"at":"2016-12-31T23:59:60Z"}'); + $this->assertTrue(new ParamsProcessor(new R11DateHandler()->params())->isError()); + } + + /** + * @return \Iterator + */ + public static function patterns(): \Iterator + { + yield 'plain' => ['/^[a-z]+$/', '^[a-z]+$']; + yield 'escaped plus' => ['/^a\+\+$/', '^a\+\+$']; + yield 'lookahead and a group' => ['/^(?=a)(?:a|b)+x$/u', '^(?=a)(?:a|b)+x$']; + yield 'lookahead and named group' => ['/^(?=a)(?a|b)+x$/u', null]; + yield 'start anchor' => ['/\Aab\z/', null]; + yield 'end anchor Z' => ['/ab\Z/', null]; + yield 'possessive' => ['/^a++$/', null]; + yield 'possessive braces' => ['/^a{2}+$/', null]; + yield 'possessive question' => ['/^a?+$/', null]; + yield 'atomic group' => ['/^(?>a+)b$/', null]; + yield 'python group' => ['/(?Pa)/', null]; + yield 'inline flag' => ['/(?i)a/', null]; + yield 'scoped flag' => ['/(?i:a)b/', null]; + yield 'horizontal space' => ['/a\hb/', null]; + } + + #[DataProvider('patterns')] + public function testOnlyEcmaCompatiblePatternsReachOpenApi(string $pattern, ?string $expected): void + { + $this->assertSame($expected, new Pattern($pattern)->expression()); + } + + public function testAuthorizationFromAnApacheRewriteIsRead(): void + { + $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] = 'Bearer abc'; + $this->assertSame('Bearer abc', HeaderBag::get('Authorization')); + + $_SERVER['HTTP_AUTHORIZATION'] = 'Bearer direct'; + $this->assertSame('Bearer direct', HeaderBag::get('authorization')); + + unset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'], $_SERVER['HTTP_AUTHORIZATION']); + $this->assertFalse(HeaderBag::has('Authorization')); + } + + public function testTheUnsupportedMediaTypeResponseDescribesItsDetail(): void + { + $legacy = new ResponseBuilder()->build(new R11FormHandler(), new NoAuthorization(), true, new SchemaRegistry()); + $schema = $legacy[415]['content']['application/json; charset=utf-8']['schema']; + $this->assertSame([ + 'type' => 'object', + 'properties' => [ + 'status' => ['type' => 'string', 'enum' => ['error']], + 'message' => ['type' => 'string'], + 'detail' => ['type' => 'string', 'description' => 'Which media types the endpoint reads. Sent only when error details are on.'], + ], + 'required' => ['status', 'message'], + ], $schema); + $this->assertSame('Unsupported media type', $legacy[415]['description']); + + $problem = new ResponseBuilder(true)->build(new R11FormHandler(), new NoAuthorization(), true, new SchemaRegistry()); + $this->assertSame(['$ref' => '#/components/schemas/ProblemDetails'], $problem[415]['content']['application/problem+json; charset=utf-8']['schema']); + } +} + +final readonly class R11Inner +{ + public function __construct(#[Body] public string $q = 'x') + { + } +} + +final readonly class R11QueryDtoInput +{ + public function __construct( + #[Query] public R11Inner $x, + ) { + } +} + +final class R11QueryDtoHandler extends TypedHandler +{ + public function handleDto(R11QueryDtoInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11QueryListInput +{ + /** @param list $many */ + public function __construct( + #[Query] public array $many = [], + ) { + } +} + +final class R11QueryListHandler extends TypedHandler +{ + public function handleDto(R11QueryListInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11DateDefaultInput +{ + public function __construct( + #[Query] public \DateTimeImmutable $d = new \DateTimeImmutable('2020-01-01T00:00:00Z'), + ) { + } +} + +final class R11DateDefaultHandler extends TypedHandler +{ + public function handleDto(R11DateDefaultInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11DtoDefaultInput +{ + public function __construct( + #[Body] public R11Inner $i = new R11Inner(), + ) { + } +} + +final class R11DtoDefaultHandler extends TypedHandler +{ + public function handleDto(R11DtoDefaultInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11ListObjectDefaultInput +{ + /** @param list $items */ + public function __construct( + #[Body] public array $items = [new R11Inner()], + ) { + } +} + +final class R11ListObjectDefaultHandler extends TypedHandler +{ + public function handleDto(R11ListObjectDefaultInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11NullableItemsInput +{ + /** @param list $a */ + public function __construct( + #[Body] public array $a = [], + ) { + } +} + +final class R11NullableItemsHandler extends TypedHandler +{ + public function handleDto(R11NullableItemsInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11UnionItemsInput +{ + /** @param list $a */ + public function __construct( + #[Body] public array $a = [], + ) { + } +} + +final class R11UnionItemsHandler extends TypedHandler +{ + public function handleDto(R11UnionItemsInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11NestedListsInput +{ + /** @param list> $a */ + public function __construct( + #[Body] public array $a = [], + ) { + } +} + +final class R11NestedListsHandler extends TypedHandler +{ + public function handleDto(R11NestedListsInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11AssocInput +{ + /** @param array $a */ + public function __construct( + #[Body] public array $a = [], + ) { + } +} + +final class R11AssocHandler extends TypedHandler +{ + public function handleDto(R11AssocInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11OtherDocInput +{ + /** @param iterable $a */ + public function __construct( + #[Body] public array $a = [], + ) { + } +} + +final class R11OtherDocHandler extends TypedHandler +{ + public function handleDto(R11OtherDocInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11PlainDateTimeInput +{ + public function __construct( + #[Body] public \DateTime $d, + ) { + } +} + +final class R11PlainDateTimeHandler extends TypedHandler +{ + public function handleDto(R11PlainDateTimeInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11DateInterfaceInput +{ + public function __construct( + #[Body] public \DateTimeInterface $d, + ) { + } +} + +final class R11DateInterfaceHandler extends TypedHandler +{ + public function handleDto(R11DateInterfaceInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11EmptySplitInput +{ + /** @param list $a */ + public function __construct( + #[Query] #[Cast(Split::class, '')] public array $a = [], + ) { + } +} + +final class R11EmptySplitHandler extends TypedHandler +{ + public function handleDto(R11EmptySplitInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11SplitIntsInput +{ + /** @param list $a */ + public function __construct( + #[Query] #[Cast(Split::class, ',')] public array $a = [], + ) { + } +} + +final class R11SplitIntsHandler extends TypedHandler +{ + public function handleDto(R11SplitIntsInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11PathDashInput +{ + public function __construct( + #[Path('a-b')] public int $x, + ) { + } +} + +final class R11PathDashHandler extends TypedHandler +{ + public function handleDto(R11PathDashInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11HeaderUnderscoreInput +{ + public function __construct( + #[Header('X_Foo')] public ?string $x = null, + ) { + } +} + +final class R11HeaderUnderscoreHandler extends TypedHandler +{ + public function handleDto(R11HeaderUnderscoreInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11DocFormsInput +{ + /** + * @param list|null $a + * @param ?list $b + * @param null|list $c + * @param string[] $d + * @param non-empty-list $e + * @param list $f + * @phpstan-param list $g + * @psalm-param list $h + */ + public function __construct( + #[Query] public ?array $a = null, + #[Query] public ?array $b = null, + #[Query] public ?array $c = null, + #[Query] public ?array $d = null, + #[Query] public ?array $e = null, + #[Query] public ?array $f = null, + #[Query] public array $g = [], + #[Query] public array $h = [], + ) { + } +} + +final class R11DocFormsHandler extends TypedHandler +{ + public function handleDto(R11DocFormsInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11OptionalInput +{ + public function __construct( + #[Body] public ?string $a = null, + #[Body] public ?R11Color $c = null, + ) { + } +} + +final class R11OptionalHandler extends TypedHandler +{ + public function handleDto(R11OptionalInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11FormInput +{ + public function __construct( + #[Body] public ?string $a = null, + ) { + } +} + +#[Consumes(MediaTypes::MULTIPART)] +final class R11MultipartHandler extends TypedHandler +{ + public function handleDto(R11FormInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final class R11FormHandler extends TypedHandler +{ + public function handleDto(R11FormInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11TextInput +{ + public function __construct( + #[Body] #[Length(max: 3)] public string $text, + ) { + } +} + +final class R11TextHandler extends TypedHandler +{ + public function handleDto(R11TextInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11RangeInput +{ + public function __construct( + #[Query] #[Range(max: 1.0E-12)] public float $x = 0.0, + ) { + } +} + +final class R11RangeHandler extends TypedHandler +{ + public function handleDto(R11RangeInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11DateInput +{ + public function __construct( + #[Body] public \DateTimeImmutable $at, + ) { + } +} + +final class R11DateHandler extends TypedHandler +{ + public function handleDto(R11DateInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11HeaderInput +{ + public function __construct( + #[Header('Authorization')] public ?string $auth = null, + ) { + } +} + +final class R11HeaderHandler extends TypedHandler +{ + public function handleDto(R11HeaderInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +enum R11Color: string +{ + case Red = 'red'; +} + +final readonly class R11TrailingUnionInput +{ + /** @param list|string $a */ + public function __construct(#[Body] public array $a = []) + { + } +} + +final class R11TrailingUnionHandler extends TypedHandler +{ + public function handleDto(R11TrailingUnionInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11ArrayOfArraysInput +{ + /** @param array $a */ + public function __construct(#[Body] public array $a = []) + { + } +} + +final class R11ArrayOfArraysHandler extends TypedHandler +{ + public function handleDto(R11ArrayOfArraysInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11BracketUnionInput +{ + /** @param string[]|int $a */ + public function __construct(#[Body] public array $a = []) + { + } +} + +final class R11BracketUnionHandler extends TypedHandler +{ + public function handleDto(R11BracketUnionInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11ArrayOfListsInput +{ + /** @param array> $a */ + public function __construct(#[Body] public array $a = []) + { + } +} + +final class R11ArrayOfListsHandler extends TypedHandler +{ + public function handleDto(R11ArrayOfListsInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11UnionBracketsInput +{ + /** @param int|string[] $a */ + public function __construct(#[Body] public array $a = []) + { + } +} + +final class R11UnionBracketsHandler extends TypedHandler +{ + public function handleDto(R11UnionBracketsInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11GenericOfArrayInput +{ + /** @param Collection $a */ + public function __construct(#[Body] public array $a = []) + { + } +} + +final class R11GenericOfArrayHandler extends TypedHandler +{ + public function handleDto(R11GenericOfArrayInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11VarFallbackInput +{ + /** @param $a */ + public function __construct( + /** @var list */ + #[Body] public array $a = [], + ) { + } +} + +final class R11VarFallbackHandler extends TypedHandler +{ + public function handleDto(R11VarFallbackInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11BadCaster implements CasterInterface +{ + public function __construct(string $format, $loose = null) + { + throw new \InvalidArgumentException('Bad format'); + } + + public function cast(mixed $value): mixed + { + return $value; + } +} + +final class R11NoCtorCaster implements CasterInterface +{ + public function cast(mixed $value): mixed + { + return $value; + } +} + +final readonly class R11BadCasterInput +{ + public function __construct(#[Query] #[Cast(R11BadCaster::class, 'x')] public ?string $a = null) + { + } +} + +final class R11BadCasterHandler extends TypedHandler +{ + public function handleDto(R11BadCasterInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11NoCtorCasterInput +{ + public function __construct(#[Query] #[Cast(R11NoCtorCaster::class, 'x')] public ?string $a = null) + { + } +} + +final class R11NoCtorCasterHandler extends TypedHandler +{ + public function handleDto(R11NoCtorCasterInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11BudgetInner +{ + public function __construct(#[Body] public string $a, #[Body] public string $b, #[Body] public string $c) + { + } +} + +final readonly class R11BudgetObjectInput +{ + /** @param list $ids */ + public function __construct(#[Body] public array $ids, #[Body] public R11BudgetInner $inner) + { + } +} + +final class R11BudgetObjectHandler extends TypedHandler +{ + public function handleDto(R11BudgetObjectInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11NamedItem +{ + public function __construct(#[Body] #[Length(max: 3)] public string $name) + { + } +} + +final readonly class R11ConstraintBudgetInput +{ + /** @param list $items */ + public function __construct(#[Body] public array $items) + { + } +} + +final class R11ConstraintBudgetHandler extends TypedHandler +{ + public function handleDto(R11ConstraintBudgetInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R11BudgetTopInput +{ + /** @param list $ids */ + public function __construct(#[Body] public array $ids, #[Body] public int $x, #[Body] public int $y) + { + } +} + +final class R11BudgetTopHandler extends TypedHandler +{ + public function handleDto(R11BudgetTopInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} diff --git a/tests/Input/Round12Test.php b/tests/Input/Round12Test.php new file mode 100644 index 000000000..c66711f6b --- /dev/null +++ b/tests/Input/Round12Test.php @@ -0,0 +1,656 @@ + $name . $i . '=1', range(1, $count))); + } + + /** + * @return array>|null + */ + private function post(string $contentType, string $raw, TypedHandler $handler): ?array + { + $_SERVER['CONTENT_TYPE'] = $contentType; + $_SERVER['REQUEST_METHOD'] = 'POST'; + RequestInput::setRawBody($raw); + $processor = new ParamsProcessor($handler->params()); + + return $processor->isError() ? $processor->getErrors() : null; + } + + public function testAPostFormWithMoreFieldsThanMaxInputVarsIsRejected(): void + { + $limit = (int) ini_get('max_input_vars'); + // PHP keeps the first `limit` variables and drops the rest without a word + $_POST = array_fill_keys(array_map(static fn (int $i): string => 'f' . $i, range(1, $limit)), '1'); + + $errors = $this->post('application/x-www-form-urlencoded', self::pairs('f', $limit + 1), new R12FormHandler()); + + $this->assertSame(['body' => ['Too many form fields']], $errors); + } + + public function testAPostFormWithExactlyTheLimitIsAccepted(): void + { + $limit = (int) ini_get('max_input_vars'); + $_POST = array_fill_keys(array_map(static fn (int $i): string => 'f' . $i, range(1, $limit)), '1'); + + $this->assertNull($this->post('application/x-www-form-urlencoded', self::pairs('f', $limit), new R12FormHandler())); + } + + public function testAPostFormIsCountedWithItsNestedValues(): void + { + $limit = (int) ini_get('max_input_vars'); + $_POST = ['a' => array_fill(0, $limit, '1')]; + $raw = implode('&', array_map(static fn (int $i): string => 'a[]=' . $i, range(1, $limit + 1))); + + $this->assertSame(['body' => ['Too many form fields']], $this->post('application/x-www-form-urlencoded', $raw, new R12FormHandler())); + } + + public function testASmallPostFormIsNotParsedAgain(): void + { + $limit = (int) ini_get('max_input_vars'); + $_POST = ['a' => 'x']; + + // the body is not even looked at: PHP cannot have cut a form that fits + $this->assertNull($this->post('application/x-www-form-urlencoded', self::pairs('f', $limit + 1), new R12FormHandler())); + } + + public function testAMultipartPostIsLeftToPhp(): void + { + $limit = (int) ini_get('max_input_vars'); + $_POST = array_fill_keys(array_map(static fn (int $i): string => 'f' . $i, range(1, $limit)), '1'); + + // PHP does not give a multipart body back, so a form that was cut cannot be told from a complete one + $this->assertNull($this->post('multipart/form-data; boundary=x', self::pairs('f', $limit + 1), new R12MultipartHandler())); + } + + #[DataProvider('charsets')] + public function testJsonCharsets(string $contentType, ?string $rejected): void + { + $errors = $this->post($contentType, '{"a":"x"}', new R12FormHandler()); + + if ($rejected === null) { + $this->assertNull($errors, $contentType); + } else { + $this->assertSame(['body' => ['JSON must be UTF-8; the request says charset=' . $rejected]], $errors, $contentType); + } + } + + /** + * @return \Iterator + */ + public static function charsets(): \Iterator + { + yield 'utf-8' => ['application/json; charset=utf-8', null]; + yield 'utf8 spelling' => ['application/json; charset=utf8', null]; + yield 'UTF8 upper case' => ['application/json; charset=UTF8', null]; + yield 'us-ascii' => ['application/json; charset=US-ASCII', null]; + yield 'quoted' => ['application/json; charset="utf-8"', null]; + yield 'spaces around the equals sign' => ['application/json; charset = utf-8', null]; + yield 'trailing space' => ['application/json; charset="UTF-8" ', null]; + yield 'quoted value that only looks like a charset' => ['application/json; foo="a;charset=latin1"', null]; + yield 'the first charset wins' => ['application/json; charset=utf-8; charset=latin1', null]; + yield 'another parameter first' => ['application/json; foo=1; charset=latin1', 'latin1']; + yield 'latin1' => ['application/json; charset=ISO-8859-1', 'iso-8859-1']; + yield 'quoted latin1' => ['application/json;charset="latin1"', 'latin1']; + yield 'long value is cut' => ['application/json; charset=' . str_repeat('X', 100), str_repeat('x', 30)]; + yield 'value of exactly the shown length' => ['application/json; charset=' . str_repeat('y', 30), str_repeat('y', 30)]; + } + + /** + * @return \Iterator, string}> + */ + public static function descriptions(): \Iterator + { + yield 'var with a description' => [R12VarDescriptionHandler::class, 'string']; + yield 'var without a space before the end of the comment' => [R12VarTightHandler::class, 'int']; + yield 'non-empty-list with a description' => [R12VarNonEmptyHandler::class, 'string']; + yield 'phpstan var with a nested generic and a description' => [R12VarGenericHandler::class, 'int']; + } + + /** + * @param class-string $handler + */ + #[DataProvider('descriptions')] + public function testAVarTypeMayBeFollowedByADescription(string $handler, string $item): void + { + $this->assertSame($item, DtoCompiler::compile($handler)->fields[0]->listItem); + } + + /** + * @return \Iterator, string}> + */ + public static function invalid(): \Iterator + { + yield 'associative var with a description' => [R12VarAssocHandler::class, 'documents `array>`, an array that is not a list']; + yield 'array shape item' => [R12ShapeItemHandler::class, 'declare an item DTO']; + yield 'positive-int' => [R12PositiveIntHandler::class, 'PHPStan refinements such as positive-int']; + yield 'non-empty-string' => [R12NonEmptyStringHandler::class, 'documents list. PHPStan refinements']; + yield 'integer range' => [R12IntRangeHandler::class, 'documents list>. PHPStan refinements']; + yield 'generic item' => [R12GenericItemHandler::class, 'documents list>. PHPStan refinements']; + yield 'generic item with a list inside' => [R12ListInsideGenericHandler::class, 'documents list>. PHPStan refinements']; + yield 'dashed name that is no refinement' => [R12DashedItemHandler::class, 'documents list, and that type was not found']; + yield 'DateTime of Nette' => [R12NetteDateHandler::class, 'has type Nette\Utils\DateTime. Use DateTimeImmutable itself']; + yield 'DateTimeImmutable subclass' => [R12MyDateHandler::class, 'has type Tomaj\NetteApi\Test\Input\R12MyDate. Use DateTimeImmutable itself']; + yield 'empty path name' => [R12EmptyPathHandler::class, "for example #[Path('my_name')]"]; + yield 'empty query name' => [R12EmptyQueryHandler::class, "for example #[Query('my_name')]"]; + yield 'empty body name' => [R12EmptyBodyHandler::class, "for example #[Body('my_name')]"]; + yield 'empty header name' => [R12EmptyHeaderHandler::class, "for example #[Header('X-Request-Id')]"]; + yield 'name that starts with a digit' => [R12DigitNameHandler::class, 'must start with a letter or an underscore']; + } + + /** + * @param class-string $handler + */ + #[DataProvider('invalid')] + public function testCompileMessages(string $handler, string $needle): void + { + try { + DtoCompiler::compile($handler); + $this->fail('compiled'); + } catch (\LogicException $exception) { + $this->assertStringContainsString($needle, $exception->getMessage()); + } + } + + /** + * @return \Iterator + */ + public static function patterns(): \Iterator + { + yield 'unicode property with a quantifier' => ['/^\p{L}+$/u', null]; + yield 'braces after an escaped brace' => ['/\{3}+/', null]; + yield 'escaped backslash and A' => ['/\\\\A/', '\\\\A']; + yield 'escaped backslash and a letter that is only PCRE after one more backslash' => ['/a\\\\\\\\A/', 'a\\\\\\\\A']; + yield 'escaped plus then a quantifier' => ['/a\++/', 'a\++']; + yield 'lazy quantifier' => ['/[0-9]+?/', '[0-9]+?']; + yield 'lookbehind' => ['/(?<=a)b/', null]; + yield 'named group' => ['/(?a)/', null]; + yield 'hex code point' => ['/^\x{41}+$/u', null]; + yield 'hex byte' => ['/^\x41+$/', null]; + yield 'posix class' => ['/[[:alpha:]]/', null]; + yield 'comment' => ['/a(?#note)b/', null]; + yield 'branch reset' => ['/(?|a|b)/', null]; + yield 'escape character' => ['/a\e/', null]; + yield 'back reference g' => ['/(a)\g{1}/', null]; + yield 'escaped backslash then possessive' => ['/\\\\++/', null]; + yield 'three backslashes then A' => ['/\\\\\A/', null]; + yield 'possessive after a number of repetitions' => ['/a{2}+/', null]; + yield 'possessive after a range' => ['/[a-z]{2,}+/', null]; + yield 'relative recursion' => ['/(a)(?-1)/', null]; + yield 'numbered recursion' => ['/(a)(?1)/', null]; + yield 'named recursion' => ['/(?a)(?&n)/', null]; + yield 'single quoted group name' => ["/(?'n'a)/", null]; + yield 'non newline escape' => ['/a\N/', null]; + yield 'possessive question' => ['/a?+/', null]; + yield 'possessive star' => ['/a*+/', null]; + } + + #[DataProvider('patterns')] + public function testPatternOmissionFromOpenApi(string $pattern, ?string $expression): void + { + $this->assertSame($expression, new Pattern($pattern)->expression()); + } + + public function testTheNoteAboutAnExhaustedBudgetBelongsToTheFirstFieldWhenNothingReadsABody(): void + { + $_GET = ['ids' => array_fill(0, 150, 'x')]; + $metadata = DtoCompiler::compile(R12QueryBudgetHandler::class); + $mapper = new DtoMapper($metadata); + + $first = $mapper->errors($metadata->fields[0]); + $this->assertCount(101, $first); + $this->assertSame(['Only the first 100 errors are reported, the rest of the request was not checked'], $first['body']); + $this->assertSame([], $mapper->errors($metadata->fields[1])); + } + + public function testTheNoteBelongsToTheFirstBodyFieldEvenWhenAQueryFieldComesFirst(): void + { + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + RequestInput::setRawBody('{"ids":' . json_encode(array_fill(0, 150, 'x')) . '}'); + $metadata = DtoCompiler::compile(R12MixedBudgetHandler::class); + $mapper = new DtoMapper($metadata); + + $this->assertSame([], $mapper->errors($metadata->fields[0])); + $this->assertArrayHasKey('body', $mapper->errors($metadata->fields[1])); + } + + public function testAnErrorOfTheBodyAndTheNoteShareTheKey(): void + { + $this->assertNull($this->post('application/json', '{"a":"x"}', new R12FormHandler())); + RequestInput::reset(); + $errors = $this->post('application/json', '{"ids":' . json_encode(array_fill(0, 101, 'x')) . '}', new R12BodyBudgetHandler()); + + $this->assertCount(101, $errors ?? []); + $this->assertSame(['Only the first 100 errors are reported, the rest of the request was not checked'], $errors['body'] ?? []); + } + + public function testRangePrintsMinusZeroAsZero(): void + { + $context = new ConstraintContext('x', self::class, [], []); + + $this->assertSame('Value must be at most 0', new Range(max: -0.0)->validate(1, $context)); + } +} + +final readonly class R12FormInput +{ + public function __construct(#[Body] public ?string $a = null) + { + } +} + +final class R12FormHandler extends TypedHandler +{ + public function handleDto(R12FormInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +#[Consumes(MediaTypes::MULTIPART)] +final class R12MultipartHandler extends TypedHandler +{ + public function handleDto(R12FormInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R12VarDescriptionInput +{ + public function __construct( + /** @var list Names of the things */ + #[Body] public array $names = [], + ) { + } +} + +final class R12VarDescriptionHandler extends TypedHandler +{ + public function handleDto(R12VarDescriptionInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R12VarTightInput +{ + public function __construct( + /** @var list*/ + #[Body] public array $ids = [], + ) { + } +} + +final class R12VarTightHandler extends TypedHandler +{ + public function handleDto(R12VarTightInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R12VarNonEmptyInput +{ + public function __construct( + /** @var non-empty-list Names of the things */ + #[Body] public array $names = ['a'], + ) { + } +} + +final class R12VarNonEmptyHandler extends TypedHandler +{ + public function handleDto(R12VarNonEmptyInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R12VarGenericInput +{ + public function __construct( + /** @phpstan-var list Numbers: any of them */ + #[Body] public array $numbers = [], + ) { + } +} + +final class R12VarGenericHandler extends TypedHandler +{ + public function handleDto(R12VarGenericInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R12VarAssocInput +{ + public function __construct( + /** @var array> Lists by name */ + #[Body] public array $lists = [], + ) { + } +} + +final class R12VarAssocHandler extends TypedHandler +{ + public function handleDto(R12VarAssocInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R12ShapeItemInput +{ + /** @param list $shapes */ + public function __construct(#[Body] public array $shapes = []) + { + } +} + +final class R12ShapeItemHandler extends TypedHandler +{ + public function handleDto(R12ShapeItemInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R12PositiveIntInput +{ + /** @param list $ids */ + public function __construct(#[Body] public array $ids = []) + { + } +} + +final class R12PositiveIntHandler extends TypedHandler +{ + public function handleDto(R12PositiveIntInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R12NonEmptyStringInput +{ + /** @param list $names */ + public function __construct(#[Body] public array $names = []) + { + } +} + +final class R12NonEmptyStringHandler extends TypedHandler +{ + public function handleDto(R12NonEmptyStringInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R12IntRangeInput +{ + /** @param list> $ids */ + public function __construct(#[Body] public array $ids = []) + { + } +} + +final class R12IntRangeHandler extends TypedHandler +{ + public function handleDto(R12IntRangeInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R12GenericItemInput +{ + /** @param list> $items */ + public function __construct(#[Body] public array $items = []) + { + } +} + +final class R12GenericItemHandler extends TypedHandler +{ + public function handleDto(R12GenericItemInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R12NetteDateInput +{ + public function __construct(#[Body] public ?DateTime $at = null) + { + } +} + +final class R12NetteDateHandler extends TypedHandler +{ + public function handleDto(R12NetteDateInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +class R12MyDate extends \DateTimeImmutable +{ +} + +final readonly class R12MyDateInput +{ + public function __construct(#[Body] public ?R12MyDate $at = null) + { + } +} + +final class R12MyDateHandler extends TypedHandler +{ + public function handleDto(R12MyDateInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R12EmptyPathInput +{ + public function __construct(#[Path('')] public int $id) + { + } +} + +final class R12EmptyPathHandler extends TypedHandler +{ + public function handleDto(R12EmptyPathInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R12EmptyQueryInput +{ + public function __construct(#[Query('')] public ?int $page = null) + { + } +} + +final class R12EmptyQueryHandler extends TypedHandler +{ + public function handleDto(R12EmptyQueryInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R12EmptyBodyInput +{ + public function __construct(#[Body('')] public ?int $page = null) + { + } +} + +final class R12EmptyBodyHandler extends TypedHandler +{ + public function handleDto(R12EmptyBodyInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R12EmptyHeaderInput +{ + public function __construct(#[Header('')] public ?string $id = null) + { + } +} + +final class R12EmptyHeaderHandler extends TypedHandler +{ + public function handleDto(R12EmptyHeaderInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R12DigitNameInput +{ + public function __construct(#[Query('0a')] public ?int $page = null) + { + } +} + +final class R12DigitNameHandler extends TypedHandler +{ + public function handleDto(R12DigitNameInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R12QueryBudgetInput +{ + /** @param list $ids */ + public function __construct(#[Query] public array $ids = [], #[Query] public int $page = 1) + { + } +} + +final class R12QueryBudgetHandler extends TypedHandler +{ + public function handleDto(R12QueryBudgetInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R12BodyBudgetInput +{ + /** @param list $ids */ + public function __construct(#[Body] public array $ids = []) + { + } +} + +final class R12BodyBudgetHandler extends TypedHandler +{ + public function handleDto(R12BodyBudgetInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R12ListInsideGenericInput +{ + /** @param list> $items */ + public function __construct(#[Body] public array $items = []) + { + } +} + +final class R12ListInsideGenericHandler extends TypedHandler +{ + public function handleDto(R12ListInsideGenericInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R12DashedItemInput +{ + /** @param list $items */ + public function __construct(#[Body] public array $items = []) + { + } +} + +final class R12DashedItemHandler extends TypedHandler +{ + public function handleDto(R12DashedItemInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R12MixedBudgetInput +{ + /** @param list $ids */ + public function __construct(#[Query] public int $page = 1, #[Body] public array $ids = []) + { + } +} + +final class R12MixedBudgetHandler extends TypedHandler +{ + public function handleDto(R12MixedBudgetInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} diff --git a/tests/Input/Round13Test.php b/tests/Input/Round13Test.php new file mode 100644 index 000000000..26575093a --- /dev/null +++ b/tests/Input/Round13Test.php @@ -0,0 +1,409 @@ +clean(); + } + + protected function tearDown(): void + { + $this->clean(); + } + + private function clean(): void + { + RequestInput::reset(); + PathValues::reset(); + $_GET = []; + $_POST = []; + unset($_SERVER['HTTP_X_T'], $_SERVER['CONTENT_TYPE'], $_SERVER['REQUEST_METHOD']); + } + + /** + * @return array> + */ + private function errors(TypedHandler $handler): array + { + $processor = new ParamsProcessor($handler->params()); + $this->assertTrue($processor->isError()); + + return $processor->getErrors(); + } + + /** + * @return \Iterator + */ + public static function patterns(): \Iterator + { + yield 'zip code' => ['/^[0-9]{5}$/', true]; + yield 'with the flags u and D' => ['/^[a-z]+$/uD', true]; + yield 'other delimiters' => ['#^[a-z]+$#', true]; + yield 'brackets as delimiters' => ['{^[a-z]+$}', true]; + yield 'alternatives' => ['/^(?:ab|cd)$/', true]; + yield 'alternative at the top' => ['/^a|b$/', true]; + yield 'empty alternative' => ['/^(a|)$/', true]; + yield 'empty group' => ['/^()$/', true]; + yield 'a capturing group' => ['/^(ab)+$/', true]; + yield 'lookahead' => ['/^(?=a)a$/', true]; + yield 'negative lookahead' => ['/^(?!a)b$/', true]; + yield 'greedy and lazy quantifiers' => ['/^a*b+?c??d{2}e{2,}f{2,3}?$/', true]; + yield 'quantified group' => ['/^(?:a|b){2,3}$/', true]; + yield 'escaped punctuation' => ['/^\\\\\^\$\.\*\+\?\(\)\[\]\{\}\|\/$/', true]; + yield 'escaped whitespace' => ['/^\n\r\t$/', true]; + yield 'class with literals and a range' => ['/^[A-Za-z0-9._%+-]+$/', true]; + yield 'class with escapes' => ['/^[\-\]\\\\\n\.\^]+$/', true]; + yield 'dash at the start of a class' => ['/^[-a]+$/', true]; + yield 'caret inside a class' => ['/^[a^]+$/', true]; + yield 'space and punctuation' => ['/^a b,c;d:e=f#g%h&i-j@k!l~m"n\'o

q`r_s$/', true]; + yield 'digits and word characters without u' => ['/^\w+\d\b$/', true]; + yield 'word boundary' => ['/^\ba\b$/', true]; + yield 'nested groups' => ['/^((a)(b))$/', true]; + + yield 'digits with u' => ['/^\d+$/u', false]; + yield 'word characters with u' => ['/^\w+$/u', false]; + yield 'word boundary with u' => ['/^\ba$/u', false]; + yield 'digits with u and D' => ['/^\d$/uD', false]; + yield 'the dot' => ['/^a.b$/', false]; + yield 'negated class' => ['/^[^a]$/', false]; + yield 'whitespace class' => ['/^\s+$/', false]; + yield 'negated digit' => ['/^\D+$/', false]; + yield 'negated word' => ['/^\W+$/', false]; + yield 'negated boundary' => ['/^\B$/', false]; + yield 'unicode property' => ['/^\p{L}+$/u', false]; + yield 'short unicode property' => ['/^\pL+$/u', false]; + yield 'hex escape' => ['/^\x41$/', false]; + yield 'vertical whitespace' => ['/^\v$/', false]; + yield 'back reference' => ['/^(a)\1$/', false]; + yield 'escaped dash outside a class' => ['/^\-$/', false]; + yield 'escaped at sign' => ['/^a\@$/', false]; + yield 'escaped underscore' => ['/^\_$/', false]; + yield 'escaped delimiter other than slash' => ['#^\#$#', false]; + yield 'class escape other than punctuation' => ['/^[\d]$/', false]; + yield 'class with the closing bracket first' => ['/^[]a]$/', false]; + yield 'empty negated class' => ['/^[^]a]$/', false]; + yield 'a bracket inside a class' => ['/^[[]$/', false]; + yield 'unescaped closing bracket' => ['/^a]$/', false]; + yield 'unescaped closing brace' => ['/^a}$/', false]; + yield 'unescaped opening brace' => ['/^a{$/', false]; + yield 'quantifier without a minimum' => ['/^a{,3}$/', false]; + yield 'double quantifier' => ['/^a{2}{3}$/', false]; + yield 'quantifier after an anchor' => ['/^?a$/', false]; + yield 'possessive' => ['/^a++$/', false]; + yield 'quantified lookahead' => ['/^(?=a)*a$/', false]; + yield 'quantified word boundary' => ['/^\b+a$/', false]; + yield 'named group' => ['/^(?a)$/', false]; + yield 'lookbehind' => ['/(?<=a)b/', false]; + yield 'atomic group' => ['/^(?>a)$/', false]; + yield 'inline flag' => ['/^(?i)a$/', false]; + yield 'case insensitive flag' => ['/^a$/i', false]; + yield 'multiline flag' => ['/^a$/m', false]; + yield 'extended flag' => ['/^a$/x', false]; + yield 'dot all flag' => ['/^a$/s', false]; + yield 'a non ASCII letter' => ['/^é$/', false]; + yield 'a non ASCII letter in a class' => ['/^[é]$/u', false]; + yield 'a control character' => ["/^a\tb\$/", false]; + yield 'an unclosed group is not valid anyway but a stray bracket is' => ['/^(a))$/', false]; + yield 'start of subject anchor' => ['/\Aa\z/', false]; + } + + #[DataProvider('patterns')] + public function testOnlyAPatternThatMeansTheSameInEcma262IsExported(string $pattern, bool $portable): void + { + $expression = null; + try { + $expression = new Pattern($pattern)->expression(); + } catch (\InvalidArgumentException) { + $this->assertFalse($portable, $pattern); + + return; + } + + $this->assertSame($portable ? substr($pattern, 1, strrpos($pattern, $pattern[0] === '{' ? '}' : $pattern[0]) - 1) : null, $expression, $pattern); + } + + public function testAPortablePatternIsDocumentedAsPatternAndTheOthersAsXPattern(): void + { + $fields = DtoCompiler::compile(R13PatternHandler::class)->fields; + + $this->assertSame(['type' => 'string', 'pattern' => '^[0-9]{5}$'], SchemaBuilder::build($fields[0], true)); + $this->assertSame(['type' => 'string', 'x-pattern' => '/^\p{Lu}[a-z]+$/u'], SchemaBuilder::build($fields[1], true)); + $this->assertSame(['type' => 'string', 'x-pattern' => '/^[a-z]+$/i'], SchemaBuilder::build($fields[2], true)); + $this->assertSame(['type' => 'string', 'minLength' => 2, 'pattern' => '^aa$'], SchemaBuilder::build($fields[3], true)); + } + + public function testThePatternIsStillCheckedWhateverIsExported(): void + { + $_GET = ['name' => 'ada']; + + $this->assertSame(['name' => ['Value must match the pattern /^\p{Lu}[a-z]+$/u']], $this->errors(new R13NameHandler())); + } + + /** + * @return \Iterator + */ + public static function invalidUtf8(): \Iterator + { + yield 'latin 1 letter' => ["\xE9"]; + yield 'lone continuation byte' => ["a\x80b"]; + yield 'truncated sequence' => ["abc\xE2\x82"]; + yield 'overlong slash' => ["\xC0\xAF"]; + yield 'surrogate' => ["\xED\xA0\x80"]; + yield 'beyond the last code point' => ["\xF4\x90\x80\x80"]; + } + + #[DataProvider('invalidUtf8')] + public function testInvalidUtf8InAQueryStringIsRejected(string $value): void + { + $_GET = ['q' => $value]; + + $this->assertSame(['q' => ['Value must be valid UTF-8']], $this->errors(new R13Handler())); + } + + public function testInvalidUtf8InAHeaderIsRejected(): void + { + $_SERVER['HTTP_X_T'] = "\xE9"; + + $this->assertSame(['X-T' => ['Value must be valid UTF-8']], $this->errors(new R13Handler())); + } + + public function testInvalidUtf8InAPathValueIsRejected(): void + { + PathValues::set(['id' => "\xE9"]); + + $this->assertSame(['id' => ['Value must be valid UTF-8']], $this->errors(new R13PathHandler())); + } + + public function testInvalidUtf8InAFormValueIsRejected(): void + { + $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_POST = ['name' => "\xE9"]; + RequestInput::setRawBody('name=%E9'); + + $this->assertSame(['name' => ['Value must be valid UTF-8']], $this->errors(new R13FormHandler())); + } + + public function testInvalidUtf8InAnItemOfAListIsRejectedWithItsPosition(): void + { + $_GET = ['tags' => ['ok', "\xE9"]]; + + $this->assertSame(['tags[1]' => ['Value must be valid UTF-8']], $this->errors(new R13ListHandler())); + } + + public function testInvalidUtf8IsReportedInsteadOfAMisleadingLengthOrPatternMessage(): void + { + $_GET = ['short' => "\xE9\xE9\xE9", 'u' => "\xE9"]; + + $this->assertSame([ + 'short' => ['Value must be valid UTF-8'], + 'u' => ['Value must be valid UTF-8'], + ], $this->errors(new R13LengthHandler())); + } + + public function testInvalidUtf8ForAStringBackedEnumIsAnUnknownCase(): void + { + $_GET = ['kind' => "\xE9"]; + + $this->assertSame(['kind' => ['Value must be one of: a, b']], $this->errors(new R13EnumHandler())); + } + + public function testValidUtf8IsAccepted(): void + { + $_GET = ['q' => 'žluťoučký kůň 😀', 'short' => '', 'u' => 'é']; + $_SERVER['HTTP_X_T'] = 'ž'; + PathValues::set(['id' => 'é']); + + $this->assertFalse(new ParamsProcessor(new R13Handler()->params())->isError()); + $this->assertFalse(new ParamsProcessor(new R13PathHandler()->params())->isError()); + $this->assertFalse(new ParamsProcessor(new R13LengthHandler()->params())->isError()); + } + + public function testAJsonStringWithSomethingThatLooksLikeInvalidUtf8EscapesIsFine(): void + { + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + RequestInput::setRawBody('{"name":"\u00e9"}'); + + $this->assertFalse(new ParamsProcessor(new R13FormHandler()->params())->isError()); + } + + public function testAHandlerWithParamsKeepsAcceptingAnyBytes(): void + { + $_GET = ['q' => "\xE9"]; + $handler = new class extends BaseHandler { + public function params(): array + { + return [new GetInputParam('q')]; + } + + public function handle(array $params): ResponseInterface + { + return new JsonApiResponse(200, []); + } + }; + + $this->assertFalse(new ParamsProcessor($handler->params())->isError()); + } +} + +final readonly class R13PatternInput +{ + public function __construct( + #[Query] #[Pattern('/^[0-9]{5}$/')] public string $zip, + #[Query] #[Pattern('/^\p{Lu}[a-z]+$/u')] public string $name, + #[Query] #[Pattern('/^[a-z]+$/i')] public string $code, + #[Query] #[Length(min: 2)] #[Pattern('/^aa$/')] public string $both, + ) { + } +} + +final class R13PatternHandler extends TypedHandler +{ + public function handleDto(R13PatternInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R13NameInput +{ + public function __construct(#[Query] #[Pattern('/^\p{Lu}[a-z]+$/u')] public string $name) + { + } +} + +final class R13NameHandler extends TypedHandler +{ + public function handleDto(R13NameInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R13Input +{ + public function __construct( + #[Query] public string $q = 'd', + #[Header('X-T')] public string $h = 'd', + ) { + } +} + +final class R13Handler extends TypedHandler +{ + public function handleDto(R13Input $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R13PathInput +{ + public function __construct(#[Path] public string $id) + { + } +} + +final class R13PathHandler extends TypedHandler +{ + public function handleDto(R13PathInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R13FormInput +{ + public function __construct(#[Body] public string $name) + { + } +} + +final class R13FormHandler extends TypedHandler +{ + public function handleDto(R13FormInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R13ListInput +{ + /** + * @param list $tags + */ + public function __construct(#[Query] public array $tags = []) + { + } +} + +final class R13ListHandler extends TypedHandler +{ + public function handleDto(R13ListInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class R13LengthInput +{ + public function __construct( + #[Query] #[Length(max: 2)] public string $short = 'x', + #[Query] #[Pattern('/^.+$/u')] public string $u = 'a', + ) { + } +} + +final class R13LengthHandler extends TypedHandler +{ + public function handleDto(R13LengthInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +enum R13Kind: string +{ + case A = 'a'; + case B = 'b'; +} + +final readonly class R13EnumInput +{ + public function __construct(#[Query] public R13Kind $kind) + { + } +} + +final class R13EnumHandler extends TypedHandler +{ + public function handleDto(R13EnumInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} diff --git a/tests/Input/ScalarCoercerTest.php b/tests/Input/ScalarCoercerTest.php new file mode 100644 index 000000000..80ad79c66 --- /dev/null +++ b/tests/Input/ScalarCoercerTest.php @@ -0,0 +1,135 @@ +assertSame(2, ScalarCoercer::toInt(2)); + $this->assertSame(2, ScalarCoercer::toInt('2')); + $this->assertSame(2, ScalarCoercer::toInt('+2')); + $this->assertSame(2, ScalarCoercer::toInt('02')); + $this->assertSame(-3, ScalarCoercer::toInt('-3')); + $this->assertSame(0, ScalarCoercer::toInt('-0')); + $this->assertSame(PHP_INT_MAX, ScalarCoercer::toInt((string) PHP_INT_MAX)); + + foreach (['1a', 'x1', '1.0', ' 1', '', '1 ', '+', '-', true, 1.5, null, []] as $value) { + try { + ScalarCoercer::toInt($value); + $this->fail('accepted ' . var_export($value, true)); + } catch (ConversionFailed $exception) { + $this->assertSame('Value must be an integer', $exception->getMessage()); + } + } + $this->expectException(ConversionFailed::class); + ScalarCoercer::toInt((string) PHP_INT_MAX . '0'); + } + + public function testFloats(): void + { + $this->assertEqualsWithDelta(2.0, ScalarCoercer::toFloat(2), PHP_FLOAT_EPSILON); + $this->assertEqualsWithDelta(1.5, ScalarCoercer::toFloat(1.5), PHP_FLOAT_EPSILON); + $this->assertEqualsWithDelta(1.5, ScalarCoercer::toFloat('1.5'), PHP_FLOAT_EPSILON); + $this->assertEqualsWithDelta(0.5, ScalarCoercer::toFloat('.5'), PHP_FLOAT_EPSILON); + $this->assertEqualsWithDelta(100.0, ScalarCoercer::toFloat('1e2'), PHP_FLOAT_EPSILON); + $this->assertEqualsWithDelta(0.015, ScalarCoercer::toFloat('+1.5e-2'), PHP_FLOAT_EPSILON); + + foreach (['1a', 'nan', 'INF', '-INF', '', ' 1', true] as $value) { + try { + ScalarCoercer::toFloat($value); + $this->fail('accepted ' . var_export($value, true)); + } catch (ConversionFailed $exception) { + $this->assertSame('Value must be a number', $exception->getMessage()); + } + } + $this->expectException(ConversionFailed::class); + ScalarCoercer::toFloat(NAN); + } + + public function testFloatRejectsInfinity(): void + { + $this->expectException(ConversionFailed::class); + ScalarCoercer::toFloat(INF); + } + + public function testBooleans(): void + { + $this->assertTrue(ScalarCoercer::toBool(true)); + $this->assertFalse(ScalarCoercer::toBool(false)); + $this->assertTrue(ScalarCoercer::toBool(1)); + $this->assertFalse(ScalarCoercer::toBool(0)); + $this->assertTrue(ScalarCoercer::toBool('TRUE')); + $this->assertFalse(ScalarCoercer::toBool('False')); + $this->assertTrue(ScalarCoercer::toBool('1')); + $this->assertFalse(ScalarCoercer::toBool('0')); + + foreach (['yes', '2', '', 2, null, []] as $value) { + try { + ScalarCoercer::toBool($value); + $this->fail('accepted ' . var_export($value, true)); + } catch (ConversionFailed $exception) { + $this->assertSame('Value must be a boolean', $exception->getMessage()); + } + } + } + + public function testStringsAndDateTimes(): void + { + $this->assertSame('ada', ScalarCoercer::toString('ada')); + $this->expectException(ConversionFailed::class); + ScalarCoercer::toString(1); + } + + public function testDateTimeAcceptsRfc3339(): void + { + $date = ScalarCoercer::toDateTime('2026-11-06T14:30:00+01:00'); + $this->assertSame('2026-11-06T14:30:00+01:00', $date->format('Y-m-d\TH:i:sP')); + + $utc = ScalarCoercer::toDateTime('2026-11-06T13:30:00Z'); + $this->assertSame('+00:00', $utc->format('P')); + + $fraction = ScalarCoercer::toDateTime('2026-11-06T14:30:00.5+01:00'); + $this->assertSame('500000', $fraction->format('u')); + } + + public function testDateTimeRejectsIncompleteValues(): void + { + foreach (['2026-11-06', '2026-11-06T14:30:00', '2026-02-31T14:30:00Z', '2026-11-06T14:30:00+01', 1, ''] as $value) { + try { + ScalarCoercer::toDateTime($value); + $this->fail('accepted ' . var_export($value, true)); + } catch (ConversionFailed $exception) { + $this->assertSame('DateTime must be a valid RFC 3339 date and time', $exception->getMessage()); + } + } + } + + public function testEnums(): void + { + $this->assertSame(UserStatus::Active, ScalarCoercer::toEnum('active', UserStatus::class)); + $this->assertSame(Priority::High, ScalarCoercer::toEnum('2', Priority::class)); + $this->assertSame(Priority::High, ScalarCoercer::toEnum(2, Priority::class)); + + try { + ScalarCoercer::toEnum('nope', UserStatus::class); + $this->fail('accepted unknown enum'); + } catch (ConversionFailed $exception) { + $this->assertSame('Value must be one of: active, disabled', $exception->getMessage()); + } + try { + ScalarCoercer::toEnum('1a', Priority::class); + $this->fail('accepted bad int enum'); + } catch (ConversionFailed $exception) { + $this->assertSame('Value must be one of: 1, 2', $exception->getMessage()); + } + } +} diff --git a/tests/Input/TypeNameTest.php b/tests/Input/TypeNameTest.php new file mode 100644 index 000000000..3c6fecbbc --- /dev/null +++ b/tests/Input/TypeNameTest.php @@ -0,0 +1,125 @@ +assertSame('string', TypeName::resolve(' string ', $scope)); + $this->assertSame('string', TypeName::resolve('\\string', $scope)); + $this->assertSame('int', TypeName::resolve('Int', $scope)); + // `use ... as RangeAlias ;` with a space before the semicolon is still an import + $this->assertSame(Range::class, TypeName::resolve(' RangeAlias ', $scope)); + $this->assertSame(Range::class, TypeName::resolve('rangealias', $scope)); + // a leading backslash is fully qualified, imports do not apply + $this->assertSame('RangeAlias', TypeName::resolve('\\RangeAlias', $scope)); + $this->assertSame(\DateTimeImmutable::class, TypeName::resolve('\\DateTimeImmutable', $scope)); + $this->assertSame(Email::class, TypeName::resolve('EmailAlias', $scope)); + $this->assertSame('Tomaj\\NetteApi\\Test\\Input\\Fixtures\\Email', TypeName::resolve('Email', $scope)); + $this->assertSame(Query::class, TypeName::resolve('Q', $scope)); + $this->assertSame(Body::class, TypeName::resolve('Body', $scope)); + $this->assertSame(File::class, TypeName::resolve('File', $scope)); + $this->assertSame('Myfunction\\Widget', TypeName::resolve('Widget', $scope)); + $this->assertSame('Myfunction\\Widget\\Part', TypeName::resolve('Widget\\Part', $scope)); + $this->assertSame('Tomaj\\NetteApi\\Validation\\Sub\\Thing', TypeName::resolve('Validation\\Sub\\Thing', $scope)); + $this->assertSame('Tomaj\\NetteApi\\Test\\Input\\Fixtures\\Other\\Thing', TypeName::resolve('Other\\Thing', $scope)); + $this->assertSame('Tomaj\\NetteApi\\Test\\Input\\Fixtures\\Ghost', TypeName::resolve('Ghost', $scope)); + $this->assertSame('Tomaj\\NetteApi\\Test\\Input\\Fixtures\\strlen', TypeName::resolve('strlen', $scope)); + $this->assertSame('Tomaj\\NetteApi\\Test\\Input\\Fixtures\\Trait1', TypeName::resolve('Trait1', $scope)); + $this->assertSame('Tomaj\\NetteApi\\Test\\Input\\Fixtures\\Captured', TypeName::resolve('Captured', $scope)); + eval('namespace FooEval { class Bar {} }'); + $this->assertSame('FooEval\\Widget', TypeName::resolve('Widget', new \ReflectionClass(Bar::class))); + } + + public function testImportsBelongToTheNamespaceBlockOfTheClass(): void + { + $scope = new \ReflectionClass(SecondScope::class); + $this->assertSame('Second\\Imported\\Widget', TypeName::resolve('Widget', $scope)); + $this->assertSame('Tomaj\\NetteApi\\Test\\Input\\Fixtures\\EmailAlias', TypeName::resolve('EmailAlias', $scope)); + } + + public function testImportsOfCode(): void + { + $code = <<<'PHP_WRAP' + assertSame([ + 'bar' => 'Foo\Bar', + 'q' => 'Baz\Qux', + 'one' => 'Group\Sub\One', + 'deux' => 'Group\Sub\Two', + 'three' => 'Group\Sub\Three', + 'plain' => 'Plain', + 'klass' => 'After\Klass', + ], TypeName::importsOf($code, 'App\Api')); + $this->assertSame([], TypeName::importsOf($code, 'Other')); + $this->assertSame([], TypeName::importsOf('', '')); + $this->assertSame(['b' => 'A\B', 'c' => 'C'], TypeName::importsOf('assertSame(['only' => 'A\Only'], TypeName::importsOf($code, 'First')); + $this->assertSame(['here' => 'B\Here', 'd' => 'C\D'], TypeName::importsOf($code, 'Second\Level')); + $this->assertSame(['thing' => 'Global\Thing'], TypeName::importsOf($code, '')); + } + + public function testDollarBraceInterpolationKeepsTheDepth(): void + { + $code = 'assertSame(['import' => 'Late\Import'], TypeName::importsOf($code, 'N')); + } +} + diff --git a/tests/Misc/ConsoleRequestTest.php b/tests/Misc/ConsoleRequestTest.php index c15e52aa0..ef6f566d7 100644 --- a/tests/Misc/ConsoleRequestTest.php +++ b/tests/Misc/ConsoleRequestTest.php @@ -4,9 +4,132 @@ namespace Tomaj\NetteApi\Test\Params; +use Tomaj\NetteApi\EndpointInterface; use PHPUnit\Framework\TestCase; use Tomaj\NetteApi\Misc\ConsoleRequest; use Tomaj\NetteApi\Handlers\EchoHandler; +use Tomaj\NetteApi\EndpointIdentifier; +use Tomaj\NetteApi\Test\Input\Fixtures\AvatarHandler; +use Tomaj\NetteApi\Test\Input\Fixtures\CreateOrderHandler; +use Tomaj\NetteApi\Test\Input\Fixtures\UserDetailHandler; +use Tomaj\NetteApi\Link\ApiLink; +use Nette\Application\LinkGenerator; +use Nette\Application\Routers\RouteList; +use Nette\Http\UrlScript; +use Nette\Http\FileUpload; +use Tomaj\NetteApi\Handlers\TypedHandler; +use Tomaj\NetteApi\Input\Body; +use Tomaj\NetteApi\Input\Consumes; +use Tomaj\NetteApi\Input\MediaTypes; +use Tomaj\NetteApi\Input\File; +use Tomaj\NetteApi\Input\FileUpload as InputFileUpload; +use Tomaj\NetteApi\Input\Header; +use Tomaj\NetteApi\Response\JsonApiResponse; +use Tomaj\NetteApi\Validation\Length; +use Tomaj\NetteApi\Validation\Pattern; +use Tomaj\NetteApi\Response\ResponseInterface; + +final readonly class ConsoleInnerInput +{ + public function __construct(#[Body] public int $b = 0) + { + } +} + +final readonly class ConsoleMetaInput +{ + public function __construct( + #[Body] public ?ConsoleInnerInput $a = null, + #[Body] public bool $t = false, + #[Body] public bool $f = false, + #[Body] public ?string $n = null, + ) { + } +} + +final readonly class ConsoleWireInput +{ + /** + * @param list $ids + * @param list $flags + */ + public function __construct( + #[Body] public int $count = 0, + #[Body] public float $ratio = 0.0, + #[Body] public bool $on = false, + #[Body] public bool $off = true, + #[Body] public int $bad = 0, + #[Body] public array $ids = [], + #[Body] public array $flags = [], + #[Body] public ?ConsoleMetaInput $meta = null, + #[Body] public ?string $tags = null, + #[Header('X-Tag')] public ?string $header = null, + #[File] public ?InputFileUpload $doc = null, + ) { + } +} + +final class ConsoleWireHandler extends TypedHandler +{ + public function handleDto(ConsoleWireInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class ConsoleTextInput +{ + public function __construct( + #[Body] #[Length(min: 3)] public string $name, + #[Header('X-Need')] public string $need, + #[Body] #[Pattern('/^[a-z]+$/i')] public string $ci = 'abc', + #[Header('X-Other')] public ?string $other = null, + ) { + } +} + +final class ConsoleTextHandler extends TypedHandler +{ + public function handleDto(ConsoleTextInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class ConsoleFormInput +{ + public function __construct( + #[Body] public int $count = 0, + #[Body] public bool $on = false, + #[Body] public ?ConsoleMetaInput $meta = null, + ) { + } +} + +#[Consumes(MediaTypes::FORM)] +final class ConsoleFormHandler extends TypedHandler +{ + public function handleDto(ConsoleFormInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class ConsoleMultipartInput +{ + public function __construct(#[Body] public int $count = 0) + { + } +} + +#[Consumes(MediaTypes::MULTIPART)] +final class ConsoleMultipartHandler extends TypedHandler +{ + public function handleDto(ConsoleMultipartInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} final class ConsoleRequestTest extends TestCase { @@ -28,4 +151,234 @@ public function testMultiValueKeysAreMappedToTheirParam(): void $this->assertSame('http://127.0.0.1:23523/?status=ok&message=Hello', $response->getUrl()); } + + public function testTypedPathAndHeaderGoToTheirSources(): void + { + $endpoint = new EndpointIdentifier('GET', 1, 'users', '{id}/detail'); + $request = new ConsoleRequest(new UserDetailHandler(), $endpoint, self::localLink()); + $response = $request->makeRequest('ignored', 'GET', ['id' => '4/2 x', 'limit' => '5', 'X-Request-Id' => "abc\r\nX-Evil: 1"]); + + $this->assertSame('http://127.0.0.1:23523/api/v1/users/4%2F2%20x/detail?limit=5', $response->getUrl()); + $this->assertSame(['X-Request-Id: abcX-Evil: 1'], $response->getHeaders()); + $this->assertSame([], $response->getPostFields()); + $this->assertNull($response->getRawPost()); + } + + public function testAnOverriddenLinkStillDecidesTheUrlWhenThereAreValuesForThePath(): void + { + $link = new class (self::localLinkGenerator()) extends ApiLink { + public function link(EndpointInterface $endpoint, $params = []): string + { + return 'custom:' . parent::link($endpoint, $params); + } + }; + $detail = new EndpointIdentifier('GET', 1, 'users', '{id}/detail'); + + // link() keeps its 3.x signature and leaves a {name} segment literal + $this->assertSame('custom:http://127.0.0.1:23523/api/v1/users/{id}/detail', $link->link($detail)); + $this->assertSame('http://127.0.0.1:23523/api/v1/users/{id}/detail?x=1', self::localLink()->link($detail, ['x' => 1])); + + // the console fills the segments of whatever link() returned, with or without path values + $request = new ConsoleRequest(new UserDetailHandler(), $detail, $link); + $this->assertSame('custom:http://127.0.0.1:23523/api/v1/users/7/detail?limit=5', $request->makeRequest('ignored', 'GET', ['id' => '7', 'limit' => '5'])->getUrl()); + $request = new ConsoleRequest(new EchoHandler(), new EndpointIdentifier('POST', 1, 'users', 'create'), $link); + $this->assertStringStartsWith('custom:http://127.0.0.1:23523/api/v1/users/create', $request->makeRequest('ignored', 'POST', [])->getUrl()); + } + + public function testABlankPathValueIsNotSentButExplained(): void + { + foreach (['', ' '] as $blank) { + $request = new ConsoleRequest(new UserDetailHandler()); + $response = $request->makeRequest('http://127.0.0.1:23523/api/v1/users/{id}/detail', 'GET', ['id' => $blank, 'limit' => '5']); + + $this->assertTrue($response->isError()); + $this->assertSame("The path value 'id' is empty. Fill it in and send the request again.", $response->getErrorMessage()); + $this->assertSame(0, $response->getErrorNumber()); + $this->assertSame(0, $response->getResponseTime()); + $this->assertSame('http://127.0.0.1:23523/api/v1/users/{id}/detail', $response->getUrl()); + $this->assertSame('GET', $response->getMethod()); + } + } + + public function testPathIsSubstitutedWithoutALinkGenerator(): void + { + $request = new ConsoleRequest(new UserDetailHandler()); + $response = $request->makeRequest('http://127.0.0.1:23523/api/v1/users/{id}/detail', 'GET', ['id' => '42']); + + $this->assertSame('http://127.0.0.1:23523/api/v1/users/42/detail', $response->getUrl()); + } + + public function testTypedBodyIsSentAsJsonWithWireTypes(): void + { + $request = new ConsoleRequest(new CreateOrderHandler()); + $response = $request->makeRequest('http://127.0.0.1:23523/', 'POST', [ + 'customerEmail' => 'a@example.com', + 'address' => '{"street":"Main","postalCode":"12345"}', + 'items___0' => '{"sku":"A","quantity":2}', + 'items___1' => 'not json', + ]); + + $this->assertSame('http://127.0.0.1:23523/', $response->getUrl()); + $this->assertSame(['Content-Type: application/json'], $response->getHeaders()); + $this->assertSame( + '{"customerEmail":"a@example.com","address":{"street":"Main","postalCode":"12345"},"items":[{"sku":"A","quantity":2},"not json"]}', + $response->getRawPost(), + ); + } + + public function testTypedBodyWithAFileIsSentAsMultipart(): void + { + $file = new FileUpload(['name' => 'a.png', 'type' => 'image/png', 'size' => 3, 'tmp_name' => __FILE__, 'error' => UPLOAD_ERR_OK]); + $request = new ConsoleRequest(new AvatarHandler()); + $response = $request->makeRequest('http://127.0.0.1:23523/', 'POST', ['displayName' => 'Jane', 'avatar' => $file]); + + $fields = $response->getPostFields(); + $this->assertSame(['avatar', 'displayName'], array_keys($fields)); + $this->assertInstanceOf(\CURLFile::class, $fields['avatar']); + $this->assertSame('Jane', $fields['displayName']); + $this->assertNull($response->getRawPost()); + $this->assertSame([], $response->getHeaders()); + } + + public function testBodyScalarsAreSentWithTheirWireTypes(): void + { + $request = new ConsoleRequest(new ConsoleWireHandler()); + $response = $request->makeRequest('http://127.0.0.1:23523/', 'POST', [ + 'count' => ' 7 ', 'ratio' => '2', 'tags' => 'a/b č', 'on' => ' true ', 'off' => ' 0', 'bad' => '1.5', + 'ids___0' => '3', 'ids___1' => 'x', 'flags___0' => 'false', 'flags___1' => '1', 'flags___2' => 'maybe', + 'X-Tag' => 'a', + ]); + + $this->assertSame(['X-Tag: a', 'Content-Type: application/json'], $response->getHeaders()); + $this->assertSame( + '{"count":7,"ratio":2.0,"tags":"a/b č","on":true,"off":false,"bad":"1.5","ids":[3,"x"],"flags":[false,true,"maybe"]}', + $response->getRawPost(), + ); + } + + public function testBlankTypedFieldsAreNotSent(): void + { + $request = new ConsoleRequest(new ConsoleWireHandler()); + $response = $request->makeRequest('http://127.0.0.1:23523/', 'POST', [ + 'count' => '', 'ratio' => ' ', 'on' => '', 'meta' => '', 'tags' => '', + 'ids___0' => '1', 'ids___1' => '', 'ids___2' => '2', 'ids___3' => '', 'ids___4' => '', + 'flags___0' => '', 'X-Tag' => '', + ]); + + // an optional text field is left to the server default as well + $this->assertSame(['ids' => [1, 2]], json_decode((string) $response->getRawPost(), true)); + $this->assertSame(['Content-Type: application/json'], $response->getHeaders()); + } + + public function testARequiredTextFieldKeepsItsEmptyStringSoThatItsConstraintsCanBeTried(): void + { + $request = new ConsoleRequest(new ConsoleTextHandler()); + $response = $request->makeRequest('http://127.0.0.1:23523/', 'POST', ['name' => '', 'ci' => '', 'X-Need' => '', 'X-Other' => ' ']); + + // ci has a default and a pattern, so the server decides; a blank header is never sent + $this->assertSame('{"name":""}', $response->getRawPost()); + $this->assertSame(['Content-Type: application/json'], $response->getHeaders()); + } + + public function testBlankSlotsOfAListOfObjectsAreNotSent(): void + { + $request = new ConsoleRequest(new CreateOrderHandler()); + $response = $request->makeRequest('http://127.0.0.1:23523/', 'POST', [ + 'items___0' => '{"sku":"a","quantity":1}', 'items___1' => '', 'items___2' => '', + ]); + + $this->assertStringContainsString('"items":[{"sku":"a","quantity":1}]', (string) $response->getRawPost()); + } + + public function testANonStringBodyValueIsSentAsItIs(): void + { + $request = new ConsoleRequest(new ConsoleWireHandler()); + $response = $request->makeRequest('http://127.0.0.1:23523/', 'POST', ['count' => ['5']]); + + $this->assertSame('{"count":["5"]}', $response->getRawPost()); + } + + public function testNestedBodyIsFlattenedNextToAnUpload(): void + { + $file = new FileUpload(['name' => 'a.png', 'type' => 'image/png', 'size' => 3, 'tmp_name' => __FILE__, 'error' => UPLOAD_ERR_OK]); + $request = new ConsoleRequest(new ConsoleWireHandler()); + $response = $request->makeRequest('http://127.0.0.1:23523/', 'POST', [ + 'doc' => $file, 'meta' => '{"t":true,"a":{"b":1},"f":false,"n":null}', 'on' => 'nope', + ]); + + $fields = $response->getPostFields(); + unset($fields['doc']); + $this->assertSame(['meta[t]' => '1', 'meta[a][b]' => 1, 'meta[f]' => '0', 'on' => 'nope'], $fields); + $this->assertNull($response->getRawPost()); + } + + public function testEndpointWithoutALinkGeneratorKeepsTheQueryAndExtraHeaders(): void + { + $endpoint = new EndpointIdentifier('GET', 1, 'users', '{id}/detail'); + $request = new ConsoleRequest(new UserDetailHandler(), $endpoint); + $response = $request->makeRequest('http://127.0.0.1:23523/api/v1/users/{id}/detail', 'GET', ['id' => '7', 'limit' => '5'], ['headers' => ['X-Extra: 1']]); + + $this->assertSame('http://127.0.0.1:23523/api/v1/users/7/detail?limit=5', $response->getUrl()); + $this->assertSame(['X-Extra: 1'], $response->getHeaders()); + } + + public function testAFormOnlyHandlerReceivesAFormBody(): void + { + $request = new ConsoleRequest(new ConsoleFormHandler()); + $response = $request->makeRequest('http://127.0.0.1:23523/', 'POST', ['count' => '3', 'on' => 'true', 'meta' => '{"t":true,"a":{"b":4}}']); + + $this->assertSame(['Content-Type: application/x-www-form-urlencoded'], $response->getHeaders()); + parse_str((string) $response->getRawPost(), $sent); + $this->assertSame(['count' => '3', 'on' => '1', 'meta' => ['t' => '1', 'a' => ['b' => '4']]], $sent); + $this->assertSame([], $response->getPostFields()); + } + + public function testAMultipartOnlyHandlerReceivesMultipartFieldsWithoutAFile(): void + { + $request = new ConsoleRequest(new ConsoleMultipartHandler()); + $response = $request->makeRequest('http://127.0.0.1:23523/', 'POST', ['count' => '3']); + + $this->assertSame(['count' => 3], $response->getPostFields()); + $this->assertNull($response->getRawPost()); + $this->assertSame([], $response->getHeaders()); + } + + public function testJsonStaysTheChoiceWhenItIsListedFirst(): void + { + $request = new ConsoleRequest(new ConsoleWireHandler()); + $response = $request->makeRequest('http://127.0.0.1:23523/', 'POST', ['count' => '3']); + + $this->assertSame(['Content-Type: application/json'], $response->getHeaders()); + $this->assertSame('{"count":3}', $response->getRawPost()); + } + + public function testNumbersThatJsonCannotHoldStayText(): void + { + $request = new ConsoleRequest(new ConsoleWireHandler()); + $response = $request->makeRequest('http://127.0.0.1:23523/', 'POST', ['count' => '99999999999999999999', 'ratio' => '1e999', 'tags' => "bad \xB1 byte"]); + + $this->assertSame('{"count":"99999999999999999999","ratio":"1e999","tags":"bad ' . "\u{FFFD}" . ' byte"}', $response->getRawPost()); + } + + public function testAnEmptyJsonObjectStaysAnObject(): void + { + $request = new ConsoleRequest(new ConsoleWireHandler()); + $response = $request->makeRequest('http://127.0.0.1:23523/', 'POST', ['meta' => '{}']); + + $this->assertSame('{"meta":{}}', $response->getRawPost()); + $list = $request->makeRequest('http://127.0.0.1:23523/', 'POST', ['ids___0' => '[1]', 'meta' => '[]']); + $this->assertSame('{"ids":["[1]"],"meta":[]}', $list->getRawPost()); + } + + private static function localLink(): ApiLink + { + return new ApiLink(self::localLinkGenerator()); + } + + private static function localLinkGenerator(): LinkGenerator + { + $router = new RouteList(); + $router->addRoute('api/v/[/]', 'Api:Api:default'); + return new LinkGenerator($router, new UrlScript('http://127.0.0.1:23523/')); + } } diff --git a/tests/OpenApi/ParameterBuilderTest.php b/tests/OpenApi/ParameterBuilderTest.php index 55996371f..9e87efb95 100644 --- a/tests/OpenApi/ParameterBuilderTest.php +++ b/tests/OpenApi/ParameterBuilderTest.php @@ -47,6 +47,16 @@ public function testMultiRequiredParamWithExample(): void ]], $parameters); } + public function testAMultiParamWithAnExplicitNonArraySchemaKeepsItsPlainName(): void + { + $parameters = new ParameterBuilder()->build(new ConfigurableHandler([ + new GetInputParam('csv')->setMulti()->setOpenApiSchema(['type' => 'string']), + new GetInputParam('ids')->setMulti()->setOpenApiSchema(['type' => 'array', 'items' => ['type' => 'integer']]), + ])); + + $this->assertSame(['csv', 'ids[]'], array_column($parameters, 'name')); + } + public function testAvailableValuesWithDescriptions(): void { $parameters = new ParameterBuilder()->build(new ConfigurableHandler([ diff --git a/tests/OpenApi/TypedInputOpenApiTest.php b/tests/OpenApi/TypedInputOpenApiTest.php new file mode 100644 index 000000000..6b14e28a4 --- /dev/null +++ b/tests/OpenApi/TypedInputOpenApiTest.php @@ -0,0 +1,99 @@ +operation(new UserDetailHandler()); + $manual = $this->operation(new ConfigurableHandler([ + new PathInputParam('id')->setOpenApiSchema(['type' => 'integer', 'minimum' => 1]), + new GetInputParam('limit')->setOpenApiSchema(['type' => 'integer', 'minimum' => 1, 'maximum' => 100, 'default' => 20]), + new GetInputParam('status')->setOpenApiSchema(['type' => 'string', 'enum' => ['active', 'disabled']]), + new HeaderInputParam('X-Request-Id')->setOpenApiSchema(['type' => 'string']), + ])); + + $this->assertSame($manual['parameters'], $dto['parameters']); + $this->assertMatchesSnapshot('typed-user-detail.json', $dto['parameters']); + } + + public function testNestedBodyListsJsonAndForm(): void + { + $dto = $this->operation(new CreateOrderHandler()); + $schema = $dto['requestBody']['content']['application/json']['schema']; + $manual = $this->operation(new ConfigurableHandler([ + new BodyInputParam('customerEmail')->setRequired()->setOpenApiSchema($schema['properties']['customerEmail'])->setContentTypes(['application/json', 'application/x-www-form-urlencoded']), + new BodyInputParam('address')->setRequired()->setOpenApiSchema($schema['properties']['address'])->setContentTypes(['application/json', 'application/x-www-form-urlencoded']), + new BodyInputParam('items')->setRequired()->setOpenApiSchema($schema['properties']['items'])->setContentTypes(['application/json', 'application/x-www-form-urlencoded']), + new BodyInputParam('deliveryAt')->setOpenApiSchema($schema['properties']['deliveryAt'])->setContentTypes(['application/json', 'application/x-www-form-urlencoded']), + ])); + + $this->assertSame($manual['requestBody'], $dto['requestBody']); + $this->assertSame(['customerEmail', 'address', 'items'], $schema['required']); + $this->assertSame('email', $schema['properties']['customerEmail']['format']); + $this->assertSame(1, $schema['properties']['items']['minItems']); + $this->assertArrayHasKey('application/x-www-form-urlencoded', $dto['requestBody']['content']); + $this->assertMatchesSnapshot('typed-create-order.json', $dto['requestBody']); + } + + public function testDirectPathAndHeaderParamsUseThoseLocations(): void + { + $parameters = new ParameterBuilder()->build(new ConfigurableHandler([ + new PathInputParam('id'), + new HeaderInputParam('X-Request-Id')->setDescription('Request id'), + new GetInputParam('page'), + ])); + + $this->assertSame('path', $parameters[0]['in']); + $this->assertTrue($parameters[0]['required']); + $this->assertSame(['type' => 'string'], $parameters[0]['schema']); + $this->assertSame('header', $parameters[1]['in']); + $this->assertSame('Request id', $parameters[1]['description']); + $this->assertSame('query', $parameters[2]['in']); + } + + /** + * @return array + */ + private function operation(BaseHandler $handler): array + { + return new PathBuilder()->buildOperation( + new Api(new EndpointIdentifier('GET', 1, 'sample'), $handler, new NoAuthorization()), + new SchemaRegistry(), + ); + } + + /** + * @param array $value + */ + private function assertMatchesSnapshot(string $name, array $value): void + { + $actual = json_encode($value, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "\n"; + $file = __DIR__ . '/snapshots/' . $name; + if (getenv('UPDATE_SNAPSHOTS')) { + file_put_contents($file, $actual); + self::markTestIncomplete('Snapshot ' . $name . ' was written'); + } + $this->assertFileExists($file); + $this->assertSame(file_get_contents($file), $actual); + } +} diff --git a/tests/OpenApi/snapshots/typed-create-order.json b/tests/OpenApi/snapshots/typed-create-order.json new file mode 100644 index 000000000..75e3b9b17 --- /dev/null +++ b/tests/OpenApi/snapshots/typed-create-order.json @@ -0,0 +1,125 @@ +{ + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "customerEmail": { + "type": "string", + "format": "email" + }, + "address": { + "type": "object", + "properties": { + "street": { + "type": "string", + "minLength": 1, + "maxLength": 120 + }, + "postalCode": { + "type": "string", + "pattern": "^[0-9]{5}$" + } + }, + "required": [ + "street", + "postalCode" + ] + }, + "items": { + "type": "array", + "items": { + "type": "object", + "properties": { + "sku": { + "type": "string" + }, + "quantity": { + "type": "integer", + "minimum": 1 + } + }, + "required": [ + "sku", + "quantity" + ] + }, + "minItems": 1, + "maxItems": 50 + }, + "deliveryAt": { + "type": "string", + "format": "date-time", + "nullable": true + } + }, + "required": [ + "customerEmail", + "address", + "items" + ] + } + }, + "application/x-www-form-urlencoded": { + "schema": { + "type": "object", + "properties": { + "customerEmail": { + "type": "string", + "format": "email" + }, + "address": { + "type": "object", + "properties": { + "street": { + "type": "string", + "minLength": 1, + "maxLength": 120 + }, + "postalCode": { + "type": "string", + "pattern": "^[0-9]{5}$" + } + }, + "required": [ + "street", + "postalCode" + ] + }, + "items": { + "type": "array", + "items": { + "type": "object", + "properties": { + "sku": { + "type": "string" + }, + "quantity": { + "type": "integer", + "minimum": 1 + } + }, + "required": [ + "sku", + "quantity" + ] + }, + "minItems": 1, + "maxItems": 50 + }, + "deliveryAt": { + "type": "string", + "format": "date-time", + "nullable": true + } + }, + "required": [ + "customerEmail", + "address", + "items" + ] + } + } + } +} diff --git a/tests/OpenApi/snapshots/typed-user-detail.json b/tests/OpenApi/snapshots/typed-user-detail.json new file mode 100644 index 000000000..07204feb0 --- /dev/null +++ b/tests/OpenApi/snapshots/typed-user-detail.json @@ -0,0 +1,42 @@ +[ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 100, + "default": 20 + } + }, + { + "name": "status", + "in": "query", + "required": false, + "schema": { + "type": "string", + "enum": [ + "active", + "disabled" + ] + } + }, + { + "name": "X-Request-Id", + "in": "header", + "required": false, + "schema": { + "type": "string" + } + } +] diff --git a/tests/Params/ParamTypeTest.php b/tests/Params/ParamTypeTest.php index 3fbeb721f..12886539d 100644 --- a/tests/Params/ParamTypeTest.php +++ b/tests/Params/ParamTypeTest.php @@ -12,8 +12,11 @@ use Tomaj\NetteApi\Params\InputParam; use Tomaj\NetteApi\Params\JsonInputParam; use Tomaj\NetteApi\Params\ParamType; +use Tomaj\NetteApi\Params\HeaderInputParam; +use Tomaj\NetteApi\Params\PathInputParam; use Tomaj\NetteApi\Params\PostInputParam; use Tomaj\NetteApi\Params\PutInputParam; +use Tomaj\NetteApi\Params\BodyInputParam; use Tomaj\NetteApi\Params\RawInputParam; use Tomaj\NetteApi\Validation\InputType; use Tomaj\NetteApi\Validation\InputValidator; @@ -29,13 +32,18 @@ public function testParamTypes(): void $this->assertSame(ParamType::Cookie, new CookieInputParam('a')->getParamType()); $this->assertSame(ParamType::PostRaw, new RawInputParam('a')->getParamType()); $this->assertSame(ParamType::PostJson, new JsonInputParam('a', '{}')->getParamType()); + $this->assertSame(ParamType::Path, new PathInputParam('a')->getParamType()); + $this->assertSame(ParamType::Header, new HeaderInputParam('a')->getParamType()); + $this->assertSame(ParamType::Body, new BodyInputParam('a')->getParamType()); $this->assertSame(InputParam::TYPE_POST_JSON, ParamType::PostJson->value); + $this->assertSame(InputParam::TYPE_PATH, ParamType::Path->value); + $this->assertSame(InputParam::TYPE_HEADER, ParamType::Header->value); } public function testCustomTypeGivesNull(): void { $param = new class ('a') extends InputParam { - protected $type = 'HEADER'; + protected $type = 'CUSTOM'; public function getValue(): mixed { diff --git a/tests/Params/PathHeaderBodyParamTest.php b/tests/Params/PathHeaderBodyParamTest.php new file mode 100644 index 000000000..722b22046 --- /dev/null +++ b/tests/Params/PathHeaderBodyParamTest.php @@ -0,0 +1,85 @@ +assertTrue($param->isRequired()); + $this->assertSame(['Field is required'], $param->validate()->getErrors()); + + PathValues::set(['id' => '12']); + $this->assertTrue($param->validate()->isOk()); + $this->assertSame(12, $param->getValue()); + } + + public function testHeaderIsCaseInsensitive(): void + { + $_SERVER['HTTP_X_REQUEST_ID'] = 'req-7'; + $param = new HeaderInputParam('x-request-id', InputType::STRING); + $this->assertFalse($param->isRequired()); + $this->assertSame('req-7', $param->getValue()); + $this->assertTrue($param->validate()->isOk()); + + unset($_SERVER['HTTP_X_REQUEST_ID']); + $withDefault = new HeaderInputParam('X-Missing')->setDefault('fallback'); + $this->assertSame('fallback', $withDefault->getValue()); + } + + public function testBodyReadsPostAndJson(): void + { + $_POST = ['name' => 'Ada']; + $param = new BodyInputParam('name', InputType::STRING); + $this->assertSame('Ada', $param->getValue()); + + $_POST = []; + $_SERVER['CONTENT_TYPE'] = 'application/json'; + RequestInput::setRawBody('{"name":"Grace","extra":1}'); + $this->assertSame('Grace', $param->getValue()); + + RequestInput::reset(); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + RequestInput::setRawBody('[1,2]'); + $empty = new BodyInputParam('name')->setDefault('none'); + $this->assertSame('none', $empty->getValue()); + + RequestInput::reset(); + $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; + $_POST = []; + RequestInput::setRawBody('{"name":"from-json"}'); + $this->assertSame('none', new BodyInputParam('name')->setDefault('none')->getValue()); + } + + public function testSchemaAndContentTypesRoundTrip(): void + { + $param = new BodyInputParam('name') + ->setOpenApiSchema(['type' => 'string']) + ->setContentTypes(['application/json', 'application/x-www-form-urlencoded']); + $this->assertSame(['type' => 'string'], $param->getOpenApiSchema()); + $this->assertSame(['application/json', 'application/x-www-form-urlencoded'], $param->getContentTypes()); + $this->assertNull(new BodyInputParam('other')->getOpenApiSchema()); + $this->assertSame([], new BodyInputParam('other')->getContentTypes()); + } +} diff --git a/tests/Presenters/ApiPresenterIpDetectorTest.php b/tests/Presenters/ApiPresenterIpDetectorTest.php index eb830eb75..a707933bb 100644 --- a/tests/Presenters/ApiPresenterIpDetectorTest.php +++ b/tests/Presenters/ApiPresenterIpDetectorTest.php @@ -209,7 +209,8 @@ public function testAFailingIpDetectorDoesNotFailALimiterWithoutTheIp(): void #[\Override] public function getByType(string $type, bool $throw = true): ?object { - throw new \LogicException('more IP detectors'); + // the http request service is optional, only the IP detector lookup fails + return $type === IpDetectorInterface::class ? throw new \LogicException('more IP detectors') : null; } }; $this->assertSame([200, 429], [$this->code($presenter), $this->code($presenter)]); @@ -241,7 +242,7 @@ public function log(int $responseCode, string $requestMethod, string $requestHea return true; } } - : throw $this->error; + : ($type === IpDetectorInterface::class ? throw $this->error : null); } }; $handler = $this->createMock(ErrorHandlerInterface::class); diff --git a/tests/Presenters/ApiPresenterRateLimitTest.php b/tests/Presenters/ApiPresenterRateLimitTest.php index 373146753..f826a2ced 100644 --- a/tests/Presenters/ApiPresenterRateLimitTest.php +++ b/tests/Presenters/ApiPresenterRateLimitTest.php @@ -257,6 +257,11 @@ public function handleRateLimit(RateLimitResponse $rateLimit): ResponseInterface $this->rateLimit = $rateLimit; return $this->inner->handleRateLimit($rateLimit); } + + public function handleUnsupportedMediaType(string $detail): ResponseInterface + { + return $this->inner->handleUnsupportedMediaType($detail); + } }; $presenter->errorHandler = $handler; [$result, $headers] = $this->call($presenter); diff --git a/tests/Presenters/ApiPresenterUnsupportedMediaTypeTest.php b/tests/Presenters/ApiPresenterUnsupportedMediaTypeTest.php new file mode 100644 index 000000000..1ba42cb01 --- /dev/null +++ b/tests/Presenters/ApiPresenterUnsupportedMediaTypeTest.php @@ -0,0 +1,174 @@ + */ + private array $server; + + /** @var list */ + public array $logged = []; + + protected function setUp(): void + { + $this->server = $_SERVER; + unset($_SERVER['HTTP_AUTHORIZATION']); + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_SERVER['CONTENT_TYPE'] = 'text/csv'; + $_POST = []; + $_FILES = []; + RequestInput::reset(); + PathValues::reset(); + } + + protected function tearDown(): void + { + $_SERVER = $this->server; + RequestInput::reset(); + } + + public function testUnsupportedMediaTypeIsAnsweredWith415AndLogged(): void + { + $presenter = $this->presenter(new NoAuthorization()); + $response = $presenter->run($this->request()); + $this->assertInstanceOf(JsonApiResponse::class, $response); + $this->assertSame(415, $response->getCode()); + $this->assertSame(415, $presenter->response->getCode()); + $this->assertSame([415], $this->logged); + $this->assertSame("Content-Type 'text/csv' is not supported for this endpoint. Use one of: application/json, application/x-www-form-urlencoded.", $response->getPayload()['detail']); + } + + public function testAuthorizationIsCheckedBeforeTheMediaType(): void + { + $presenter = $this->presenter(new BearerTokenAuthorization(new StaticTokenRepository(['secret' => '*']), new StaticIpDetector('127.0.0.1'))); + $response = $presenter->run($this->request()); + $this->assertSame(401, $response->getCode()); + $this->assertSame([], $this->logged); + + $_SERVER['HTTP_AUTHORIZATION'] = 'Bearer secret'; + RequestInput::reset(); + $this->assertSame(415, $presenter->run($this->request())->getCode()); + $this->assertSame([415], $this->logged); + } + + public function testRequestPathFailureOtherThanAMissingServiceIsNotHidden(): void + { + $presenter = $this->presenter(new NoAuthorization(), new \RuntimeException('broken http request')); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('broken http request'); + // the request path is read only for an endpoint the static lookup did not find + $presenter->run(new Request('Api:Api:default', 'POST', ['version' => '1', 'package' => 'unknown'])); + } + + public function testWithoutAnHttpRequestServiceAnUnknownEndpointIsNotFound(): void + { + $presenter = $this->presenter(new NoAuthorization()); + $response = $presenter->run(new Request('Api:Api:default', 'POST', ['version' => '1', 'package' => 'unknown'])); + $this->assertSame(404, $response->getCode()); + } + + public function testAStaticEndpointDoesNotReadTheRequestPath(): void + { + $presenter = $this->presenter(new NoAuthorization(), new \RuntimeException('broken http request')); + $this->assertSame(415, $presenter->run($this->request())->getCode()); + } + + public function testARequestStartsWithoutPathValuesEvenWhenGetApiIsOverridden(): void + { + $presenter = $this->presenter(new NoAuthorization()); + $presenter->apiDecider = new class (new Container()) extends ApiDecider { + public function getApi(string $method, string $version, string $package, ?string $apiAction = null): Api + { + return new Api(new EndpointIdentifier('POST', 1, 'orders'), new CreateOrderHandler(), new NoAuthorization()); + } + }; + PathValues::set(['id' => 'left over from the previous request']); + + $presenter->run($this->request()); + + $this->assertFalse(PathValues::has('id')); + } + + private function request(): Request + { + return new Request('Api:Api:default', 'POST', ['version' => '1', 'package' => 'orders']); + } + + private function presenter(ApiAuthorizationInterface $authorization, ?\Throwable $httpRequestFailure = null): ApiPresenter + { + $logger = new readonly class ($this) implements ApiLoggerInterface { + public function __construct(private ApiPresenterUnsupportedMediaTypeTest $test) + { + } + + public function log(int $responseCode, string $requestMethod, string $requestHeader, string $requestUri, string $requestIp, string $requestAgent, int $responseTime): bool + { + $this->test->logged[] = $responseCode; + return true; + } + }; + + $container = new class ($logger, $httpRequestFailure) extends Container { + public function __construct(private readonly ApiLoggerInterface $logger, private readonly ?\Throwable $httpRequestFailure) + { + parent::__construct(); + } + + public function findByType(string $type): array + { + return $type === ApiLoggerInterface::class ? ['logger'] : []; + } + + public function getByType(string $type, bool $throw = true): ?object + { + if ($type === IRequest::class) { + if ($this->httpRequestFailure !== null) { + throw $this->httpRequestFailure; + } + + return $throw ? throw new MissingServiceException('no http request') : null; + } + + return $type === ApiLoggerInterface::class ? $this->logger : new StaticIpDetector('127.0.0.1'); + } + }; + + $apiDecider = new ApiDecider(new Container()); + $apiDecider->addApi(new EndpointIdentifier('POST', 1, 'orders'), new CreateOrderHandler(), $authorization); + + $presenter = new ApiPresenter(); + $presenter->apiDecider = $apiDecider; + $presenter->response = new HttpResponse(); + $presenter->context = $container; + $presenter->outputConfigurator = new DebuggerConfigurator(); + $presenter->errorHandler = new DefaultErrorHandler($presenter->outputConfigurator); + + return $presenter; + } +} diff --git a/tests/TypedEndpointMatchTest.php b/tests/TypedEndpointMatchTest.php new file mode 100644 index 000000000..ff387e8a2 --- /dev/null +++ b/tests/TypedEndpointMatchTest.php @@ -0,0 +1,123 @@ +addApi(new EndpointIdentifier('GET', 1, 'users', 'list'), new AlwaysOkHandler(), new NoAuthorization()); + $decider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), new UserDetailHandler(), new NoAuthorization()); + + $exact = self::resolve($decider, 'GET', '1', 'users', 'list', '/api/v1/users/list'); + $this->assertInstanceOf(AlwaysOkHandler::class, $exact->getHandler()); + + $matched = self::resolve($decider, 'GET', '1', 'users', '42', '/api/v1/users/42/detail'); + $this->assertInstanceOf(UserDetailHandler::class, $matched->getHandler()); + $this->assertSame('v1/users/{id}/detail', $matched->getHandler()->getEndpoint()?->getUrl()); + + $missing = self::resolve($decider, 'GET', '1', 'users', '42', '/api/v1/users/42'); + $this->assertInstanceOf(DefaultHandler::class, $missing->getHandler()); + } + + public function testGetApiKeepsItsFourArgumentContract(): void + { + $decider = new ApiDecider(new Container()); + $decider->addApi(new EndpointIdentifier('GET', 1, 'users', 'list'), new AlwaysOkHandler(), new NoAuthorization()); + $decider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), new UserDetailHandler(), new NoAuthorization()); + + $this->assertInstanceOf(AlwaysOkHandler::class, $decider->getApi('GET', '1', 'users', 'list')->getHandler()); + $this->assertInstanceOf(DefaultHandler::class, $decider->getApi('GET', '1', 'users', '42')->getHandler()); + $this->assertNull($decider->matchPath('GET', '1', 'users', '42', null)); + $this->assertNull($decider->matchPath('GET', '1', 'users', '42', '/api/v1/users/42')); + } + + public function testASubclassCanKeepOverridingTheFourArgumentGetApi(): void + { + $decider = new class (new Container()) extends ApiDecider { + public function getApi(string $method, string $version, string $package, ?string $apiAction = null): Api + { + return new Api(new EndpointIdentifier($method, (int) $version, $package, $apiAction), new AlwaysOkHandler(), new NoAuthorization()); + } + }; + + $this->assertInstanceOf(AlwaysOkHandler::class, $decider->getApi('GET', '1', 'users', 'x')->getHandler()); + } + + public function testOverlappingTemplatesAreReported(): void + { + $decider = new ApiDecider(new Container()); + $decider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id}'), new UserDetailHandler(), new NoAuthorization()); + $decider->addApi(new EndpointIdentifier('GET', 1, 'users', '{slug}'), new UserDetailHandler(), new NoAuthorization()); + + $this->expectException(\LogicException::class); + self::resolve($decider, 'GET', '1', 'users', '42', '/api/v1/users/42'); + } + + public function testOptionsOnATemplateUsesThePreflightHandler(): void + { + $decider = new ApiDecider(new Container()); + $decider->enableGlobalPreflight(); + $decider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), new UserDetailHandler(), new NoAuthorization()); + + $api = self::resolve($decider, 'OPTIONS', '1', 'users', '42', '/api/v1/users/42/detail'); + $this->assertInstanceOf(CorsPreflightHandler::class, $api->getHandler()); + } + + public function testMatchPathNormalisesTheMethodAndAnEmptyAction(): void + { + $decider = new ApiDecider(new Container()); + $decider->enableGlobalPreflight(); + $decider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), new UserDetailHandler(), new NoAuthorization()); + + $preflight = $decider->matchPath('options', '1', 'users', '', '/api/v1/users/42/detail'); + $this->assertInstanceOf(CorsPreflightHandler::class, $preflight?->getHandler()); + $this->assertSame('OPTIONS', $preflight->getEndpoint()->getMethod()); + $this->assertNull($preflight->getEndpoint()->getApiAction()); + + $named = $decider->matchPath('OPTIONS', '1', 'users', '42', '/api/v1/users/42/detail'); + $this->assertSame('42', $named?->getEndpoint()->getApiAction()); + + $matched = $decider->matchPath('get', '1', 'users', '42', '/api/v1/users/42/detail'); + $this->assertInstanceOf(UserDetailHandler::class, $matched?->getHandler()); + } + + public function testLinkKeepsPathPlaceholders(): void + { + $link = ApiFixtures::apiLink()->link(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), ['limit' => 10]); + $this->assertStringContainsString('/api/v1/users/{id}/detail', $link); + $this->assertStringContainsString('limit=10', $link); + } + + public function testStaticLinkIsUnchanged(): void + { + $link = ApiFixtures::apiLink()->link(new EndpointIdentifier('GET', 1, 'users', 'list')); + $this->assertSame('https://example.com/api/v1/users/list', $link); + $withQuery = ApiFixtures::apiLink()->link(new EndpointIdentifier('GET', 1, 'users', 'list'), ['q' => '1']); + $this->assertSame('https://example.com/api/v1/users/list?q=1', $withQuery); + $placeholder = ApiFixtures::apiLink()->link(new EndpointIdentifier('GET', 1, 'users', '{id}')); + $this->assertStringContainsString('/api/v1/users/{id}', $placeholder); + } + + private static function resolve(ApiDecider $decider, string $method, string $version, string $package, string $apiAction, string $path): Api + { + $api = $decider->getApi($method, $version, $package, $apiAction); + + return $api->getHandler() instanceof DefaultHandler ? ($decider->matchPath($method, $version, $package, $apiAction, $path) ?? $api) : $api; + } +} From 4f681060b9f5bb512407288f66dcedf062d8e62c Mon Sep 17 00:00:00 2001 From: Tomas Majer Date: Sun, 15 Nov 2026 10:16:23 +0100 Subject: [PATCH 2/5] Review cleanup for typed input DTOs 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 docblocks in the declaring class of an inherited constructor or caster - list 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 Claude-Session: https://claude.ai/code/session_012jrra6bHr2Jmk7hfEjoKsr --- CHANGELOG.md | 19 +- UPGRADE-4.0.md | 18 +- composer.json | 3 +- docs/examples/typed-input.md | 12 + docs/guide/console.md | 2 +- docs/guide/getting-started.md | 3 +- docs/guide/input-styles.md | 30 +- docs/guide/links.md | 10 +- docs/guide/params.md | 2 +- docs/guide/typed-input-body.md | 65 +- docs/guide/typed-input-conversion.md | 20 +- docs/guide/typed-input.md | 90 +- docs/index.md | 2 +- docs/sk/examples/typed-input.md | 12 + docs/sk/guide/console.md | 2 +- docs/sk/guide/getting-started.md | 3 +- docs/sk/guide/input-styles.md | 30 +- docs/sk/guide/layers.md | 2 +- docs/sk/guide/links.md | 10 +- docs/sk/guide/params.md | 2 +- docs/sk/guide/problem-details.md | 2 +- docs/sk/guide/typed-input-body.md | 65 +- docs/sk/guide/typed-input-conversion.md | 20 +- docs/sk/guide/typed-input.md | 90 +- docs/sk/index.md | 2 +- examples/typed-input/e2e.sh | 5 +- src/ApiDecider.php | 13 + src/DI/NetteApiExtension.php | 16 +- src/Input/Body.php | 8 +- src/Input/DtoCompiler.php | 241 ++-- src/Input/DtoMapper.php | 54 +- src/Input/DtoMetadata.php | 79 +- src/Input/DtoMetadataRegistry.php | 48 +- src/Input/EndpointTemplate.php | 40 +- src/Input/Field.php | 269 ----- src/Input/File.php | 8 +- src/Input/Header.php | 8 +- src/Input/Path.php | 8 +- src/Input/Query.php | 8 +- src/Input/RequestInput.php | 52 +- src/Input/ScalarCoercer.php | 3 +- src/Input/SchemaBuilder.php | 2 + src/Input/SourceAttribute.php | 20 + src/Input/ValueExport.php | 58 - src/Link/ApiLink.php | 14 +- src/OpenApi/RequestBodyBuilder.php | 245 +++- src/Params/BodyInputParam.php | 38 +- src/Params/MappedInputParam.php | 6 +- src/Validation/Pattern.php | 9 + src/Validation/Range.php | 6 + tests/ApiDeciderTest.php | 26 + tests/DI/TypedInputExtensionTest.php | 215 ++++ tests/Input/BehaviorPinTest.php | 827 ------------- tests/Input/BodyParsingTest.php | 294 +++++ tests/Input/CasterTest.php | 261 +++++ tests/Input/ConstraintTest.php | 71 ++ ...lerBranchTest.php => DtoAttributeTest.php} | 382 +----- tests/Input/DtoCompilerTest.php | 307 +++++ tests/Input/DtoConstructorTest.php | 341 ++++++ tests/Input/DtoHandlerTest.php | 360 ++++++ tests/Input/DtoMetadataTest.php | 114 ++ tests/Input/DtoPhpDocTest.php | 172 +++ tests/Input/DtoPropertyTypeTest.php | 806 +++++++++++++ tests/Input/EndpointTemplateTest.php | 49 + tests/Input/ErrorBudgetTest.php | 372 ++++++ tests/Input/EscapeTest.php | 106 -- tests/Input/FileUploadTest.php | 33 +- .../Fixtures/Inherited/Base/LevelsCaster.php | 23 + .../Fixtures/Inherited/Base/LevelsInput.php | 26 + .../Fixtures/Inherited/LeafLevelsCaster.php | 11 + .../Fixtures/Inherited/LeafLevelsHandler.php | 17 + .../Fixtures/Inherited/LeafLevelsInput.php | 14 + tests/Input/Fixtures/Shared.php | 197 ++++ tests/Input/Fixtures/create-order-export.json | 123 +- tests/Input/RequestInputTest.php | 73 ++ tests/Input/ReviewContractTest.php | 790 ------------- tests/Input/Round10Test.php | 319 ----- tests/Input/Round11Test.php | 1042 ----------------- tests/Input/Round12Test.php | 656 ----------- tests/Input/ScalarCoercerTest.php | 66 ++ tests/Input/TypeNameTest.php | 30 +- tests/Input/Utf8Test.php | 265 +++++ tests/Link/ApiLinkTest.php | 39 + .../OpenApi/Fixtures/TypedProfileHandler.php | 20 + tests/OpenApi/Fixtures/TypedProfileInput.php | 43 + tests/OpenApi/ParameterBuilderTest.php | 58 + tests/OpenApi/RequestBodyBuilderTest.php | 124 ++ tests/OpenApi/ResponseBuilderTest.php | 40 + tests/OpenApi/TypedInputOpenApiTest.php | 233 +++- .../OpenApi/snapshots/typed-create-order.json | 60 - tests/OpenApi/snapshots/typed-profile.json | 141 +++ tests/Params/PathHeaderBodyParamTest.php | 59 +- .../ApiPresenterUnsupportedMediaTypeTest.php | 17 + tests/TypedEndpointMatchTest.php | 37 + .../PatternTest.php} | 327 ++---- 95 files changed, 5873 insertions(+), 5487 deletions(-) create mode 100644 src/Input/SourceAttribute.php delete mode 100644 src/Input/ValueExport.php delete mode 100644 tests/Input/BehaviorPinTest.php create mode 100644 tests/Input/BodyParsingTest.php rename tests/Input/{CompilerBranchTest.php => DtoAttributeTest.php} (59%) create mode 100644 tests/Input/DtoConstructorTest.php create mode 100644 tests/Input/DtoMetadataTest.php create mode 100644 tests/Input/DtoPhpDocTest.php create mode 100644 tests/Input/DtoPropertyTypeTest.php create mode 100644 tests/Input/ErrorBudgetTest.php create mode 100644 tests/Input/Fixtures/Inherited/Base/LevelsCaster.php create mode 100644 tests/Input/Fixtures/Inherited/Base/LevelsInput.php create mode 100644 tests/Input/Fixtures/Inherited/LeafLevelsCaster.php create mode 100644 tests/Input/Fixtures/Inherited/LeafLevelsHandler.php create mode 100644 tests/Input/Fixtures/Inherited/LeafLevelsInput.php create mode 100644 tests/Input/Fixtures/Shared.php create mode 100644 tests/Input/RequestInputTest.php delete mode 100644 tests/Input/ReviewContractTest.php delete mode 100644 tests/Input/Round10Test.php delete mode 100644 tests/Input/Round11Test.php delete mode 100644 tests/Input/Round12Test.php create mode 100644 tests/Input/Utf8Test.php create mode 100644 tests/Link/ApiLinkTest.php create mode 100644 tests/OpenApi/Fixtures/TypedProfileHandler.php create mode 100644 tests/OpenApi/Fixtures/TypedProfileInput.php create mode 100644 tests/OpenApi/snapshots/typed-profile.json rename tests/{Input/Round13Test.php => Validation/PatternTest.php} (53%) diff --git a/CHANGELOG.md b/CHANGELOG.md index e1697ba3a..8ce7e93e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -60,22 +60,17 @@ Planned for 4.0, developed on `master`. 3.x is maintained on the `3.x` branch. * Rate limiting (#195): `FixedWindowLimiter`, `SlidingWindowLimiter` and `TokenBucketLimiter` behind `RateLimit\RateLimiterInterface`, combined by `RateLimiterChain`; keys by IP, identity, endpoint or a combination (`Key\RateLimitKeyInterface`); storages in memory, in the Nette cache (atomic on one server through a file lock in `%tempDir%`, waiting at most 3 seconds) or in Redis with one atomic Lua script that keeps the whole state of a counter in one hash with one expiration (`Storage\RedisStorage` with ext-redis or Predis, keys `prefix{policy:key}` for Redis Cluster); own algorithms (`Algorithm\RateLimitAlgorithmInterface`, with `RedisScriptAlgorithmInterface` for Redis) and own storages (`Storage\RateLimitStorageInterface`, `KeyValueStorage`). `ApiPresenter` checks the limits before the authorization and, for identity keys, after it. A failing storage lets the request pass and logs a warning. Time comes from a `Psr\Clock\ClockInterface`. Intervals are from 1 second to 366 days. `IpKey` hashes values longer than an IP and other keys longer than 200 characters are hashed, the memory storage drops expired counters as it grows, and all algorithms keep the newest window or time of servers with skewed clocks. When the logger fails, the warning goes to `error_log`. Limits are at most 1 000 000 000, policy and `rateLimits` names are ASCII, the parts of a list key are escaped, and the presenter escapes policy names of own limiters in the headers. A list of policies stops at the first rejection, so rejected requests do not use up a shared quota. The `ip` key counts an IPv6 client per `/64`. `api: rateLimiting: logger` sets the logger of the warnings. `Authorization\AuthorizationIdentityInterface` gives a limit keyed by `identity` the caller; the token authorizations and `BasicAuthentication` implement it. An authorization that returns no identity after a successful `authorized()` is logged once per process and policy. `ApiDecider::addApi()` without the 4th argument throws a `LogicException` naming the services when the container has more autowired `RateLimitInterface` services, instead of using none. A failing API logger after the handler only goes to the Tracy log, the response of the handler is sent. * DI extension: named policies in `api: rateLimits` (`{algorithm, limit, interval, key, name}`), `api: rateLimiting` (`storage`, `redis`, `prefix`, `clock`), lists of policies and inline limits on endpoints and in `api: defaults`, `rateLimit: false`; inline limits always keep counters per endpoint (also with `name`), two named policies with the same `name` and an inline `name` equal to a named policy fail the compilation; `#[RateLimit]` takes a list or `limit`, `interval`, `algorithm`, `key` and `name` (#195). * `examples/rate-limit` uses the built-in policies; `examples/auth`, `examples/di-extension` and `examples/attributes` no longer ship an own `FileRateLimit` (#195). -* Typed input DTOs (#197, #240): `Handlers\TypedHandler` reads `handleDto(SomeInput $input)` and turns a readonly DTO into `InputParam` objects at container compile time (or once per process without the extension). It is an equal second way to declare input next to `params()` with `handle(array $params)`, which is unchanged. - * Sources: `#[Query]`, `#[Path]`, `#[Header]`, `#[Body]` and `#[File]`; nullable or defaulted properties are optional. `PathInputParam`, `HeaderInputParam` and `BodyInputParam` are also usable from `params()`. - * Endpoint actions can have `{name}` segments, for example `#[Get(1, 'users', '{id}/detail')]`. `ApiDecider::getApi()` keeps its four arguments; the new `ApiDecider::matchPath()` finds the endpoint of a URL template, and `ApiPresenter` calls it when `getApi()` finds no static endpoint. - * Strict conversion of int, float, bool, backed enums, `DateTimeImmutable` (RFC 3339) and `list`. `#[Cast]` with `CasterInterface` replaces the conversion of one property; `DateFormat`, `UnixTimestamp` and `Split` are built in. The constraints are `Range`, `Length`, `Pattern` (complete match, `$` matches only at the very end) and `Email`, and `ConstraintInterface` adds your own. - * Nested objects and lists are validated for JSON, form and multipart and reported as `items[1].quantity` in the existing error envelope and in Problem Details. A request reports at most 100 errors in total, however deeply lists are nested; when something was left unchecked, the key `body` says so. - * `#[Consumes]` limits body media types; any other one, including a body that arrives without a content type, is `415` and OpenAPI lists it. A DTO with a required file advertises only `multipart/form-data`; a JSON request to it gets a `400` that says files need `multipart/form-data`. `#[File]` is read only on the input DTO of the handler. - * OpenAPI: `in: path` and `in: header` parameters, `nullable` only on body properties, query lists as `name[]`, file properties only under `multipart/form-data`. - * The API console sends path values into the URL (`ApiLink::link()` keeps its signature and still decides the URL), header values as headers and body values as JSON, a URL-encoded form or multipart, as the handler's content types ask. Blank typed fields, blank optional text fields and blank list slots are not sent, and a blank path value is explained instead of called. - * JSON bodies must be UTF-8 (`utf-8`, `utf8` and `us-ascii` are accepted); a request that names another charset is a `400`. A multipart body sent with `PUT` or `PATCH`, and a URL-encoded form with more fields than `max_input_vars`, get a `400` that says why. `BearerTokenAuthorization` also reads `REDIRECT_HTTP_AUTHORIZATION`. `ApiPresenter::run()` also resets the path values. - * A `string` from a query, form, header or path value must be valid UTF-8 (a `400` `Value must be valid UTF-8` otherwise); `params()` handlers are unchanged. OpenAPI gets `pattern` only for a `#[Pattern]` that means the same in ECMA 262, and the PCRE pattern as `x-pattern` otherwise. - * The DI cache is rebuilt when a DTO, its parent class, a trait it uses, a caster, a constraint or an enum changes. - * Documentation: [typed input](https://tomaj.github.io/nette-api/guide/typed-input), body and conversion pages, [params() and DTO side by side](https://tomaj.github.io/nette-api/guide/input-styles) and `examples/typed-input`; `examples/attributes` and `examples/di-extension` have a typed endpoint next to the `params()` ones. +* Typed input DTOs (#197, #240): `Handlers\TypedHandler` with `handleDto(SomeInput $input)` reads a readonly DTO whose properties carry `#[Query]`, `#[Path]`, `#[Header]`, `#[Body]` or `#[File]`. It is an equal second way to declare input next to `params()`, which is unchanged, and the same declaration drives validation, OpenAPI and the API console. `PathInputParam`, `HeaderInputParam` and `BodyInputParam` are usable from `params()` too. See [typed input](https://tomaj.github.io/nette-api/guide/typed-input) and `examples/typed-input`. + * Endpoint actions can have `{name}` segments, for example `#[Get(1, 'users', '{id}/detail')]`. `ApiDecider::getApi()` keeps its signature; the new `ApiDecider::matchPath()` finds the endpoint of a URL template. `ApiLink::link()` fills `{name}` from the parameter of the same name. + * Strict conversion of scalars, backed enums, `DateTimeImmutable` (RFC 3339) and `list`; `#[Cast]` with `CasterInterface` (`DateFormat`, `UnixTimestamp` and `Split` built in); constraints `Range`, `Length`, `Pattern`, `Email` and own `ConstraintInterface`. + * Nested DTOs and lists for JSON, form and multipart bodies, with errors reported as `items[1].quantity` in the existing envelope and in Problem Details. + * `#[Consumes]` limits the body media types; any other one is a `415` through the new `ErrorHandlerInterface::handleUnsupportedMediaType()`, which own error handlers must add. + * For typed handlers, strings must be valid UTF-8, a JSON body that names another charset is a `400`, and so are a multipart body sent with `PUT` or `PATCH` and a form with more fields than `max_input_vars`. ### Changed * Dev tools: PHPUnit ^12 || ^13, PHPStan ^2.1 (level max, no baseline), Rector ^2.2, PHP_CodeSniffer ^4.0, Infection; `symfony/yaml` ^7.4.12 || ^8.0.12. * `vendor/bin/phpunit` no longer requires `XDEBUG_MODE=coverage`; coverage reports are opt-in via `composer coverage`. +* `BearerTokenAuthorization` also reads the token from `REDIRECT_HTTP_AUTHORIZATION`, which Apache with CGI or FastCGI sets after a rewrite (#240). ### Deprecated * `RateLimit\RateLimitInterface` and its `check()`: it still works through `LegacyRateLimitAdapter` with an `E_USER_DEPRECATED` notice and is removed in 5.0. Implement `RateLimiterInterface` or use a built-in limiter (#195). diff --git a/UPGRADE-4.0.md b/UPGRADE-4.0.md index 4ddf4822c..f441e9454 100644 --- a/UPGRADE-4.0.md +++ b/UPGRADE-4.0.md @@ -74,19 +74,15 @@ new BearerTokenAuthorization(new StaticBearerTokenRepository(['token' => '*']), new BearerTokenAuthorization(new StaticTokenRepository(['token' => '*']), $ipDetector); ``` -## Error handlers answer 415 +## Typed input: new param classes, enum cases and InputParam methods -`ErrorHandlerInterface` has `handleUnsupportedMediaType(string $detail): ResponseInterface`. A typed handler sends 415 when the body content type is missing or not one of the types it accepts. `DefaultErrorHandler` uses the message `unsupported media type` and adds the detail only when error details are on. `ProblemDetailsErrorHandler` uses status 415, title `Unsupported Media Type` and type `unsupported-media-type`. An own error handler has to implement the method. `params()` handlers are not affected. +`TypedHandler` is an additional way to declare input; handlers on `params()` keep their conversion, validation and OpenAPI output. What can affect existing code: -## Typed input does not change params() +* New param classes `PathInputParam`, `HeaderInputParam` and `BodyInputParam`; existing parameter classes are unchanged. +* `ParamType` has new cases `Path`, `Header` and `Body`. An exhaustive `match` on `ParamType` without a `default` arm throws `UnhandledMatchError` for them. +* `InputParam` has new public methods `setOpenApiSchema()`, `getOpenApiSchema()`, `setContentTypes()` and `getContentTypes()`. A subclass with a method of the same name must match their signatures. -`TypedHandler` is an additional way to declare input. Handlers that stay on `BaseHandler::params()` and `handle(array $params)` keep their conversion, validation and OpenAPI output. `PathInputParam` and `HeaderInputParam` are new classes; existing parameter classes are unchanged. A path segment is written in the endpoint action or package, for example `#[Get(1, 'users', '{id}/detail')]`. The usual route `/api/v/[/][/]` already delivers `users/42/detail`. - -## ApiDecider::getApi() and ApiLink::link() keep their signatures - -`ApiDecider::getApi(string $method, string $version, string $package, ?string $apiAction = null)` is unchanged, so a subclass that overrides it needs no change. Endpoints with `{name}` segments are found by the new `ApiDecider::matchPath()`, which `ApiPresenter` calls when `getApi()` returns no static endpoint. An own presenter that should serve URL templates calls `matchPath()` the same way. - -`ApiLink::link(EndpointInterface $endpoint, $params = [])` is unchanged too. A link for an endpoint with `{name}` segments keeps them literal (the OpenAPI path template). The API console puts typed path values into those segments after `link()` returned the URL, so a subclass that overrides `link()` (for example to add a prefix) still decides the URL of every endpoint. `BearerTokenAuthorization` also reads `REDIRECT_HTTP_AUTHORIZATION`, which Apache with CGI or FastCGI sets after a rewrite. +`ApiDecider::getApi()` and `ApiLink::link()` keep their signatures; endpoints with `{name}` segments are found by the new `ApiDecider::matchPath()`, which `ApiPresenter` calls when `getApi()` returns no static endpoint. An own presenter that should serve URL templates calls `matchPath()` the same way. ## Stricter types @@ -139,7 +135,7 @@ Overriding methods are marked with `#[\Override]`. ## Error handlers -`ErrorHandlerInterface` methods return `ResponseInterface` instead of `JsonApiResponse`, and the interface has three new methods compared with 3.x: `handleNotFound()` and `handleRateLimit()` (#196), and `handleUnsupportedMediaType(string $detail)` for the `415` of typed handlers (#197, see "Error handlers answer 415" above). An own implementation must add them; a wrapper can delegate to `DefaultErrorHandler`: +`ErrorHandlerInterface` methods return `ResponseInterface` instead of `JsonApiResponse`, and the interface has three new methods compared with 3.x: `handleNotFound()` and `handleRateLimit()` (#196), and `handleUnsupportedMediaType(string $detail)` for the `415` that a typed handler sends when the body content type is missing or not accepted (#197; `params()` handlers are not affected). An own implementation must add them; a wrapper can delegate to `DefaultErrorHandler`: ```php use Tomaj\NetteApi\EndpointInterface; diff --git a/composer.json b/composer.json index d3ff22309..f68722b0b 100644 --- a/composer.json +++ b/composer.json @@ -57,7 +57,8 @@ "Tomaj\\NetteApi\\Test\\": "tests" }, "classmap": [ - "tests/Input/Fixtures/Handlers.php" + "tests/Input/Fixtures/Handlers.php", + "tests/Input/Fixtures/Shared.php" ] }, "scripts": { diff --git a/docs/examples/typed-input.md b/docs/examples/typed-input.md index a39b9f414..af6cc0c81 100644 --- a/docs/examples/typed-input.md +++ b/docs/examples/typed-input.md @@ -39,6 +39,18 @@ Typed handlers, path and header parameters and `#[Consumes]` are new in 4.0.0. <<< @/../examples/typed-input/app/Api/UserDetailHandler.php +## A nested body DTO + +`CreateOrderInput` nests an `AddressInput` and a `list`; the same classes read a JSON body and a URL-encoded form with bracket names. + +<<< @/../examples/typed-input/app/Api/Input/CreateOrderInput.php + +<<< @/../examples/typed-input/app/Api/Input/AddressInput.php + +<<< @/../examples/typed-input/app/Api/Input/ItemInput.php + +<<< @/../examples/typed-input/app/Api/CreateOrderHandler.php + ## A file upload <<< @/../examples/typed-input/app/Api/Input/AvatarInput.php diff --git a/docs/guide/console.md b/docs/guide/console.md index d97d7d2f5..ff1032fb4 100644 --- a/docs/guide/console.md +++ b/docs/guide/console.md @@ -42,7 +42,7 @@ The console builds the request from the params of the handler, whether they come | body field | the first media type the handler reads that the console can build: JSON, a URL-encoded form or multipart | | file | a multipart upload; with a file attached the body fields go in the same multipart request | -In a JSON body each value keeps its declared type, and a nested object field takes JSON text, for example `{}` for an empty object. A list field has one input per item, and an item that is an object takes JSON text. A typed field that is left blank is not sent (an empty string would never be a valid number, date, choice, object or list item), so an unused list slot is skipped. A blank optional text field is not sent either, so the server uses its default; a required text field is sent as an empty string, so that its length and pattern constraints can be tried. An empty header is never sent. A blank path value is not sent at all: the console shows `The path value 'id' is empty. Fill it in and send the request again.` instead of calling a URL with an empty segment. A number that JSON cannot hold, such as `1e999` or an integer beyond the 64-bit range, is sent as text, so the server answers with its normal `400`. +In a JSON body each value keeps its declared type; a nested object, or an object item of a list, takes JSON text. Blank optional fields are not sent; a blank path value shows an error instead of sending. ## FAQ diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.md index b60845f63..310068030 100644 --- a/docs/guide/getting-started.md +++ b/docs/guide/getting-started.md @@ -158,7 +158,7 @@ use Tomaj\NetteApi\Input\Query; use Tomaj\NetteApi\Response\JsonApiResponse; use Tomaj\NetteApi\Response\ResponseInterface; -// app/Api/HelloInput.php +// both classes in one file for brevity; with PSR-4 autoloading move HelloInput to app/Api/HelloInput.php final readonly class HelloInput { public function __construct( @@ -168,7 +168,6 @@ final readonly class HelloInput } } -// app/Api/HelloHandler.php final class HelloHandler extends TypedHandler { public function summary(): string diff --git a/docs/guide/input-styles.md b/docs/guide/input-styles.md index 70c442408..1eb579f84 100644 --- a/docs/guide/input-styles.md +++ b/docs/guide/input-styles.md @@ -1,15 +1,15 @@ --- title: params() and DTO side by side -description: 'The same endpoints declared with params() and with a typed DTO in Nette API: seven pairs that show how to rewrite a handler from one style to the other.' +description: 'The same endpoints declared with params() and with a typed DTO in Nette API: six pairs that show how to rewrite a handler from one style to the other.' --- # params() and DTO side by side -`params()` with `handle(array $params)` and `TypedHandler` with a DTO are two equal ways to write handlers in one application. Neither disables the other. Registration, authorization, outputs, rate limits, OpenAPI and the console are shared. [Typed input (DTO)](/guide/typed-input) compares the two styles, and [Input params](/guide/params) documents the first. +`params()` and a `TypedHandler` DTO are two equal ways to declare input and can be mixed in one application; [Typed input (DTO)](/guide/typed-input) compares them. ## Rewriting between styles -The following pairs show the same request contract in both styles, so you can rewrite a handler from either style to the other when it suits that endpoint. Framework imports are omitted where they are unchanged; application constructor dependencies and response creation remain in the handler. You can rewrite one endpoint, leave every other handler unchanged and rewrite the next one when it is convenient. There is no application-wide switch. +Each pair shows the same request contract in both styles; framework imports are omitted, and you can rewrite one endpoint at a time. ### 1. Simple GET: optional/defaulted query params and an enum @@ -282,7 +282,7 @@ final class LoginHandler extends BaseHandler } ``` -With a DTO, `Body` means a body field regardless of whether the request is JSON or form-encoded. The `max` bound is the only length rule here, because a minimum would start rejecting existing short passwords at login: +With a DTO, `Body` means a body field regardless of whether the request is JSON or form-encoded: ```php final readonly class LoginInput @@ -433,28 +433,6 @@ final class ScheduleHandler extends TypedHandler `ConstraintContext::value()` reads sibling values in the same DTO, so cross-property constraints do not have to inspect the HTTP request. Business rules that need a database still belong in application services; a constraint should remain a deterministic request-contract check. -### 7. Both styles in one application - -An endpoint may depend on the looser `InputType::INTEGER` conversion of `params()`, on a custom `InputParam`, or on manual parsing of an unusual content type. `params()` is the right style for it: - -```php -final class ReportHandler extends BaseHandler -{ - public function params(): array - { - return [new GetInputParam('offset', InputType::INTEGER)]; - } - - public function handle(array $params): ResponseInterface - { - // This endpoint intentionally uses the looser params() conversion. - return $this->reports->generate($params['offset']); - } -} -``` - -Its neighboring `ListReportsHandler` can extend `TypedHandler`. Mixing the styles is supported without any limit; the choice is about ergonomics for each endpoint. - ### Checklist for rewriting a handler to a DTO 1. **Capture the current contract:** save endpoint tests and the current OpenAPI operation, including defaults and error behavior. diff --git a/docs/guide/links.md b/docs/guide/links.md index 438f47ce9..ee57227d6 100644 --- a/docs/guide/links.md +++ b/docs/guide/links.md @@ -15,17 +15,15 @@ $url = $apiLink->link(new EndpointIdentifier('GET', 1, 'users', 'detail'), ['id' It needs a route to `Api:Api:default` with `version`, `package` and `apiAction` parameters, as in [Getting started](/guide/getting-started). -For an endpoint whose URL has `{name}` segments, such as `{id}/detail`, `link()` keeps the segments literal, which is the OpenAPI path template. Replace a segment with the URL-encoded value yourself: +For an endpoint whose URL has `{name}` segments, such as `{id}/detail`, `link()` fills each segment from the parameter of the same name (URL-encoded); the other parameters go to the query string. A segment without a value stays literal, which is the OpenAPI path template: ```php -$url = $apiLink->link(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), ['limit' => 5]); -// https://example.com/api/v1/users/{id}/detail?limit=5 -$url = str_replace('{id}', rawurlencode('42'), $url); +$url = $apiLink->link(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), ['id' => 42, 'limit' => 5]); // https://example.com/api/v1/users/42/detail?limit=5 +$url = $apiLink->link(new EndpointIdentifier('GET', 1, 'users', '{id}/detail')); +// https://example.com/api/v1/users/{id}/detail ``` -The API console does the same with the values typed into the path inputs, after `link()` has built the URL, so a subclass that overrides `link()` still decides the URL of every endpoint. - Inside a handler extending `BaseHandler` or `TypedHandler`, call `$this->createLink($params)` for a link to the handler's own endpoint. It needs Nette's `LinkGenerator` first, otherwise it throws `Nette\InvalidStateException`. Add a `setup` line to the handler service: ```yaml diff --git a/docs/guide/params.md b/docs/guide/params.md index 14ebbbab0..63a3f3ab3 100644 --- a/docs/guide/params.md +++ b/docs/guide/params.md @@ -63,7 +63,7 @@ In 3.x `?limit=abc` with `INTEGER` is not an error: the value is converted to `n ## Path, header and body params -`PathInputParam` reads a value from the endpoint URL. Declare the placeholder in the endpoint action with `{name}`, for example `users/{id}/detail`, as described in [Typed input](/guide/typed-input#path-values-and-url-templates). The param is always required and its OpenAPI placeholder has the same name. `HeaderInputParam` reads a request header, case-insensitively. `BodyInputParam` reads one field of a JSON object, a URL-encoded form or a multipart body, and `setContentTypes()` lists the media types it accepts. A typed DTO generates the same three classes from `#[Path]`, `#[Header]` and `#[Body]`, and `params()` can declare them directly: +`PathInputParam` reads a value from the endpoint URL. Declare the placeholder in the endpoint action with `{name}`, for example `users/{id}/detail`, as described in [Typed input](/guide/typed-input#path-values-and-url-templates). The param is always required and its OpenAPI placeholder has the same name. `HeaderInputParam` reads a request header, case-insensitively. `BodyInputParam` reads one field of a JSON object, a URL-encoded form or a multipart body, and `setContentTypes()` lists the media types it accepts. In a typed DTO, `#[Path]`, `#[Header]` and `#[Body]` properties become `MappedInputParam` objects with the type `TYPE_PATH`, `TYPE_HEADER` or `TYPE_BODY`; `params()` declares these classes directly: ```php public function params(): array diff --git a/docs/guide/typed-input-body.md b/docs/guide/typed-input-body.md index c0b56df0d..deca5bdb9 100644 --- a/docs/guide/typed-input-body.md +++ b/docs/guide/typed-input-body.md @@ -73,15 +73,65 @@ JSON request body: } ``` -The DTO mapper creates `AddressInput` and both `ItemInput` objects recursively. `list` is required PHPDoc for an array of DTOs; `list`, `list`, `list` and `list` are supported for scalar arrays. The usual spellings are read: `list`, `non-empty-list`, `T[]`, with `|null` or a leading `?` (nullability comes from the PHP type), and `@phpstan-param` or `@psalm-param` instead of `@param`. A description after the type is fine (`@var list Names of the things`). An item is one non-nullable type, so `list` and `list` are compile-time errors; use an item DTO. Associative arrays, unions other than nullable types, `mixed`, `object` and untyped arrays are rejected when the container is compiled, not halfway through a request. A list default is checked item by item at the same time, so `@param list` with the default `['x']` does not compile. +The DTO mapper creates `AddressInput` and both `ItemInput` objects recursively. An array of DTOs needs PHPDoc such as `list`, and a scalar array `list`, `list`, `list` or `list` (`non-empty-list`, `T[]`, `@phpstan-param` and `@psalm-param` work too); associative arrays, unions, `mixed`, `object` and untyped arrays fail when the container is compiled. The same DTO works with URL-encoded form fields, and with multipart fields when it has a `#[File]` property or `#[Consumes('multipart/form-data')]`. Nested fields use PHP bracket notation, such as `address[street]` and `items[0][sku]`; `deliveryAt` keeps the same RFC 3339 string. Body parsing depends on the content type, not on a JSON schema. -## Body content types +OpenAPI documents this body as (responses omitted): + +```openapi +requestBody: + required: true + content: + application/json: + schema: + type: object + required: [customerEmail, address, items] + properties: + customerEmail: {type: string, format: email} + address: + type: object + required: [street, postalCode] + properties: + street: {type: string, minLength: 1, maxLength: 120} + postalCode: {type: string, pattern: '^[0-9]{5}$'} + items: + type: array + minItems: 1 + maxItems: 50 + items: + type: object + required: [sku, quantity] + properties: + sku: {type: string} + quantity: {type: integer, minimum: 1} + deliveryAt: {type: string, format: date-time, nullable: true} +``` + +The endpoint accepts a form too, but OpenAPI 3.0 cannot describe a list of objects in a form body, so only JSON is listed here. A DTO whose body has only scalars, lists of scalars and objects of scalars lists both media types; the form schema names a list `tags[]` and sends an object as `deepObject`: + +```openapi +requestBody: + content: + application/json: + schema: + type: object + properties: + tags: {type: array, items: {type: string}} + address: {type: object, properties: {street: {type: string}}} + application/x-www-form-urlencoded: + schema: + type: object + properties: + 'tags[]': {type: array, items: {type: string}} + address: {type: object, properties: {street: {type: string}}} + encoding: + address: {style: deepObject, explode: true} +``` -A `TypedHandler` with body fields accepts both **`application/json`** and **`application/x-www-form-urlencoded`** by default. If its DTO contains a `#[File]` property, the defaults are **`application/json`** and **`multipart/form-data`**: multipart replaces URL-encoded form, because URL-encoded form cannot carry files, and files are uploaded together with the body fields. The content type is matched without parameters, so `application/json; charset=utf-8` is accepted. JSON is always read as UTF-8: another `charset`, such as `application/json; charset=ISO-8859-1`, is a `400` instead of being decoded wrongly (`utf-8`, its common spelling `utf8` and `us-ascii` are accepted). A body that arrives without any `Content-Type` is a `415` even when every field is optional, because it would otherwise be dropped silently. +## Body content types -OpenAPI advertises the same choices in `requestBody.content`: JSON and URL-encoded form, or JSON and multipart when a file is present. When a file is required, only multipart is advertised, because a JSON request could only be answered with `400`. File properties appear only in the `multipart/form-data` schema, because JSON cannot carry a file. A JSON request to a DTO with a required file gets `400` with the file field as the path and the message `File is required and can only be uploaded as multipart/form-data, but the request is application/json`. Body fields are `TYPE_BODY` params and files are `TYPE_FILE` params; there is still only one validation and mapping path. +A `TypedHandler` with body fields accepts **`application/json`** and **`application/x-www-form-urlencoded`** by default, or **`application/json`** and **`multipart/form-data`** when its DTO contains a `#[File]` property; OpenAPI lists the same types in `requestBody.content` (only multipart when a file is required). The content type is matched without parameters. JSON must be UTF-8: a request that names another `charset` is a `400`. A body without a `Content-Type`, or with a type the handler does not accept, is a `415`. File properties appear only in the `multipart/form-data` schema, and a JSON request to a DTO with a required file gets a `400` that says files need `multipart/form-data`. ### Restrict accepted types with Consumes @@ -118,7 +168,7 @@ A request with another content type is rejected before mapping with **415 Unsupp } ``` -An absent body content type on a request that requires a body receives the same actionable 415 rather than a later null-property error. With Problem Details enabled, status 415 and the same message are used in that format, and its `detail` always names the accepted types. The default envelope hides `detail` when error details are disabled, as it does for field errors. +With Problem Details enabled, the 415 uses that format, and its `detail` always names the accepted types. ### JSON, form and multipart differences @@ -136,13 +186,12 @@ For example, JSON `"quantity": 2` stays an integer, while form `quantity=2` beco For an optional form value, omit `deliveryAt` instead of sending `deliveryAt=null` or an empty value. A multipart file cannot be replaced with a JSON base64 string; an application needing base64 uploads can keep `BaseHandler` and parse its own raw body. -PHP reads multipart bodies only for `POST`. A `multipart/form-data` body sent with `PUT` or `PATCH` is not parsed by PHP, so the endpoint answers `400` with `multipart/form-data is only parsed by PHP for POST requests, but this one is PUT. Send it with POST, or use application/json`. Send uploads and multipart forms with `POST`. A URL-encoded form with more fields than PHP's `max_input_vars` (1000 by default) is a `400` `Too many form fields`, for `POST` as well as for `PUT` and `PATCH`. PHP cuts a multipart `POST` that has more fields before the application sees it, and that cannot be told from a complete one: raise `max_input_vars` or send JSON for such forms. +Send multipart with `POST`. Forms over `max_input_vars` are rejected with `400`. ## Forms and cookie-authenticated endpoints A URL-encoded form is a "simple" cross-site request: a page on any website can submit it to your API together with the visitor's cookies and without a CORS preflight, which a JSON body cannot do. A DTO with body fields accepts a form by default, so an endpoint authenticated only by a session cookie, or by the address of the client, can be reached by such a cross-site form. Restrict it to JSON with `#[Consumes('application/json')]` and keep `SameSite` on the cookie. Endpoints authenticated by a bearer token or an API key header are not affected, because a browser form cannot set those headers. - ## File upload ```php @@ -160,5 +209,5 @@ final readonly class AvatarInput } ``` -`FileUpload` is the library's typed upload value object. It exposes the original name, client content type, temporary path, size and upload error; it does not trust the client content type or move the file automatically. `?FileUpload` means an optional upload and `list` accepts several files in one field. Check the upload error, size and real type before storing it, exactly as with `FileInputParam`. Upload errors such as `UPLOAD_ERR_INI_SIZE` are not turned into validation errors; the `FileUpload` carries them in `error`. Only a missing file is: no entry, or `UPLOAD_ERR_NO_FILE` with an empty name, and for `list` every slot being `UPLOAD_ERR_NO_FILE`. Upload requests must use `POST`, see above. `#[File]` belongs on the input DTO of the handler; a `#[File]` inside a nested DTO or a list of DTOs is a compile-time error, because PHP keeps nested uploads in a separate `$_FILES` tree and body fields must never be read as upload metadata. +`FileUpload` exposes the original name, the client content type, the temporary path, the size and the upload error. `?FileUpload` is an optional upload and `list` accepts several files in one field. The handler checks the upload error, the size and the real type before storing the file; nothing is moved automatically. `#[File]` is allowed only on the root input DTO of the handler, not inside a nested DTO or a list. diff --git a/docs/guide/typed-input-conversion.md b/docs/guide/typed-input-conversion.md index e186c0e77..9ac35d9b3 100644 --- a/docs/guide/typed-input-conversion.md +++ b/docs/guide/typed-input-conversion.md @@ -21,11 +21,11 @@ Typed input never relies on PHP's loose scalar casts. | `DateTimeImmutable` | an RFC 3339 string with date, time and explicit offset, for example `2026-11-06T14:30:00+01:00` (`T` and `Z` may be lowercase; a leap second such as `23:59:60` is rejected, because PHP cannot represent it) | | `array` | a list whose items each satisfy the PHPDoc item type | -A string must be valid UTF-8, so that it can be put into a JSON response: `?q=%E9` (a Latin-1 byte) is a `400` `Value must be valid UTF-8` on the field, not a value whose `Length` or `Pattern` gives a misleading message. A JSON body is decoded as UTF-8 anyway. This is the typed input only; a handler with `params()` keeps accepting any bytes, as before, because changing it would reject requests that work today. +The UTF-8 check applies to typed input only; a `params()` handler keeps accepting any bytes. -`?page=1a` for an integer is a `400`, never `1` or `null`. Whitespace is not trimmed implicitly and unknown strings do not become `false`. JSON numbers and booleans retain their types, so a whole number written as a float, `1.0` or `1e2`, is not an integer: a client that serialises whole numbers as floats must send `1` for an integer property. Application normalization belongs in the handler or in a custom constraint, not in surprising global casts. +`?page=1a` for an integer is a `400`, never `1` or `null`. Whitespace is not trimmed and unknown strings do not become `false`. JSON numbers and booleans keep their types, so `1.0` or `1e2` is not an integer. -A query list uses the PHP bracket form `ids[]=3&ids[]=4`, and OpenAPI names the parameter `ids[]` so generated clients send that form. A comma-separated value uses `Split` instead. Form bodies support PHP bracket names; other nested form encodings are not decoded. A query can carry only scalars, enums and lists of them: a nested DTO or a `list` behind `#[Query]` is a compile-time error, because OpenAPI cannot describe PHP bracket nesting for a generated client. Read nested objects from the body with `#[Body]`. +A query list uses the PHP bracket form `ids[]=3&ids[]=4` (OpenAPI names the parameter `ids[]`); a comma-separated value uses `Split`. A query carries only scalars, enums and lists of them; read nested objects from the body with `#[Body]`. DTO mapping supports only the five sources above; an input from another source uses `params()` with a custom `InputParam`. @@ -37,10 +37,10 @@ Constraint attributes are in `Tomaj\NetteApi\Validation` and can be combined on | --- | --- | --- | | `#[Range(min: 1, max: 100)]` | `int`, `float` | inclusive numeric bounds; either bound may be omitted | | `#[Length(min: 1, max: 80)]` | `string`, `array` | Unicode character count or list item count; either bound may be omitted; a list over `max` is rejected before its items are mapped | -| `#[Pattern('/^[A-Z]+$/')]` | `string` | complete PCRE match, `$` matches only at the very end because the `D` modifier is added (`/^[0-9]{5}$/` rejects `81101` followed by a newline); an invalid pattern is a compile-time error; the pattern is PCRE, not JavaScript, and it is always checked with PCRE; OpenAPI `pattern` is ECMA 262, so it gets `pattern` only when the expression means the same there, and the whole PCRE pattern (delimiters and flags included) otherwise as the extension `x-pattern`; that plain subset is ASCII literals, escaped punctuation, `\n`, `\r`, `\t`, classes of literals and ranges (also with `\-`), groups, lookahead, alternation, anchors and quantifiers, with no flag other than `u` and `D`, and `\d`, `\w` and `\b` only without `u`, because PCRE reads them as Unicode with `u` and JavaScript does not; everything else goes to `x-pattern`, among it the dot, negated classes, `\s`, `\D`, `\W`, `\p{L}`, `\x`, back references, named groups, lookbehind, non-ASCII characters, possessive quantifiers, atomic groups, inline flags and flags such as `i` | +| `#[Pattern('/^[A-Z]+$/')]` | `string` | complete PCRE match (`D` modifier added); an invalid pattern fails compilation. OpenAPI gets `pattern` when the regex is portable to JavaScript, otherwise `x-pattern` | | `#[Email]` | `string` | valid email address | -Validation collects all field errors rather than stopping at the first one; a request reports at most the first 100 errors in total, nested lists included, and the rest of the body is not checked. Then comes the note `Only the first 100 errors are reported, the rest of the request was not checked` under the key `body`, only when something was actually left unchecked. Messages state the actual limits, for example `Value must have between 1 and 50 items` instead of a generic `Invalid value`. +Validation collects all field errors rather than stopping at the first one. One request reports at most 100 errors, nested lists included; when something was left unchecked, a note under the key `body` says so. Messages state the actual limits, for example `Value must have between 1 and 50 items` instead of a generic `Invalid value`. ### Custom constraints @@ -53,7 +53,7 @@ interface ConstraintInterface } ``` -Return `null` for success or one developer-facing message for failure. `ConstraintContext` exposes the property path, the DTO class and `value('sibling')` for other converted properties of the same DTO; defaults are checked at container compilation with all sibling defaults, and a sibling without a default is `null` there; constraints must not throw for ordinary invalid client input. Custom constraints have no OpenAPI representation unless the application extends the OpenAPI builders. +Return `null` for success or one message for failure. `ConstraintContext` exposes the property path, the DTO class and `value('sibling')` for other converted properties of the same DTO. Do not throw for invalid client input. Custom constraints have no OpenAPI representation unless the application extends the OpenAPI builders. ### Constraints on list items @@ -88,7 +88,7 @@ A caster reports invalid client input by throwing `Tomaj\NetteApi\Input\CastExce } ``` -Other exceptions are programmer/server errors and are not disguised as client validation errors. Container compilation verifies that the caster class exists, is instantiable, implements `CasterInterface`, accepts the declared attribute arguments and has a native `cast()` return type identical to the property type (or a documented covariant class subtype). A `list` caster must declare `array` with matching list-item PHPDoc. This check is limited to native declarations; `mixed` is not accepted as a caster return type. An incompatible caster fails during compilation, not on the first request. +Any other exception is a server error, not a validation error. Container compilation checks that the caster implements `CasterInterface`, accepts the attribute arguments and declares a native `cast()` return type matching the property type (`array` with list PHPDoc for `list`; `mixed` is not accepted). ### OpenAPI schema hints @@ -126,7 +126,7 @@ final readonly class IssueInput } ``` -The `DateFormat('d.m.Y')` schema hint is `{type: string, example: '24.12.2026'}`. Only `DateFormat('Y-m-d')` adds `format: date`, because OpenAPI `date` means the RFC 3339 full date. A NUL byte or any other unparsable value is a `400` at the field, not an exception. +The `DateFormat('d.m.Y')` schema hint is `{type: string, example: '24.12.2026'}`; only `DateFormat('Y-m-d')` adds `format: date`. ### CSV to list<string> @@ -143,7 +143,7 @@ final readonly class ReportInput } ``` -In OpenAPI the property is one string with the example `red,green,blue`, and the console shows one text input. `?columns=id,createdAt,total` becomes `['id', 'createdAt', 'total']`. `Split` returns an empty list for an omitted optional property only through the property's normal default; an explicitly present empty string produces `['']`, which a constraint can reject. +In OpenAPI the property is one string and the console shows one text input. `?columns=id,createdAt,total` becomes `['id', 'createdAt', 'total']`; an empty string gives `['']`, which a constraint can reject. ### Decimal string to a Money value object @@ -178,5 +178,5 @@ final readonly class PriceInput } ``` -`12,50` becomes `Money` and a subsequent custom `PositiveMoney` constraint receives that `Money` object. `12.50`, `1a` and an array produce a 400 at `price` with the caster's message. Currency-specific formatting remains in the application caster rather than becoming another global scalar rule. Because the caster replaces the built-in conversion, `Money` is never compiled as a transport DTO: it can have a private constructor and a static factory, and the compiler only checks that `cast()` declares a `Money` return type. Named caster arguments such as `#[Cast(MyCaster::class, suffix: 'x')]` keep their names in the compiled container. +`12,50` becomes `Money`, and constraints receive that object. `12.50`, `1a` and an array produce a 400 at `price` with the caster's message. Because the caster replaces the built-in conversion, `Money` can have a private constructor and a static factory. diff --git a/docs/guide/typed-input.md b/docs/guide/typed-input.md index 9d3d153b4..1a8ade19c 100644 --- a/docs/guide/typed-input.md +++ b/docs/guide/typed-input.md @@ -26,7 +26,7 @@ A handler declares its input in one of two equal ways. Both are fully supported, Pick `params()` when the endpoint relies on its looser conversion, on a custom `InputParam` or on manual parsing of an unusual body. Pick a DTO when you want typed values, nested bodies, cross-field constraints or the whole request contract in one class. Neither style is deprecated, and choosing one for an endpoint does not affect any other endpoint. [params() and DTO side by side](/guide/input-styles) shows the same endpoint written in both styles. -`TypedHandler` turns the DTO declaration into the same `InputParam` objects that `params()` returns. +`TypedHandler` turns the DTO declaration into `InputParam` objects, so validation, OpenAPI and the console work as with `params()`. With the DI extension this metadata is compiled into the container, and changing a DTO, a caster, a constraint or an enum rebuilds it. A constant of another class used in an attribute argument or a default is not tracked; clear the cache after changing it. Without the extension the metadata is built once per process. ## The smallest handler @@ -73,7 +73,7 @@ Constructor dependencies, `summary()`, `description()`, `outputs()`, tags and re ## Source attributes -Attributes are in `Tomaj\NetteApi\Input` and target promoted constructor properties. Each promoted property has exactly one source attribute. The external name defaults to the property name; pass a name to override it. `description` and repeatable `examples` become the description and examples of the generated `InputParam`. +Attributes are in `Tomaj\NetteApi\Input` and target promoted constructor properties. Each promoted property has exactly one source attribute. The external name defaults to the property name; pass a name to override it. `description` and `examples` (an array keyed by the example name, as in `InputParam::addExample()`) become the description and examples of the generated `InputParam`. | Attribute | Source | Generated parameter type | | --- | --- | --- | @@ -87,13 +87,13 @@ Every DTO property becomes one `MappedInputParam`, an `InputParam` that validate For example, `#[Header('X-Request-Id')] public ?string $requestId = null` reads `X-Request-Id`, not `requestId`. Header lookup is case-insensitive. A `#[Path]` name starts with a letter or an underscore and has letters, digits and underscores, because it is written as a `{name}` segment; a `#[Header]` name uses dashes, not underscores (`X-Request-Id`, not `X_Request_Id`), because PHP exposes header names with dashes. Anything else is a compile-time error with the corrected name. A path or header value is one string, so a native list or nested DTO there is a compile-time error; split it with a caster, for example `#[Header('X-Tags')] #[Cast(Split::class, ',')] public array $tags`. -`PathInputParam` and `HeaderInputParam` are also public for handlers that use `params()`, see [Input params](/guide/params#path-header-and-body-params). +`PathInputParam`, `HeaderInputParam` and `BodyInputParam` are also public for handlers that use `params()`, see [Input params](/guide/params#path-header-and-body-params). -Do not use `#[Header]` for a header that a proxy sets or strips to carry trust, such as `X-Forwarded-User`. PHP and web servers map `X_Request_Id` and `X-Request-Id` to the same name, so a client can send a look-alike. Authenticate such values in the proxy and drop the client's copy there. The `Authorization` header is also read from `REDIRECT_HTTP_AUTHORIZATION`, which Apache with CGI or FastCGI sets after a rewrite such as `RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]`. `BearerTokenAuthorization` reads it the same way, so a token that reaches `#[Header('Authorization')]` also reaches the authorization. Other headers are read from the `HTTP_*` server variables. +Do not use `#[Header]` for a header that a proxy sets or strips to carry trust, such as `X-Forwarded-User`. PHP and web servers map `X_Request_Id` and `X-Request-Id` to the same name, so a client can send a look-alike. Authenticate such values in the proxy and drop the client's copy there. ### Path values and URL templates -A path value is declared in the endpoint URL with `{name}`, for example `users/{id}/detail`. It is required, it cannot be nullable or have a default, and its OpenAPI path placeholder has the same name. A missing or undeclared path parameter is a container-compilation error. Static endpoint URLs work unchanged. A path value is one URL segment: the path is URL-decoded before it is matched, so an encoded slash (`%2F`) is read as a separator and the endpoint is not found. Send a value that can contain `/` in the query or in the body. +A path value is declared in the endpoint URL with `{name}`, for example `users/{id}/detail`. It is required, it cannot be nullable or have a default, and its OpenAPI path placeholder has the same name. A missing or undeclared path parameter is a container-compilation error. Static endpoint URLs work unchanged. A path value is one URL segment. Segments are URL-decoded after the path is split, so an encoded slash stays in the value: `/users/a%2Fb/detail` gives `id` `a/b`. Register the template as the action of the endpoint, in any of the usual ways: @@ -112,13 +112,13 @@ final class UserDetailHandler extends TypedHandler $apiDecider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), new UserDetailHandler(), new NoAuthorization()); ``` -The route has to let the extra segment through, as the one in the [typed input example](/examples/typed-input) does: `/api/v/[/][/]`. A request is looked up among the static endpoints first and then among the templates. If two templates match one URL, the request fails with a `LogicException` that names both, so make a static segment differ. +The route has to let the template segments through. The route of the [typed input example](/examples/typed-input), `/api/v/[/][/]`, lets one segment through after the action; a deeper template such as `{id}/orders/{orderId}` needs `[/]` in the route mask, otherwise Nette answers `404` before the API sees the request. A request is looked up among the static endpoints first and then among the templates. If two templates match one URL, the request fails with a `LogicException` that names both, so make a static segment differ. ### Required values and defaults A non-nullable property without a default is required. A nullable property or a property with a default is optional. A missing nullable value becomes `null`; a missing value with a default uses that default. This also sets `required` in OpenAPI. -Required path parameters cannot be nullable or have a default. An optional body field accepts an omitted field, while an explicit JSON `null` is accepted only for a nullable property. An empty string is not silently converted to `null`. A default is `null`, a scalar, an array or a backed enum case; an object default such as `= new Inner()` is a compile-time error, because defaults are stored in the compiled container. Use `= null` and create the object in the handler. +Required path parameters cannot be nullable or have a default. An optional body field accepts an omitted field, while an explicit JSON `null` is accepted only for a nullable property. An empty string is not silently converted to `null`. A default is `null`, a scalar, an array or a backed enum case; an object default such as `= new Inner()` is a compile-time error. Use `= null` and create the object in the handler. ## Complete request example @@ -155,7 +155,6 @@ X-Request-Id: req-01J8Y7N6R9 The handler receives `id: 42`, `limit: 10`, `status: UserStatus::Active` and the request ID string. No casts or array-key lookups are needed. - A request with a body, a nested DTO and a list is in [body, files and content types](/guide/typed-input-body#post-with-a-nested-dto-and-an-array). ## Error responses @@ -177,13 +176,13 @@ The response envelope stays the same as `ParamsProcessor`. The detail key is the When error details are disabled, only `status` and `message` are returned. With Problem Details enabled, the same field paths and messages appear in its input-error extension. Malformed JSON and an unreadable body keep the existing body-parser errors. -The key `body` also carries the failures of the request body as a whole, such as `Too many form fields`, a wrong JSON charset and the note that only the first 100 errors are reported. A DTO field that is itself called `body` shares that key, so its messages are listed together with those; give the property another external name, for example `#[Body('payload')]`, to keep them apart. +Request-level body errors appear under `body`; avoid naming a field `body` (use `#[Body('payload')]`). A missing nested object reports the nested object path. Unknown input fields are ignored, matching ordinary query/form parameter handling; they are not silently mapped to properties. ## OpenAPI and the API console -`TypedHandler::params()` exposes generated `InputParam` objects, so the existing console automatically gets labels, required markers, defaults, examples, enum choices and file inputs. The console sends each value to its source: path values are URL-encoded into `{name}` segments, header values become request headers, and body values are sent in the first media type the handler reads that the console can build: JSON with the declared types (a nested DTO field takes JSON text, a list field has one input per item and a DTO item takes JSON text), a URL-encoded form or multipart. A file always means multipart, with bracket names for nested fields. There is no DTO-specific console mode, see [Web console](/guide/console). +The [web console](/guide/console) builds its form from the generated `InputParam` objects and sends each value to its source; there is no DTO-specific mode. For OpenAPI, query, path and header properties become operation parameters. Body properties are combined into one object schema; nested DTOs and lists become nested schemas. By default `requestBody.content` lists both `application/json` and `application/x-www-form-urlencoded`, or JSON and `multipart/form-data` when the DTO contains a file. `#[Consumes]` limits the list and accepted requests to explicit media types. An operation with a body also documents a `415` response. `nullable: true` appears only on body properties: a query string, a path segment or a header cannot carry `null`, so an optional query or header value is simply absent. A nullable enum lists `null` in its `enum`, as OpenAPI 3.0.3 requires. @@ -209,82 +208,19 @@ parameters: schema: {type: string} ``` -The POST example contributes: - -```openapi -requestBody: - required: true - content: - application/json: - schema: - type: object - required: [customerEmail, address, items] - properties: - customerEmail: {type: string, format: email} - address: - type: object - required: [street, postalCode] - properties: - street: {type: string, minLength: 1, maxLength: 120} - postalCode: {type: string, pattern: '^[0-9]{5}$'} - items: - type: array - minItems: 1 - maxItems: 50 - items: - type: object - required: [sku, quantity] - properties: - sku: {type: string} - quantity: {type: integer, minimum: 1} - deliveryAt: {type: string, format: date-time, nullable: true} -``` - JSON schema is generated here only as an OpenAPI output format. Runtime validation uses the recursive DTO mapper and never requires a JSON schema. ### Long-running workers -The request values of a typed handler (body, files, path and header values) are kept in static state for the current request. `ApiPresenter::run()` resets it at the start of every request, so PHP-FPM, RoadRunner, FrankenPHP worker mode and Swoole all see only the current request as long as every request goes through `ApiPresenter` and a worker handles one request at a time. Concurrent requests in one process, such as interleaved Swoole coroutines, are not supported, because the state is process-wide. Code that calls a typed handler's `params()` outside the presenter in a worker, for example a test or a CLI command, calls `Tomaj\NetteApi\Input\RequestInput::reset()` and `Tomaj\NetteApi\Params\PathValues::reset()` first. - +The request values of a typed handler are kept in process-wide static state that `ApiPresenter::run()` resets at the start of every request, so workers (RoadRunner, FrankenPHP, Swoole) are fine as long as each handles one request at a time; concurrent coroutines in one process are not supported. Code that calls a typed handler's `params()` outside the presenter in a worker calls `Tomaj\NetteApi\Input\RequestInput::reset()` and `Tomaj\NetteApi\Params\PathValues::reset()` first. ## Security notes -- **Mapping runs before authorization.** The input is converted and validated before the authorization is checked, and only the answer waits for it: a client without access gets `401`, not field errors. The rate limit still runs first. A caster or a constraint is therefore reachable without a login, so keep them pure and cheap: no database, network or file access. Put `#[Length(max: ...)]` on every list. One request reports at most 100 errors in total, however deeply lists and objects are nested; the rest of the body is not checked. -- **Cap the request body at the web server.** `#[Length(max: ...)]` limits a list before its items are mapped, but the body is decoded first, and a list of small objects takes far more memory in PHP than in the request (up to roughly 70 times for a list of small objects, about 18 times for a list of numbers). Limit the size where the request enters: `client_max_body_size` in nginx, `LimitRequestBody` in Apache, and `post_max_size` and `memory_limit` in PHP. +- **Mapping runs before authorization.** The input is converted and validated before the authorization is checked, and only the answer waits for it: a client without access gets `401`, not field errors. The rate limit still runs first. A caster or a constraint is therefore reachable without a login, so keep them pure and cheap: no database, network or file access. Put `#[Length(max: ...)]` on every list. +- **Cap the request body at the web server.** `#[Length(max: ...)]` limits a list before its items are mapped, but the body is decoded first, and a decoded list takes many times more memory in PHP than in the request. Limit the size where the request enters: `client_max_body_size` in nginx, `LimitRequestBody` in Apache, and `post_max_size` and `memory_limit` in PHP. - **`#[Header]` is not proof of origin.** See the note under [source attributes](#source-attributes). - **Form bodies and cookies.** A DTO with body fields accepts URL-encoded forms by default, which any website can submit without a CORS preflight. For an endpoint authenticated by a cookie or by the client address, use `#[Consumes('application/json')]`, see [body, files and content types](/guide/typed-input-body#forms-and-cookie-authenticated-endpoints). ## Example -`examples/typed-input` follows the same standalone Composer layout and `e2e.sh` CI convention as the other examples (`public/index.php`): - -```text -examples/typed-input/ -├── composer.json -├── README.md -├── e2e.sh -├── config/common.neon -├── public/index.php -└── app/Api/ - ├── ListUsersHandler.php # query, backed enum and defaults - ├── UserDetailHandler.php # path id and X-Request-Id header - ├── CreateOrderHandler.php # JSON/form body, nested DTO and list - ├── AvatarUploadHandler.php # multipart body and FileUpload - └── Input/ # readonly DTOs and UserStatus -``` - -The end-to-end test covers successful JSON, form and multipart requests, defaults, enum conversion, every source attribute, strict rejection of `1a`, nested error paths and the generated OpenAPI document. CI runs it with the other examples. - - -## How it is built - -- **Compile-time metadata.** `NetteApiExtension` reflects DTOs and writes their `InputParam` definitions and mapping metadata into the compiled container. Requests and OpenAPI generation do not reflect DTOs again and need no cache invalidation setup; enum backing types are cached per class. Changing a DTO, its parent class, a trait it uses, a caster, a constraint or an enum rebuilds the container like changing endpoint attributes. Without the DI extension, a small generated-metadata registry is built once per request; no runtime Nette Cache dependency is introduced. -- **One metadata pipeline.** DTO metadata is translated into the existing `InputParam` objects, so validation, OpenAPI and the console have no separate DTO branches. -- **Recursive runtime validation.** It handles JSON, form and multipart consistently and gives exact property paths. A JSON schema is only generated for OpenAPI. -- **Readonly promoted properties only.** DTOs are instantiated once through their constructor and cannot be partially mutated by the mapper. A required constructor parameter that is not a promoted property, and variadic or by-reference parameters, are compile-time errors. -- **Strict, explicit scalar conversion.** Invalid client data is a `400`, not a surprising cast. -- **A small constraint set.** Range, Length, Pattern and Email cover common API contracts; custom constraints cover application rules without a validation framework. -- **JSON and form accepted by default, `Consumes` restricts.** One DTO serves JSON and form clients, and OpenAPI advertises the same media types; when a file is present, multipart replaces URL-encoded form, which cannot carry files. `Consumes` is a class-level attribute like the other endpoint attributes, and its name keeps it apart from the HTTP `Accept` header, which is about responses. -- **`handleDto(Input $input)` as the handler method.** The name states that it is the entry point of the handler, and reflection reads the DTO class from its parameter, so no extra attribute or configuration is needed. -- **`Cast` with `CasterInterface`.** Application formats stay local to a property, constructor arguments cover options such as `d.m.Y`, and `CastException` gives field-path 400 errors. An optional schema-hint interface keeps OpenAPI metadata optional for casters. - +A runnable project with every source attribute, a nested body and a file upload is described in [Typed input example](/examples/typed-input). diff --git a/docs/index.md b/docs/index.md index 6bc0e8f76..65fbe6898 100644 --- a/docs/index.md +++ b/docs/index.md @@ -71,7 +71,7 @@ and a few lines of configuration register it as `GET /api/v1/hello`: <<< @/../examples/hello-world/config/common.neon{yaml} -The [hello world example](/examples/hello-world) runs exactly this code in CI. +The `params()` tab is the [hello world example](/examples/hello-world), which runs in CI; the typed version is `GreetHandler` in [`examples/attributes`](/examples/attributes). ## Where to go next diff --git a/docs/sk/examples/typed-input.md b/docs/sk/examples/typed-input.md index 3d88c7b9d..d80b50631 100644 --- a/docs/sk/examples/typed-input.md +++ b/docs/sk/examples/typed-input.md @@ -39,6 +39,18 @@ Typované handlery, path a header parametre a `#[Consumes]` sú nové v 4.0.0. <<< @/../examples/typed-input/app/Api/UserDetailHandler.php +## Vnorené DTO tela + +`CreateOrderInput` obsahuje vnorený `AddressInput` a `list`; tie isté triedy čítajú JSON telo aj URL-enkódovaný formulár s názvami so zátvorkami. + +<<< @/../examples/typed-input/app/Api/Input/CreateOrderInput.php + +<<< @/../examples/typed-input/app/Api/Input/AddressInput.php + +<<< @/../examples/typed-input/app/Api/Input/ItemInput.php + +<<< @/../examples/typed-input/app/Api/CreateOrderHandler.php + ## Nahrávanie súboru <<< @/../examples/typed-input/app/Api/Input/AvatarInput.php diff --git a/docs/sk/guide/console.md b/docs/sk/guide/console.md index f11e8ddfa..cdd87674a 100644 --- a/docs/sk/guide/console.md +++ b/docs/sk/guide/console.md @@ -42,7 +42,7 @@ Konzola zostaví požiadavku z parametrov handlera, či už pochádzajú z `para | pole tela | prvý media type, ktorý handler číta a konzola ho vie zostaviť: JSON, URL-enkódovaný formulár alebo multipart | | súbor | multipart upload; pri priloženom súbore idú polia tela v tej istej multipart požiadavke | -V tele JSON si každá hodnota zachová deklarovaný typ a vstup pre vnorený objekt berie JSON text, napríklad `{}` pre prázdny objekt. Vstup pre zoznam má jedno políčko na položku a položka, ktorá je objekt, berie JSON text. Typované pole, ktoré ostane prázdne, sa nepošle (prázdny reťazec nikdy nie je platné číslo, dátum, voľba, objekt ani položka zoznamu), takže nepoužité políčko zoznamu sa preskočí. Prázdne voliteľné textové pole sa tiež nepošle, takže server použije jeho predvolenú hodnotu; povinné textové pole sa pošle ako prázdny reťazec, aby sa dali vyskúšať jeho obmedzenia dĺžky a patternu. Prázdna hlavička sa nepošle nikdy. Prázdna hodnota z cesty sa neposiela vôbec: konzola ukáže `The path value 'id' is empty. Fill it in and send the request again.` namiesto volania URL s prázdnym segmentom. Číslo, ktoré JSON nezvládne, napríklad `1e999` alebo celé číslo mimo 64-bitového rozsahu, sa pošle ako text, takže server odpovie svojím bežným `400`. +V tele JSON si každá hodnota zachová deklarovaný typ; vnorený objekt alebo položka zoznamu, ktorá je objekt, berie JSON text. Prázdne voliteľné polia sa neposielajú; pri prázdnej hodnote z cesty konzola namiesto odoslania ukáže chybu. ## Časté otázky diff --git a/docs/sk/guide/getting-started.md b/docs/sk/guide/getting-started.md index abba31505..73bfd1838 100644 --- a/docs/sk/guide/getting-started.md +++ b/docs/sk/guide/getting-started.md @@ -158,7 +158,7 @@ use Tomaj\NetteApi\Input\Query; use Tomaj\NetteApi\Response\JsonApiResponse; use Tomaj\NetteApi\Response\ResponseInterface; -// app/Api/HelloInput.php +// obe triedy v jednom súbore pre stručnosť; pri PSR-4 autoloadingu presuňte HelloInput do app/Api/HelloInput.php final readonly class HelloInput { public function __construct( @@ -168,7 +168,6 @@ final readonly class HelloInput } } -// app/Api/HelloHandler.php final class HelloHandler extends TypedHandler { public function summary(): string diff --git a/docs/sk/guide/input-styles.md b/docs/sk/guide/input-styles.md index ed8d4d16a..dadb5547a 100644 --- a/docs/sk/guide/input-styles.md +++ b/docs/sk/guide/input-styles.md @@ -1,15 +1,15 @@ --- title: params() a DTO vedľa seba -description: 'Rovnaké endpointy deklarované cez params() aj cez typované DTO v Nette API: sedem dvojíc ukazuje, ako prepísať handler z jedného štýlu na druhý.' +description: 'Rovnaké endpointy deklarované cez params() aj cez typované DTO v Nette API: šesť dvojíc ukazuje, ako prepísať handler z jedného štýlu na druhý.' --- # params() a DTO vedľa seba -`params()` s `handle(array $params)` a `TypedHandler` s DTO sú dva rovnocenné spôsoby písania handlerov v jednej aplikácii. Jeden nevypína druhý. Registrácia, autorizácia, výstupy, obmedzenia požiadaviek, OpenAPI a konzola sú spoločné. [Typovaný vstup (DTO)](/sk/guide/typed-input) oba štýly porovnáva a [Vstupné parametre](/sk/guide/params) popisujú prvý z nich. +`params()` a DTO v `TypedHandler` sú dva rovnocenné spôsoby deklarácie vstupu a v jednej aplikácii sa dajú kombinovať; [Typovaný vstup (DTO)](/sk/guide/typed-input) ich porovnáva. ## Prepisovanie medzi štýlmi -Nasledujúce dvojice ukazujú rovnaký kontrakt požiadavky v oboch štýloch, takže handler môžete prepísať z ktoréhokoľvek štýlu na druhý, keď sa to pre daný endpoint hodí. Importy frameworku sú vynechané tam, kde sa nemenia; závislosti aplikácie v konštruktore a vytváranie odpovede ostávajú v handleri. Môžete prepísať jeden endpoint, všetky ostatné handlery nechať bez zmeny a ďalší prepísať, keď sa vám to bude hodiť. Neexistuje globálny prepínač aplikácie. +Každá dvojica ukazuje rovnaký kontrakt požiadavky v oboch štýloch; importy frameworku sú vynechané a prepisovať môžete po jednom endpointe. ### 1. Jednoduchý GET: voliteľné/predvolené query parametre a enum @@ -282,7 +282,7 @@ final class LoginHandler extends BaseHandler } ``` -S DTO `Body` znamená pole tela bez ohľadu na to, či je požiadavka JSON alebo formulárová. Hranica `max` je tu jediné pravidlo dĺžky, pretože minimum by pri prihlásení začalo odmietať existujúce krátke heslá: +S DTO `Body` znamená pole tela bez ohľadu na to, či je požiadavka JSON alebo formulárová: ```php final readonly class LoginInput @@ -433,28 +433,6 @@ final class ScheduleHandler extends TypedHandler `ConstraintContext::value()` číta susedné hodnoty v tom istom DTO, takže validačné obmedzenia medzi properties nemusia skúmať HTTP požiadavku. Obchodné pravidlá, ktoré potrebujú databázu, stále patria do aplikačných služieb; validačné obmedzenie má ostať deterministickou kontrolou kontraktu požiadavky. -### 7. Oba štýly v jednej aplikácii - -Endpoint môže závisieť od voľnejšej konverzie `InputType::INTEGER` v `params()`, od vlastného `InputParam` alebo od ručného parsovania nezvyčajného content typu. Pre taký endpoint je `params()` správny štýl: - -```php -final class ReportHandler extends BaseHandler -{ - public function params(): array - { - return [new GetInputParam('offset', InputType::INTEGER)]; - } - - public function handle(array $params): ResponseInterface - { - // Existujúce správanie endpointu zámerne ostáva bez zmeny. - return $this->reports->generate($params['offset']); - } -} -``` - -Susediaci `ListReportsHandler` môže rozširovať `TypedHandler`. Miešanie štýlov je podporované bez obmedzenia; voľba sa týka pohodlia pri každom endpointe. - ### Kontrolný zoznam prepisu handlera na DTO 1. **Zachyťte aktuálny kontrakt:** uložte testy endpointu a aktuálnu OpenAPI operáciu vrátane predvolených hodnôt a chybového správania. diff --git a/docs/sk/guide/layers.md b/docs/sk/guide/layers.md index 546abab88..e92f89b0f 100644 --- a/docs/sk/guide/layers.md +++ b/docs/sk/guide/layers.md @@ -124,7 +124,7 @@ So službou `ApiLoggerInterface` v kontajneri sa zaloguje každá požiadavka, k ## Časté otázky -### Kam patrí obchodná logika? +### Kam patrí biznis logika? Do handlera alebo do služby, ktorú volá. Ostatné vrstvy iba rozhodujú, či sa spustí, a kontrolujú, čo vráti. diff --git a/docs/sk/guide/links.md b/docs/sk/guide/links.md index cd666394f..2d9242eac 100644 --- a/docs/sk/guide/links.md +++ b/docs/sk/guide/links.md @@ -15,17 +15,15 @@ $url = $apiLink->link(new EndpointIdentifier('GET', 1, 'users', 'detail'), ['id' Potrebuje routu na `Api:Api:default` s parametrami `version`, `package` a `apiAction`, ako v [Začíname](/sk/guide/getting-started). -Pri endpointe, ktorého URL má segmenty `{name}`, napríklad `{id}/detail`, `link()` nechá segmenty doslovné, čo je šablóna cesty z OpenAPI. Segment nahraďte hodnotou s URL kódovaním sami: +Pri endpointe, ktorého URL má segmenty `{name}`, napríklad `{id}/detail`, `link()` doplní každý segment z rovnomenného parametra (s URL kódovaním); ostatné parametre idú do query stringu. Segment bez hodnoty ostane doslovný, čo je šablóna cesty z OpenAPI: ```php -$url = $apiLink->link(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), ['limit' => 5]); -// https://example.com/api/v1/users/{id}/detail?limit=5 -$url = str_replace('{id}', rawurlencode('42'), $url); +$url = $apiLink->link(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), ['id' => 42, 'limit' => 5]); // https://example.com/api/v1/users/42/detail?limit=5 +$url = $apiLink->link(new EndpointIdentifier('GET', 1, 'users', '{id}/detail')); +// https://example.com/api/v1/users/{id}/detail ``` -API konzola robí to isté s hodnotami z vstupov pre cestu, a to po tom, čo `link()` zostavil URL, takže podtrieda, ktorá `link()` prepisuje, stále rozhoduje o URL každého endpointu. - V handleri, ktorý dedí z `BaseHandler` alebo `TypedHandler`, zavolajte `$this->createLink($params)` pre odkaz na vlastný endpoint handlera. Najprv potrebuje Nette `LinkGenerator`, inak vyhodí `Nette\InvalidStateException`. Pridajte do služby handlera riadok `setup`: ```yaml diff --git a/docs/sk/guide/params.md b/docs/sk/guide/params.md index 518ae6422..671a53235 100644 --- a/docs/sk/guide/params.md +++ b/docs/sk/guide/params.md @@ -63,7 +63,7 @@ V 3.x `?limit=abc` s typom `INTEGER` nie je chyba: hodnota sa pred validáciou p ## Parametre Path, Header a Body -`PathInputParam` číta hodnotu z URL endpointu. Placeholder deklarujte v akcii endpointu ako `{name}`, napríklad `users/{id}/detail`, ako popisuje [Typovaný vstup](/sk/guide/typed-input#hodnoty-z-cesty-a-sablony-url). Parameter je vždy povinný a jeho placeholder v OpenAPI má rovnaký názov. `HeaderInputParam` číta hlavičku požiadavky bez ohľadu na veľkosť písmen. `BodyInputParam` číta jedno pole objektu JSON, URL-enkódovaného formulára alebo multipart tela a `setContentTypes()` uvádza media typy, ktoré prijíma. Typované DTO vygeneruje tieto isté tri triedy z `#[Path]`, `#[Header]` a `#[Body]` a `params()` ich vie deklarovať priamo: +`PathInputParam` číta hodnotu z URL endpointu. Placeholder deklarujte v akcii endpointu ako `{name}`, napríklad `users/{id}/detail`, ako popisuje [Typovaný vstup](/sk/guide/typed-input#hodnoty-z-cesty-a-sablony-url). Parameter je vždy povinný a jeho placeholder v OpenAPI má rovnaký názov. `HeaderInputParam` číta hlavičku požiadavky bez ohľadu na veľkosť písmen. `BodyInputParam` číta jedno pole objektu JSON, URL-enkódovaného formulára alebo multipart tela a `setContentTypes()` uvádza media typy, ktoré prijíma. V typovanom DTO sa z properties `#[Path]`, `#[Header]` a `#[Body]` stanú objekty `MappedInputParam` s typom `TYPE_PATH`, `TYPE_HEADER` alebo `TYPE_BODY`; `params()` deklaruje tieto triedy priamo: ```php public function params(): array diff --git a/docs/sk/guide/problem-details.md b/docs/sk/guide/problem-details.md index 1a3141de5..4697b0b4a 100644 --- a/docs/sk/guide/problem-details.md +++ b/docs/sk/guide/problem-details.md @@ -55,7 +55,7 @@ Chyby validácie sú zoznam `{"parameter": ..., "detail": ...}` a posielajú sa ## Vlastné problémy z handlera -Obchodnú chybu, napríklad objednávku vypredaného produktu, vráti handler ako `ProblemDetailsResponse`: +Biznis chybu, napríklad objednávku vypredaného produktu, vráti handler ako `ProblemDetailsResponse`: ```php use Tomaj\NetteApi\Error\ProblemDetails; diff --git a/docs/sk/guide/typed-input-body.md b/docs/sk/guide/typed-input-body.md index c44ad6d24..0e747e98e 100644 --- a/docs/sk/guide/typed-input-body.md +++ b/docs/sk/guide/typed-input-body.md @@ -73,15 +73,65 @@ JSON telo požiadavky: } ``` -Mapper DTO rekurzívne vytvorí `AddressInput` a oba objekty `ItemInput`. `list` je povinný PHPDoc pre pole DTO; pre polia skalárov sú podporované `list`, `list`, `list` a `list`. Čítajú sa bežné zápisy: `list`, `non-empty-list`, `T[]`, s `|null` alebo úvodným `?` (nulovateľnosť určuje typ v PHP) a `@phpstan-param` alebo `@psalm-param` namiesto `@param`. Za typom môže nasledovať popis (`@var list Názvy vecí`). Položka je jeden nenulovateľný typ, preto `list` a `list` sú chybou kompilácie; použite DTO položky. Asociatívne polia, union typy okrem nulovateľných, `mixed`, `object` a netypované polia sa odmietnu pri kompilácii kontajnera, nie v polovici požiadavky. Predvolená hodnota zoznamu sa v tom istom čase skontroluje po položkách, takže `@param list` s predvolenou hodnotou `['x']` sa neskompiluje. +Mapper DTO rekurzívne vytvorí `AddressInput` a oba objekty `ItemInput`. Pole DTO potrebuje PHPDoc, napríklad `list`, a pole skalárov `list`, `list`, `list` alebo `list` (fungujú aj `non-empty-list`, `T[]`, `@phpstan-param` a `@psalm-param`); asociatívne polia, union typy, `mixed`, `object` a netypované polia zlyhajú pri kompilácii kontajnera. Rovnaké DTO funguje s URL-enkódovanými formulárovými poľami a s multipart poľami, ak má property `#[File]` alebo `#[Consumes('multipart/form-data')]`. Vnorené polia používajú PHP zápis s hranatými zátvorkami, napríklad `address[street]` a `items[0][sku]`; `deliveryAt` ostáva rovnaký RFC 3339 reťazec. Parsovanie tela závisí od content typu, nie od JSON schémy. -## Content typy tela +OpenAPI toto telo zdokumentuje takto (odpovede sú vynechané): + +```openapi +requestBody: + required: true + content: + application/json: + schema: + type: object + required: [customerEmail, address, items] + properties: + customerEmail: {type: string, format: email} + address: + type: object + required: [street, postalCode] + properties: + street: {type: string, minLength: 1, maxLength: 120} + postalCode: {type: string, pattern: '^[0-9]{5}$'} + items: + type: array + minItems: 1 + maxItems: 50 + items: + type: object + required: [sku, quantity] + properties: + sku: {type: string} + quantity: {type: integer, minimum: 1} + deliveryAt: {type: string, format: date-time, nullable: true} +``` + +Endpoint prijme aj formulár, ale OpenAPI 3.0 nevie opísať zoznam objektov vo formulárovom tele, preto je tu uvedený len JSON. DTO, ktorého telo má len skaláry, zoznamy skalárov a objekty skalárov, uvádza oba media typy; formulárová schéma pomenuje zoznam `tags[]` a objekt posiela ako `deepObject`: + +```openapi +requestBody: + content: + application/json: + schema: + type: object + properties: + tags: {type: array, items: {type: string}} + address: {type: object, properties: {street: {type: string}}} + application/x-www-form-urlencoded: + schema: + type: object + properties: + 'tags[]': {type: array, items: {type: string}} + address: {type: object, properties: {street: {type: string}}} + encoding: + address: {style: deepObject, explode: true} +``` -`TypedHandler` s poľami tela predvolene akceptuje **`application/json`** aj **`application/x-www-form-urlencoded`**. Ak jeho DTO obsahuje property `#[File]`, predvolené typy sú **`application/json`** a **`multipart/form-data`**: multipart nahradí URL-enkódovaný formulár, pretože ten nedokáže preniesť súbory, a súbory sa posielajú spolu s poľami tela. Content type sa porovnáva bez parametrov, takže `application/json; charset=utf-8` je akceptovaný. JSON sa vždy číta ako UTF-8: iný `charset`, napríklad `application/json; charset=ISO-8859-1`, je `400` namiesto nesprávneho dekódovania (akceptuje sa `utf-8`, jeho bežný zápis `utf8` a `us-ascii`). Telo, ktoré príde bez akéhokoľvek `Content-Type`, je `415` aj keď sú všetky polia voliteľné, inak by sa potichu zahodilo. +## Content typy tela -OpenAPI ponúka rovnaké možnosti v `requestBody.content`: JSON a URL-enkódovaný formulár alebo JSON a multipart pri súbore. Keď je súbor povinný, ponúka sa len multipart, pretože JSON požiadavka by mohla dostať len `400`. Properties so súbormi sú len v schéme `multipart/form-data`, pretože JSON nedokáže preniesť súbor. JSON požiadavka na DTO s povinným súborom dostane `400` s cestou poľa súboru a správou `File is required and can only be uploaded as multipart/form-data, but the request is application/json`. Polia tela sú parametre `TYPE_BODY` a súbory parametre `TYPE_FILE`; stále existuje len jedna cesta validácie a mapovania. +`TypedHandler` s poľami tela predvolene akceptuje **`application/json`** a **`application/x-www-form-urlencoded`**, alebo **`application/json`** a **`multipart/form-data`**, keď jeho DTO obsahuje property `#[File]`; OpenAPI uvádza rovnaké typy v `requestBody.content` (pri povinnom súbore len multipart). Content type sa porovnáva bez parametrov. JSON musí byť v UTF-8: požiadavka, ktorá uvedie iný `charset`, je `400`. Telo bez `Content-Type` alebo s typom, ktorý handler neprijíma, je `415`. Properties so súbormi sú len v schéme `multipart/form-data` a JSON požiadavka na DTO s povinným súborom dostane `400`, ktorá vysvetlí, že súbory potrebujú `multipart/form-data`. ### Obmedzenie akceptovaných typov cez Consumes @@ -118,7 +168,7 @@ Požiadavka s iným content typom sa pred mapovaním odmietne s **415 Unsupporte } ``` -Chýbajúci content type tela pri požiadavke, ktorá telo vyžaduje, dostane rovnakú zrozumiteľnú 415 namiesto neskoršej chyby null property. Pri zapnutých Problem Details sa použije status 415 a rovnaká hláška v tomto formáte a jeho `detail` vždy uvádza akceptované typy. Predvolená obálka `detail` vynechá, keď sú detaily chýb vypnuté, rovnako ako pri chybách polí. +So zapnutými Problem Details má 415 tento formát a jeho `detail` vždy uvádza akceptované typy. ### Rozdiely medzi JSON, formulárom a multipart @@ -136,13 +186,12 @@ Napríklad JSON `"quantity": 2` ostane integer, zatiaľ čo formulárové `quant Pre voliteľnú formulárovú hodnotu vynechajte `deliveryAt` namiesto poslania `deliveryAt=null` alebo prázdnej hodnoty. Multipart súbor nemožno nahradiť JSON base64 reťazcom; aplikácia, ktorá potrebuje base64 uploady, môže ponechať `BaseHandler` a spracovať vlastné raw telo. -PHP číta multipart telá len pri `POST`. Telo `multipart/form-data` poslané cez `PUT` alebo `PATCH` PHP nespracuje, preto endpoint odpovie `400` hláškou `multipart/form-data is only parsed by PHP for POST requests, but this one is PUT. Send it with POST, or use application/json`. Uploady a multipart formuláre posielajte cez `POST`. URL-enkódovaný formulár s viac poliami, než dovoľuje `max_input_vars` v PHP (predvolene 1000), je `400` s hláškou `Too many form fields`, pri `POST` aj pri `PUT` a `PATCH`. Multipart `POST` s väčším počtom polí PHP odreže skôr, než ho aplikácia uvidí, a nedá sa odlíšiť od úplného: pre takéto formuláre zvýšte `max_input_vars` alebo pošlite JSON. +Multipart posielajte cez `POST`. Formuláre nad `max_input_vars` sa odmietnu s `400`. ## Formuláre a endpointy autentifikované cez cookie URL-enkódovaný formulár je „jednoduchá“ požiadavka medzi webmi: stránka na ľubovoľnom webe ho môže odoslať do vášho API spolu s cookies návštevníka a bez CORS preflightu, čo telo JSON nedokáže. DTO s poľami tela formulár prijíma predvolene, takže endpoint autentifikovaný iba session cookie alebo adresou klienta sa dá zasiahnuť takým formulárom z cudzieho webu. Obmedzte ho na JSON cez `#[Consumes('application/json')]` a nastavte cookie `SameSite`. Endpointov autentifikovaných bearer tokenom alebo hlavičkou API kľúča sa to netýka, pretože formulár v prehliadači tieto hlavičky nastaviť nevie. - ## Nahrávanie súboru ```php @@ -160,5 +209,5 @@ final readonly class AvatarInput } ``` -`FileUpload` je typovaný value object knižnice pre nahraný súbor. Sprístupňuje pôvodný názov, content type od klienta, dočasnú cestu, veľkosť a chybu nahrávania; neverí content typu od klienta ani automaticky nepresúva súbor. `?FileUpload` znamená voliteľný súbor a `list` prijme viac súborov v jednom poli. Pred uložením skontrolujte chybu nahrávania, veľkosť a skutočný typ, rovnako ako pri `FileInputParam`. Chyby nahrávania ako `UPLOAD_ERR_INI_SIZE` sa nemenia na validačné chyby; `FileUpload` ich nesie v `error`. Za chýbajúci súbor sa považuje len chýbajúci záznam alebo `UPLOAD_ERR_NO_FILE` s prázdnym názvom, a pri `list` keď majú všetky položky `UPLOAD_ERR_NO_FILE`. Požiadavky s nahrávaním musia používať `POST`, pozrite vyššie. `#[File]` patrí do vstupného DTO handlera; `#[File]` vo vnorenom DTO alebo v zozname DTO je chybou kompilácie, pretože PHP drží vnorené uploady v samostatnom strome `$_FILES` a polia tela sa nikdy nesmú čítať ako metadáta uploadu. +`FileUpload` sprístupňuje pôvodný názov, content type od klienta, dočasnú cestu, veľkosť a chybu nahrávania. `?FileUpload` je voliteľný súbor a `list` prijme viac súborov v jednom poli. Handler pred uložením súboru skontroluje chybu nahrávania, veľkosť a skutočný typ; nič sa nepresúva automaticky. `#[File]` je povolený len v koreňovom vstupnom DTO handlera, nie vo vnorenom DTO ani v zozname. diff --git a/docs/sk/guide/typed-input-conversion.md b/docs/sk/guide/typed-input-conversion.md index 1e5a72c24..703592e45 100644 --- a/docs/sk/guide/typed-input-conversion.md +++ b/docs/sk/guide/typed-input-conversion.md @@ -21,11 +21,11 @@ Typovaný vstup sa nespolieha na voľné PHP pretypovania skalárov. | `DateTimeImmutable` | RFC 3339 reťazec s dátumom, časom a explicitným offsetom, napríklad `2026-11-06T14:30:00+01:00` (`T` a `Z` môžu byť malé písmená; priestupná sekunda ako `23:59:60` sa odmietne, pretože ju PHP nevie vyjadriť) | | `array` | zoznam, ktorého každá položka zodpovedá typu z PHPDoc | -Reťazec musí byť platné UTF-8, aby sa dal vložiť do JSON odpovede: `?q=%E9` (bajt Latin-1) je `400` `Value must be valid UTF-8` na poli, nie hodnota, pri ktorej `Length` alebo `Pattern` ohlási zavádzajúcu správu. JSON telo sa aj tak dekóduje ako UTF-8. Týka sa to len typovaného vstupu; handler s `params()` naďalej prijíma akékoľvek bajty ako doteraz, pretože zmena by odmietla požiadavky, ktoré dnes fungujú. +Kontrola UTF-8 platí len pre typovaný vstup; handler s `params()` naďalej prijíma akékoľvek bajty. -`?page=1a` pre integer je `400`, nikdy `1` alebo `null`. Biele znaky sa implicitne neodstránia a neznáme reťazce sa nemenia na `false`. JSON čísla a booleany si zachovajú typy, takže celé číslo zapísané ako float, `1.0` alebo `1e2`, nie je integer: klient, ktorý celé čísla serializuje ako floaty, musí pre integer property poslať `1`. Normalizácia aplikácie patrí do handlera alebo vlastného validačného obmedzenia, nie do prekvapivých globálnych pretypovaní. +`?page=1a` pre integer je `400`, nikdy `1` ani `null`. Biele znaky sa neodstraňujú a neznáme reťazce sa nemenia na `false`. JSON čísla a booleany si zachovajú typy, takže `1.0` ani `1e2` nie je integer. -Zoznam v query stringu používa PHP zápis so zátvorkami `ids[]=3&ids[]=4` a OpenAPI pomenuje parameter `ids[]`, aby ho vygenerovaní klienti posielali v tomto tvare. Hodnota oddelená čiarkami namiesto toho používa `Split`. Formulárové telá podporujú PHP názvy so zátvorkami; iné vnorené formulárové kódovania sa nedekódujú. V query môžu byť len skaláre, enumy a zoznamy z nich: vnorené DTO alebo `list` za `#[Query]` je chybou kompilácie, pretože OpenAPI nevie popísať vnorenie v PHP zápise so zátvorkami pre vygenerovaného klienta. Vnorené objekty čítajte z tela cez `#[Body]`. +Zoznam v query stringu používa PHP zápis so zátvorkami `ids[]=3&ids[]=4` (OpenAPI pomenuje parameter `ids[]`); hodnota oddelená čiarkami používa `Split`. V query môžu byť len skaláry, enumy a zoznamy z nich; vnorené objekty čítajte z tela cez `#[Body]`. Mapovanie DTO podporuje len päť zdrojov vyššie; vstup z iného zdroja použije `params()` s vlastným `InputParam`. @@ -37,10 +37,10 @@ Atribúty validačných obmedzení sú v `Tomaj\NetteApi\Validation` a dajú sa | --- | --- | --- | | `#[Range(min: 1, max: 100)]` | `int`, `float` | inkluzívne číselné hranice; jednu možno vynechať | | `#[Length(min: 1, max: 80)]` | `string`, `array` | počet Unicode znakov alebo položiek zoznamu; jednu hranicu možno vynechať; zoznam nad `max` sa odmietne skôr, než sa namapujú jeho položky | -| `#[Pattern('/^[A-Z]+$/')]` | `string` | kompletná zhoda s PCRE, `$` sedí len na úplnom konci, pretože sa pridáva modifikátor `D` (`/^[0-9]{5}$/` odmietne `81101` s koncovým novým riadkom); neplatný pattern je chybou kompilácie; pattern je PCRE, nie JavaScript, a vždy sa kontroluje cez PCRE; OpenAPI `pattern` je ECMA 262, preto ho dostane len výraz, ktorý tam znamená to isté, a inak sa celý PCRE pattern (aj s oddeľovačmi a príznakmi) uvedie v rozšírení `x-pattern`; ten jednoduchý podjazyk tvoria ASCII literály, escapované interpunkčné znaky, `\n`, `\r`, `\t`, triedy z literálov a rozsahov (aj s `\-`), skupiny, lookahead, alternatívy, kotvy a kvantifikátory, bez iného príznaku než `u` a `D`, pričom `\d`, `\w` a `\b` len bez `u`, pretože PCRE ich s `u` číta ako Unicode a JavaScript nie; všetko ostatné ide do `x-pattern`, medzi tým bodka, negované triedy, `\s`, `\D`, `\W`, `\p{L}`, `\x`, spätné odkazy, pomenované skupiny, lookbehind, znaky mimo ASCII, posesívne kvantifikátory, atomické skupiny, inline flagy a príznaky ako `i` | +| `#[Pattern('/^[A-Z]+$/')]` | `string` | kompletná zhoda s PCRE (pridá sa modifikátor `D`); neplatný pattern zlyhá pri kompilácii. OpenAPI dostane `pattern`, keď sa regex dá preniesť do JavaScriptu, inak `x-pattern` | | `#[Email]` | `string` | platná emailová adresa | -Validácia zhromaždí všetky chyby polí, nezastaví sa na prvej; jedna požiadavka nahlási najviac prvých 100 chýb spolu, aj z vnorených zoznamov, zvyšok tela sa nekontroluje a potom príde poznámka `Only the first 100 errors are reported, the rest of the request was not checked` pod kľúčom `body`, len ak sa skutočne niečo nechalo nekontrolované. Hlášky uvádzajú skutočné limity, napríklad `Value must have between 1 and 50 items` namiesto všeobecného `Invalid value`. +Validácia zhromaždí všetky chyby polí, nezastaví sa na prvej. Jedna požiadavka nahlási najviac 100 chýb vrátane vnorených zoznamov; keď niečo ostalo nekontrolované, povie to poznámka pod kľúčom `body`. Hlášky uvádzajú skutočné limity, napríklad `Value must have between 1 and 50 items` namiesto všeobecného `Invalid value`. ### Vlastné validačné obmedzenia @@ -53,7 +53,7 @@ interface ConstraintInterface } ``` -Pri úspechu vráti `null`, pri chybe jednu hlášku zrozumiteľnú vývojárovi. `ConstraintContext` sprístupňuje cestu property, triedu DTO a `value('sibling')` pre ostatné skonvertované properties toho istého DTO; predvolené hodnoty sa kontrolujú pri kompilácii kontajnera spolu so všetkými predvolenými hodnotami súrodencov a súrodenec bez predvolenej hodnoty je tam `null`; validačné obmedzenia nesmú hádzať výnimky pre bežný neplatný vstup klienta. Vlastné validačné obmedzenia nemajú reprezentáciu v OpenAPI, pokiaľ aplikácia nerozšíri OpenAPI buildery. +Pri úspechu vráťte `null`, pri chybe jednu hlášku. `ConstraintContext` sprístupňuje cestu property, triedu DTO a `value('sibling')` pre ostatné skonvertované properties toho istého DTO. Pre neplatný vstup klienta nevyhadzujte výnimku. Vlastné validačné obmedzenia nemajú reprezentáciu v OpenAPI, pokiaľ aplikácia nerozšíri OpenAPI buildery. ### Validačné obmedzenia položiek zoznamu @@ -88,7 +88,7 @@ Caster hlási neplatný klientsky vstup vyhodením `Tomaj\NetteApi\Input\CastExc } ``` -Iné výnimky sú chyby programátora/servera a nemaskujú sa ako klientske validačné chyby. Kompilácia kontajnera overí, že trieda castera existuje, je inštanciovateľná, implementuje `CasterInterface`, akceptuje deklarované argumenty atribútu a má natívny návratový typ `cast()` zhodný s typom property (alebo zdokumentovaný kovariantný typ podtriedy). Caster pre `list` musí deklarovať `array` so zhodným PHPDoc položiek zoznamu. Kontrola je obmedzená na natívne deklarácie; `mixed` nie je akceptovaný ako návratový typ castera. Nekompatibilný caster zlyhá pri kompilácii, nie pri prvej požiadavke. +Každá iná výnimka je chyba servera, nie validačná chyba. Kompilácia kontajnera overí, že caster implementuje `CasterInterface`, akceptuje argumenty atribútu a deklaruje natívny návratový typ `cast()` zhodný s typom property (pre `list` `array` s PHPDoc zoznamu; `mixed` sa neakceptuje). ### Nápovedy OpenAPI schémy @@ -126,7 +126,7 @@ final readonly class IssueInput } ``` -Nápoveď schémy `DateFormat('d.m.Y')` je `{type: string, example: '24.12.2026'}`. Len `DateFormat('Y-m-d')` pridá `format: date`, pretože OpenAPI `date` znamená plný dátum podľa RFC 3339. NUL bajt alebo iná nespracovateľná hodnota je `400` na danom poli, nie výnimka. +Nápoveda schémy `DateFormat('d.m.Y')` je `{type: string, example: '24.12.2026'}`; len `DateFormat('Y-m-d')` pridá `format: date`. ### CSV na list<string> @@ -143,7 +143,7 @@ final readonly class ReportInput } ``` -V OpenAPI je property jeden reťazec s príkladom `red,green,blue` a konzola ukazuje jedno textové pole. `?columns=id,createdAt,total` sa zmení na `['id', 'createdAt', 'total']`. `Split` vráti prázdny zoznam pre vynechanú voliteľnú property len cez jej bežnú predvolenú hodnotu; explicitne prítomný prázdny reťazec vytvorí `['']`, čo môže validačné obmedzenie zamietnuť. +V OpenAPI je property jeden reťazec a konzola ukazuje jedno textové pole. `?columns=id,createdAt,total` sa zmení na `['id', 'createdAt', 'total']`; prázdny reťazec dá `['']`, čo môže validačné obmedzenie zamietnuť. ### Desatinný reťazec na value object Money @@ -178,5 +178,5 @@ final readonly class PriceInput } ``` -`12,50` sa stane `Money` a následné vlastné validačné obmedzenie `PositiveMoney` dostane tento objekt `Money`. `12.50`, `1a` a pole vytvoria 400 na `price` s hláškou castera. Formátovanie špecifické pre menu ostáva v casteri aplikácie namiesto ďalšieho globálneho skalárneho pravidla. Keďže caster nahrádza vstavanú konverziu, `Money` sa nikdy nekompiluje ako transportné DTO: môže mať privátny konštruktor a statickú továrenskú metódu a kompilátor len skontroluje, že `cast()` deklaruje návratový typ `Money`. Pomenované argumenty castera, napríklad `#[Cast(MyCaster::class, suffix: 'x')]`, si v skompilovanom kontajneri zachovajú názvy. +`12,50` sa stane `Money` a validačné obmedzenia dostanú tento objekt. `12.50`, `1a` a pole vytvoria 400 na `price` s hláškou castera. Keďže caster nahrádza vstavanú konverziu, `Money` môže mať privátny konštruktor a statickú továrenskú metódu. diff --git a/docs/sk/guide/typed-input.md b/docs/sk/guide/typed-input.md index f265bc7d6..deac78716 100644 --- a/docs/sk/guide/typed-input.md +++ b/docs/sk/guide/typed-input.md @@ -26,7 +26,7 @@ Handler deklaruje svoj vstup jedným z dvoch rovnocenných spôsobov. Oba sú pl `params()` zvoľte, keď endpoint spolieha na jeho voľnejšiu konverziu, na vlastný `InputParam` alebo na ručné spracovanie nezvyčajného tela. DTO zvoľte, keď chcete typované hodnoty, vnorené telá, validačné obmedzenia cez viac polí alebo celý kontrakt požiadavky v jednej triede. Ani jeden štýl nie je zastaraný a voľba štýlu pre jeden endpoint neovplyvní žiadny iný. [params() a DTO vedľa seba](/sk/guide/input-styles) ukazuje ten istý endpoint napísaný oboma štýlmi. -`TypedHandler` prevedie deklaráciu DTO na tie isté objekty `InputParam`, ktoré vracia `params()`. +`TypedHandler` prevedie deklaráciu DTO na objekty `InputParam`, takže validácia, OpenAPI aj konzola fungujú ako pri `params()`. S DI rozšírením sa tieto metadáta skompilujú do kontajnera a zmena DTO, casteru, validačného obmedzenia alebo enumu ho prebuduje. Konštanta inej triedy použitá v argumente atribútu alebo v predvolenej hodnote sa nesleduje; po jej zmene vymažte cache. Bez rozšírenia sa metadáta zostavia raz za proces. ## Najmenší handler @@ -73,7 +73,7 @@ Závislosti v konštruktore, `summary()`, `description()`, `outputs()`, tagy a r ## Atribúty zdroja -Atribúty sú v `Tomaj\NetteApi\Input` a cielia na promované properties konštruktora. Každá promovaná property má práve jeden atribút zdroja. Externý názov je predvolene názov property; odovzdaním názvu ho zmeníte. `description` a opakovateľné `examples` sa stanú popisom a príkladmi vygenerovaného `InputParam`. +Atribúty sú v `Tomaj\NetteApi\Input` a cielia na promované properties konštruktora. Každá promovaná property má práve jeden atribút zdroja. Externý názov je predvolene názov property; odovzdaním názvu ho zmeníte. `description` a `examples` (pole, ktorého kľúče sú názvy príkladov, ako pri `InputParam::addExample()`) sa stanú popisom a príkladmi vygenerovaného `InputParam`. | Atribút | Zdroj | Typ vygenerovaného parametra | | --- | --- | --- | @@ -87,13 +87,13 @@ Každá property DTO sa stane jedným `MappedInputParam`, teda `InputParam`, kto Napríklad `#[Header('X-Request-Id')] public ?string $requestId = null` číta `X-Request-Id`, nie `requestId`. Vyhľadávanie hlavičky nerozlišuje veľkosť písmen. Názov v `#[Path]` začína písmenom alebo podčiarkovníkom a má písmená, číslice a podčiarkovníky, pretože sa píše ako segment `{name}`; názov v `#[Header]` používa pomlčky, nie podčiarkovníky (`X-Request-Id`, nie `X_Request_Id`), pretože PHP sprístupňuje názvy hlavičiek s pomlčkami. Čokoľvek iné je chybou kompilácie s opraveným názvom. Hodnota z cesty alebo hlavičky je jeden reťazec, preto je tam natívny zoznam alebo vnorené DTO chybou kompilácie; rozdeľte ju casterom, napríklad `#[Header('X-Tags')] #[Cast(Split::class, ',')] public array $tags`. -`PathInputParam` a `HeaderInputParam` sú verejné aj pre handlery, ktoré používajú `params()`, pozrite [Vstupné parametre](/sk/guide/params#parametre-path-header-a-body). +`PathInputParam`, `HeaderInputParam` a `BodyInputParam` sú verejné aj pre handlery, ktoré používajú `params()`, pozrite [Vstupné parametre](/sk/guide/params#parametre-path-header-a-body). -`#[Header]` nepoužívajte pre hlavičku, ktorú proxy nastavuje alebo odstraňuje ako nositeľku dôvery, napríklad `X-Forwarded-User`. PHP a webservery mapujú `X_Request_Id` aj `X-Request-Id` na rovnaký názov, takže klient môže poslať podobne vyzerajúcu hlavičku. Takéto hodnoty overte v proxy a kópiu od klienta tam zahoďte. Hlavička `Authorization` sa číta aj z `REDIRECT_HTTP_AUTHORIZATION`, ktorú Apache s CGI alebo FastCGI nastaví po prepise, napríklad `RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]`. `BearerTokenAuthorization` ju číta rovnako, takže token, ktorý sa dostane do `#[Header('Authorization')]`, sa dostane aj do autorizácie. Ostatné hlavičky sa čítajú zo serverových premenných `HTTP_*`. +`#[Header]` nepoužívajte pre hlavičku, ktorú proxy nastavuje alebo odstraňuje ako nositeľku dôvery, napríklad `X-Forwarded-User`. PHP a webservery mapujú `X_Request_Id` aj `X-Request-Id` na rovnaký názov, takže klient môže poslať podobne vyzerajúcu hlavičku. Takéto hodnoty overte v proxy a kópiu od klienta tam zahoďte. ### Hodnoty z cesty a šablóny URL -Hodnota z cesty sa deklaruje v URL endpointu ako `{name}`, napríklad `users/{id}/detail`. Je povinná, nemôže byť nulovateľná ani mať predvolenú hodnotu a placeholder v OpenAPI ceste má rovnaký názov. Chýbajúci alebo nedeklarovaný parameter cesty je chybou kompilácie kontajnera. Statické URL endpointov fungujú bez zmeny. Hodnota z cesty je jeden segment URL: cesta sa pred porovnaním dekóduje, takže zakódované lomítko (`%2F`) sa číta ako oddeľovač a endpoint sa nenájde. Hodnotu, ktorá môže obsahovať `/`, posielajte v query alebo v tele. +Hodnota z cesty sa deklaruje v URL endpointu ako `{name}`, napríklad `users/{id}/detail`. Je povinná, nemôže byť nulovateľná ani mať predvolenú hodnotu a placeholder v OpenAPI ceste má rovnaký názov. Chýbajúci alebo nedeklarovaný parameter cesty je chybou kompilácie kontajnera. Statické URL endpointov fungujú bez zmeny. Hodnota z cesty je jeden segment URL. Segmenty sa URL-dekódujú až po rozdelení cesty, takže zakódované lomítko ostane v hodnote: `/users/a%2Fb/detail` dá `id` `a/b`. Šablónu zaregistrujte ako akciu endpointu niektorým zo zvyčajných spôsobov: @@ -112,13 +112,13 @@ final class UserDetailHandler extends TypedHandler $apiDecider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), new UserDetailHandler(), new NoAuthorization()); ``` -Route musí prepustiť aj dodatočný segment, ako to robí route v [príklade typovaného vstupu](/sk/examples/typed-input): `/api/v/[/][/]`. Požiadavka sa hľadá najprv medzi statickými endpointmi a potom medzi šablónami. Ak jednej URL vyhovujú dve šablóny, požiadavka skončí s `LogicException`, ktorá pomenuje obe, takže zmeňte statický segment tak, aby sa líšili. +Route musí prepustiť segmenty šablóny. Route z [príkladu typovaného vstupu](/sk/examples/typed-input), `/api/v/[/][/]`, prepustí za akciou jeden segment; hlbšia šablóna ako `{id}/orders/{orderId}` potrebuje v maske route `[/]`, inak Nette odpovie `404` skôr, ako požiadavka dorazí do API. Požiadavka sa hľadá najprv medzi statickými endpointmi a potom medzi šablónami. Ak jednej URL vyhovujú dve šablóny, požiadavka skončí s `LogicException`, ktorá pomenuje obe, takže zmeňte statický segment tak, aby sa líšili. ### Povinné hodnoty a predvolené hodnoty Nenulovateľná property bez predvolenej hodnoty je povinná. Nulovateľná property alebo property s predvolenou hodnotou je voliteľná. Chýbajúca nulovateľná hodnota sa stane `null`; chýbajúca hodnota s predvolenou hodnotou použije túto hodnotu. Rovnako sa nastaví `required` v OpenAPI. -Povinné parametre cesty nemôžu byť nulovateľné ani mať predvolenú hodnotu. Voliteľné pole tela akceptuje vynechanie poľa, zatiaľ čo explicitné JSON `null` akceptuje len nulovateľná property. Prázdny reťazec sa potichu nemení na `null`. Predvolená hodnota je `null`, skalár, pole alebo case backed enumu; objekt ako predvolená hodnota, napríklad `= new Inner()`, je chybou kompilácie, pretože predvolené hodnoty sa ukladajú do skompilovaného kontajnera. Použite `= null` a objekt vytvorte v handleri. +Povinné parametre cesty nemôžu byť nulovateľné ani mať predvolenú hodnotu. Voliteľné pole tela akceptuje vynechanie poľa, zatiaľ čo explicitné JSON `null` akceptuje len nulovateľná property. Prázdny reťazec sa potichu nemení na `null`. Predvolená hodnota je `null`, skalár, pole alebo case backed enumu; objekt ako predvolená hodnota, napríklad `= new Inner()`, je chybou kompilácie. Použite `= null` a objekt vytvorte v handleri. ## Kompletný príklad požiadavky @@ -155,7 +155,6 @@ X-Request-Id: req-01J8Y7N6R9 Handler dostane `id: 42`, `limit: 10`, `status: UserStatus::Active` a reťazec s ID požiadavky. Nie sú potrebné pretypovania ani prístupy ku kľúčom poľa. - Požiadavka s telom, vnoreným DTO a zoznamom je v stránke [telo, súbory a content typy](/sk/guide/typed-input-body#post-s-vnorenym-dto-a-polom). ## Chybové odpovede @@ -177,13 +176,13 @@ Obálka odpovede ostáva rovnaká ako pri `ParamsProcessor`. Kľúč detailu je Pri vypnutých detailoch chýb sa vrátia len `status` a `message`. So zapnutými Problem Details sa rovnaké cesty polí a hlášky objavia v jeho rozšírení pre chyby vstupu. Pokazené JSON a nečitateľné telo zachovajú existujúce chyby parsera tela. -Kľúč `body` nesie aj zlyhania tela požiadavky ako celku, napríklad `Too many form fields`, nesprávny charset JSON a poznámku, že sa hlásia len prvých 100 chýb. Pole DTO, ktoré sa samo volá `body`, ten kľúč zdieľa, takže jeho hlášky sa vypíšu spolu s nimi; ak ich chcete oddeliť, dajte property iný externý názov, napríklad `#[Body('payload')]`. +Chyby tela požiadavky ako celku sa objavia pod `body`; pole nenazývajte `body` (použite `#[Body('payload')]`). Chýbajúci vnorený objekt nahlási cestu vnoreného objektu. Neznáme vstupné polia sa ignorujú, rovnako ako pri bežných query/formulárových parametroch; potichu sa nemapujú na properties. ## OpenAPI a API konzola -`TypedHandler::params()` sprístupní vygenerované objekty `InputParam`, takže existujúca konzola automaticky získa popisky, označenie povinnosti, predvolené hodnoty, príklady, voľby enumov a polia pre súbory. Konzola pošle každú hodnotu do jej zdroja: hodnoty z cesty sa URL-enkódujú do segmentov `{name}`, hodnoty hlavičiek sa stanú hlavičkami požiadavky a hodnoty tela sa pošlú v prvom media type, ktorý handler číta a konzola ho vie zostaviť: JSON s deklarovanými typmi (pole s vnoreným DTO berie JSON text, pole so zoznamom má jeden vstup na položku a položka DTO berie JSON text), URL-enkódovaný formulár alebo multipart. Súbor vždy znamená multipart, s názvami so zátvorkami pre vnorené polia. Neexistuje osobitný DTO režim konzoly, pozrite [Webová konzola](/sk/guide/console). +[Webová konzola](/sk/guide/console) zostaví formulár z vygenerovaných objektov `InputParam` a každú hodnotu pošle do jej zdroja; osobitný DTO režim neexistuje. V OpenAPI sa query, path a header properties stanú parametrami operácie. Properties tela sa spoja do jednej objektovej schémy; vnorené DTO a zoznamy sa stanú vnorenými schémami. Predvolene `requestBody.content` obsahuje `application/json` aj `application/x-www-form-urlencoded`, alebo JSON a `multipart/form-data`, ak DTO obsahuje súbor. `#[Consumes]` obmedzí tento zoznam aj akceptované požiadavky na explicitné media typy. Operácia s telom dokumentuje aj odpoveď `415`. `nullable: true` sa objaví len pri properties tela: query reťazec, segment cesty ani hlavička nemôžu niesť `null`, takže voliteľná hodnota z query alebo hlavičky jednoducho chýba. Nulovateľný enum uvádza `null` vo svojom `enum`, ako to vyžaduje OpenAPI 3.0.3. @@ -209,82 +208,19 @@ parameters: schema: {type: string} ``` -Príklad POST pridá: - -```openapi -requestBody: - required: true - content: - application/json: - schema: - type: object - required: [customerEmail, address, items] - properties: - customerEmail: {type: string, format: email} - address: - type: object - required: [street, postalCode] - properties: - street: {type: string, minLength: 1, maxLength: 120} - postalCode: {type: string, pattern: '^[0-9]{5}$'} - items: - type: array - minItems: 1 - maxItems: 50 - items: - type: object - required: [sku, quantity] - properties: - sku: {type: string} - quantity: {type: integer, minimum: 1} - deliveryAt: {type: string, format: date-time, nullable: true} -``` - JSON schéma sa tu generuje len ako výstupný formát OpenAPI. Runtime validácia používa rekurzívny mapper DTO a nikdy nevyžaduje JSON schému. ### Dlho bežiace workery -Hodnoty požiadavky typovaného handlera (telo, súbory, hodnoty z cesty a hlavičiek) sa držia v statickom stave pre aktuálnu požiadavku. `ApiPresenter::run()` ho vynuluje na začiatku každej požiadavky, takže PHP-FPM, RoadRunner, worker režim FrankenPHP aj Swoole vidia len aktuálnu požiadavku, pokiaľ každá požiadavka prechádza cez `ApiPresenter` a worker spracúva jednu požiadavku naraz. Súbežné požiadavky v jednom procese, napríklad prekladané Swoole korutiny, nie sú podporované, pretože stav je spoločný pre celý proces. Kód, ktorý vo workeri volá `params()` typovaného handlera mimo presentera, napríklad test alebo CLI príkaz, najprv zavolá `Tomaj\NetteApi\Input\RequestInput::reset()` a `Tomaj\NetteApi\Params\PathValues::reset()`. - +Hodnoty požiadavky typovaného handlera sa držia v statickom stave celého procesu, ktorý `ApiPresenter::run()` vynuluje na začiatku každej požiadavky, takže workery (RoadRunner, FrankenPHP, Swoole) sú v poriadku, pokiaľ každý spracúva jednu požiadavku naraz; súbežné korutiny v jednom procese podporované nie sú. Kód, ktorý vo workeri volá `params()` typovaného handlera mimo presentera, najprv zavolá `Tomaj\NetteApi\Input\RequestInput::reset()` a `Tomaj\NetteApi\Params\PathValues::reset()`. ## Bezpečnostné poznámky -- **Mapovanie beží pred autorizáciou.** Vstup sa konvertuje a validuje skôr, ako sa skontroluje autorizácia, a čaká až odpoveď: klient bez prístupu dostane `401`, nie chyby polí. Obmedzenie požiadaviek beží stále ako prvé. Caster alebo validačné obmedzenie je teda dostupné bez prihlásenia, preto ich držte čisté a lacné: žiadny prístup k databáze, sieti ani súborom. Na každý zoznam dajte `#[Length(max: ...)]`. Jedna požiadavka nahlási najviac 100 chýb spolu, nech sú zoznamy a objekty vnorené akokoľvek hlboko; zvyšok tela sa nekontroluje. -- **Veľkosť tela obmedzte na webservery.** `#[Length(max: ...)]` obmedzí zoznam skôr, ako sa jeho položky mapujú, ale telo sa dekóduje ako prvé a zoznam malých objektov zaberie v PHP oveľa viac pamäte než v požiadavke (až zhruba 70-krát pri zozname malých objektov, približne 18-krát pri zozname čísel). Obmedzte veľkosť tam, kde požiadavka vstupuje: `client_max_body_size` v nginx, `LimitRequestBody` v Apache a `post_max_size` s `memory_limit` v PHP. +- **Mapovanie beží pred autorizáciou.** Vstup sa konvertuje a validuje skôr, ako sa skontroluje autorizácia, a čaká až odpoveď: klient bez prístupu dostane `401`, nie chyby polí. Obmedzenie požiadaviek beží stále ako prvé. Caster alebo validačné obmedzenie je teda dostupné bez prihlásenia, preto ich držte čisté a lacné: žiadny prístup k databáze, sieti ani súborom. Na každý zoznam dajte `#[Length(max: ...)]`. +- **Veľkosť tela obmedzte na webservery.** `#[Length(max: ...)]` obmedzí zoznam skôr, ako sa jeho položky mapujú, ale telo sa dekóduje ako prvé a dekódovaný zoznam zaberie v PHP mnohonásobne viac pamäte než v požiadavke. Obmedzte veľkosť tam, kde požiadavka vstupuje: `client_max_body_size` v nginx, `LimitRequestBody` v Apache a `post_max_size` s `memory_limit` v PHP. - **`#[Header]` nie je dôkaz pôvodu.** Pozrite poznámku pod [atribútmi zdroja](#atributy-zdroja). - **Formuláre a cookies.** DTO s poľami tela predvolene prijíma URL-enkódované formuláre, ktoré môže odoslať ľubovoľný web bez CORS preflightu. Pre endpoint autentifikovaný cookie alebo adresou klienta použite `#[Consumes('application/json')]`, pozrite [telo, súbory a content typy](/sk/guide/typed-input-body#formulare-a-endpointy-autentifikovane-cez-cookie). ## Príklad -`examples/typed-input` má rovnaký samostatný Composer layout a konvenciou `e2e.sh` v CI ako ostatné príklady. Súbory sú rozložené ako v ostatných príkladoch (`public/index.php`): - -```text -examples/typed-input/ -├── composer.json -├── README.md -├── e2e.sh -├── config/common.neon -├── public/index.php -└── app/Api/ - ├── ListUsersHandler.php # query, enum s hodnotou a predvolené hodnoty - ├── UserDetailHandler.php # path id a hlavička X-Request-Id - ├── CreateOrderHandler.php # JSON/formulárové telo, vnorené DTO a list - ├── AvatarUploadHandler.php # multipart telo a FileUpload - └── Input/ # readonly DTO a UserStatus -``` - -End-to-end test pokrýva úspešné JSON, formulárové a multipart požiadavky, predvolené hodnoty, konverziu enumov, každý atribút zdroja, striktné zamietnutie `1a`, cesty vnorených chýb a vygenerovaný OpenAPI dokument. CI ho spúšťa spolu s ostatnými príkladmi. - - -## Ako je to postavené - -- **Metadáta pri kompilácii.** `NetteApiExtension` reflektuje DTO a zapíše ich definície `InputParam` a metadáta mapovania do skompilovaného kontajnera. Požiadavky ani generovanie OpenAPI DTO znova nereflektujú a nepotrebujú žiadne nastavenie invalidácie cache; backing typy enumov sa cachujú pre každú triedu. Zmena DTO, jeho rodičovskej triedy, traitu, ktorý používa, casteru, validačného obmedzenia alebo enumu prebuduje kontajner rovnako ako zmena atribútov endpointov. Bez DI rozšírenia sa raz za požiadavku zostaví malý register vygenerovaných metadát; nepridáva sa žiadna runtime závislosť na Nette Cache. -- **Jeden pipeline metadát.** Metadáta DTO sa prekladajú na existujúce objekty `InputParam`, takže validácia, OpenAPI a konzola nemajú osobitné vetvy pre DTO. -- **Rekurzívna runtime validácia.** Spracuje JSON, formulár aj multipart rovnako a dáva presné cesty k properties. JSON schéma sa generuje len pre OpenAPI. -- **Iba readonly promoted properties.** DTO sa vytvoria raz cez konštruktor a mapper ich nemôže čiastočne meniť. Povinný parameter konštruktora, ktorý nie je promoted property, a variadické alebo referenčné parametre sú chybou kompilácie. -- **Striktná, explicitná konverzia skalárov.** Neplatné dáta od klienta sú `400`, nie prekvapivý cast. -- **Malá sada validačných obmedzení.** Range, Length, Pattern a Email pokrývajú bežné kontrakty API; vlastné validačné obmedzenia pokrývajú pravidlá aplikácie bez validačného frameworku. -- **Predvolene JSON aj formulár, `Consumes` obmedzuje.** Jedno DTO obslúži klientov s JSON aj formulárom a OpenAPI inzeruje rovnaké media typy; keď je prítomný súbor, multipart nahradí URL-enkódovaný formulár, ktorý súbory nezvládne. `Consumes` je atribút na úrovni triedy ako ostatné atribúty endpointov a jeho názov ho odlišuje od HTTP hlavičky `Accept`, ktorá sa týka odpovedí. -- **`handleDto(Input $input)` ako metóda handlera.** Názov hovorí, že ide o vstupný bod handlera, a reflexia číta triedu DTO z jeho parametra, takže netreba ďalší atribút ani konfiguráciu. -- **`Cast` s `CasterInterface`.** Formáty aplikácie ostávajú pri property, argumenty konštruktora pokrývajú voľby ako `d.m.Y` a `CastException` dáva chyby 400 s cestou k poľu. Voliteľné rozhranie nápovedy schémy necháva metadáta OpenAPI pre castery nepovinné. - +Spustiteľný projekt so všetkými atribútmi zdroja, vnoreným telom a nahrávaním súboru popisuje [príklad typovaného vstupu](/sk/examples/typed-input). diff --git a/docs/sk/index.md b/docs/sk/index.md index a7679a1a8..6caccbefd 100644 --- a/docs/sk/index.md +++ b/docs/sk/index.md @@ -71,7 +71,7 @@ a niekoľko riadkov konfigurácie ho zaregistruje ako `GET /api/v1/hello`: <<< @/../examples/hello-world/config/common.neon{yaml} -[Príklad hello world](/sk/examples/hello-world) spúšťa presne tento kód v CI. +Záložka `params()` je [príklad hello world](/sk/examples/hello-world), ktorý beží v CI; typovaná verzia je `GreetHandler` v [`examples/attributes`](/sk/examples/attributes). ## Kam ďalej diff --git a/examples/typed-input/e2e.sh b/examples/typed-input/e2e.sh index 66bfc5149..cac82f807 100755 --- a/examples/typed-input/e2e.sh +++ b/examples/typed-input/e2e.sh @@ -66,5 +66,6 @@ rm -f "$png" request "$BASE/api/v1/openapi" expect_status 200 "openapi" expect_body '"in":"path"' "path parameter" -expect_body 'application/x-www-form-urlencoded' "form content type" -ok "OpenAPI lists the path parameter and both body content types" +expect_body '"in":"header"' "header parameter" +expect_body '"multipart/form-data"' "multipart content type" +ok "OpenAPI lists the path and header parameters and the multipart body" diff --git a/src/ApiDecider.php b/src/ApiDecider.php index 1fbc01242..242ce63f5 100644 --- a/src/ApiDecider.php +++ b/src/ApiDecider.php @@ -13,6 +13,7 @@ use Tomaj\NetteApi\Handlers\CorsPreflightHandler; use Tomaj\NetteApi\Handlers\CorsPreflightHandlerInterface; use Tomaj\NetteApi\Handlers\DefaultHandler; +use Tomaj\NetteApi\Handlers\TypedHandler; use Tomaj\NetteApi\Input\EndpointTemplate; use Tomaj\NetteApi\Params\InputParam; use Tomaj\NetteApi\Params\PathValues; @@ -50,6 +51,10 @@ public function getApi(string $method, string $version, string $package, ?string foreach ($this->apis as $api) { $identifier = $api->getEndpoint(); + if (str_contains($identifier->getUrl(), '{')) { + // a template is matched by matchPath(), a literal "{id}" in the request must not reach it + continue; + } if ($method === $identifier->getMethod() && $identifier->getVersion() === $version && $identifier->getPackage() === $package && $identifier->getApiAction() === $apiAction) { $endpointIdentifier = new EndpointIdentifier($method, $version, $package, $apiAction); $handler = $this->getHandler($api); @@ -217,8 +222,16 @@ private function matchTemplate(string $method, string $version, string $requestP return $matched; } + /** + * A URL template must match the path params of its handler. A plain handler on a static URL is skipped, + * so its params() is not called one more time on every request. + */ private function checkPath(EndpointInterface $endpoint, ApiHandlerInterface $handler): void { + if (!str_contains($endpoint->getUrl(), '{') && !$handler instanceof TypedHandler) { + return; + } + $names = []; foreach ($handler->params() as $param) { if ($param->getType() === InputParam::TYPE_PATH) { diff --git a/src/DI/NetteApiExtension.php b/src/DI/NetteApiExtension.php index feebc9685..62217b0bb 100644 --- a/src/DI/NetteApiExtension.php +++ b/src/DI/NetteApiExtension.php @@ -147,7 +147,7 @@ final class NetteApiExtension extends CompilerExtension /** @var array own service name => service it returns ("@name" in neon) */ private array $aliases = []; - /** @var array> handler class => compiled DTO metadata */ + /** @var array handler class => serialized DTO metadata, unserialized on first use */ private array $typedExport = []; public function __construct() @@ -1462,12 +1462,18 @@ private function compileTypedInput(): void continue; } - $metadata = DtoCompiler::compile($class); + ['metadata' => $metadata, 'files' => $files] = DtoCompiler::compileWithFiles($class); EndpointTemplate::assert($url, $metadata->pathNames(), sprintf('%s (%s)', $class, $endpoint->source)); - foreach ($metadata->files as $file) { - $this->compiler->addDependencies([$file]); + $this->compiler->addDependencies($files); + try { + $this->typedExport[$class] = serialize($metadata); + } catch (\Throwable $exception) { + throw new \LogicException(sprintf( + 'The typed input of %s cannot be stored in the compiled container: %s. Constraints and #[Cast] arguments have to be serializable.', + $class, + $exception->getMessage(), + ), previous: $exception); } - $this->typedExport[$class] = $metadata->export(); } EndpointTemplate::assertDisjoint($urls); diff --git a/src/Input/Body.php b/src/Input/Body.php index f4b7e3d26..aba11d641 100644 --- a/src/Input/Body.php +++ b/src/Input/Body.php @@ -8,7 +8,7 @@ * Reads a promoted DTO property from a JSON, form or multipart body field. */ #[\Attribute(\Attribute::TARGET_PROPERTY)] -final readonly class Body +final readonly class Body implements SourceAttribute { /** * @param array $examples named examples, the same pairs as InputParam::addExample() @@ -19,4 +19,10 @@ public function __construct( public array $examples = [], ) { } + + #[\Override] + public function source(): Source + { + return Source::Body; + } } diff --git a/src/Input/DtoCompiler.php b/src/Input/DtoCompiler.php index 18347aad6..bd33ac028 100644 --- a/src/Input/DtoCompiler.php +++ b/src/Input/DtoCompiler.php @@ -31,6 +31,19 @@ public static function compile(string $handler): DtoMetadata return new self()->handler($handler); } + /** + * Also returns the absolute paths of the handler, DTO, enum, constraint and caster files, so editing one rebuilds the container. + * + * @return array{metadata: DtoMetadata, files: list} + */ + public static function compileWithFiles(string $handler): array + { + $compiler = new self(); + $metadata = $compiler->handler($handler); + + return ['metadata' => $metadata, 'files' => array_values($compiler->files)]; + } + private function handler(string $handler): DtoMetadata { if (!class_exists($handler)) { @@ -67,7 +80,7 @@ private function handler(string $handler): DtoMetadata } } - return new DtoMetadata($handler, $dto, $fields, $contentTypes, $bodyRequired, $readsBody, $firstBody, array_values($this->files)); + return new DtoMetadata($handler, $dto, $fields, $contentTypes, $bodyRequired, $readsBody, $firstBody); } /** @param \ReflectionClass<*> $handler */ @@ -207,7 +220,7 @@ private function dto(string $class, bool $root): array implode(' -> ', [...$this->stack, $class]), )); } - if (!class_exists($class) && !interface_exists($class) && !enum_exists($class)) { + if (!class_exists($class) && !interface_exists($class)) { $this->fail(sprintf( "DTO '%s' does not exist. Use a readonly class in the same project, and check the namespace and the use statement.", $class, @@ -264,18 +277,25 @@ private function dto(string $class, bool $root): array $fields = []; $names = []; + $headers = []; foreach ($properties as $property) { $field = $this->property($property, $reflection, $root); - if (isset($names[$field->externalName])) { + // header names are case-insensitive, so X-Id and x-id are one header + $header = $field->source === Source::Header ? strtolower($field->externalName) : null; + $taken = $names[$field->externalName] ?? ($header === null ? null : $headers[$header] ?? null); + if ($taken !== null) { $this->fail(sprintf( "%s properties \$%s and \$%s both use the external name '%s'. Each input name can be declared once; pass a different name, for example #[Query('pageSize')].", $class, - $names[$field->externalName], + $taken, $field->property, $field->externalName, )); } $names[$field->externalName] = $field->property; + if ($header !== null) { + $headers[$header] = $field->property; + } $fields[] = $field; } $this->checkDefaults($class, $fields); @@ -348,31 +368,13 @@ private function property(\ReflectionProperty $property, \ReflectionClass $dto, $this->checkDefaultValue($class, $name, $default); } - $enumClass = null; - $enumInt = false; - $enumValues = []; - if (!$builtin && enum_exists($typeName)) { - if (!is_a($typeName, \BackedEnum::class, true)) { - $this->fail(sprintf( - '%s::$%s uses %s, which is not a backed enum. Give the enum a string or int backing (`enum Status: string`) or accept the backing value as a string.', - $class, - $name, - $typeName, - )); - } - $enumClass = $typeName; - $this->touch(new \ReflectionEnum($typeName)); - $backing = new \ReflectionEnum($typeName)->getBackingType(); - $enumInt = $backing instanceof \ReflectionNamedType && $backing->getName() === 'int'; - $enumValues = ScalarCoercer::enumValues($typeName); - } + $enum = $builtin ? null : $this->enum($typeName, $class, $name); // a caster replaces the built-in conversion, so its result type is not compiled as a transport DTO $casted = $property->getAttributes(Cast::class) !== []; $children = []; $item = null; $listItem = null; - $listItemBuiltin = false; if ($typeName === 'array') { if ($list === null) { $found = $this->documentedType($property, $dto); @@ -381,13 +383,12 @@ private function property(\ReflectionProperty $property, \ReflectionClass $dto, $class, $name, $name, - $found === null ? '' : sprintf(' Found `%s`, but only list, non-empty-list and T[] are read.', $found), + $found === null ? '' : sprintf(' Found `%s`, but only list, non-empty-list and T[] are read.', $found['type']), )); } $listItem = $list['name']; - $listItemBuiltin = $list['builtin']; - $item = $casted ? null : $this->itemField($list, $source['source'], $class, $name, $root); - } elseif (!$casted && !$builtin && $enumClass === null && $typeName !== \DateTimeImmutable::class && $typeName !== FileUpload::class) { + $item = $casted ? null : $this->itemField($list, $source['source'], $class, $name); + } elseif (!$casted && !$builtin && $enum === null && $typeName !== \DateTimeImmutable::class && $typeName !== FileUpload::class) { $children = $this->dto($typeName, false); } @@ -421,27 +422,26 @@ private function property(\ReflectionProperty $property, \ReflectionClass $dto, } $constraints = $this->constraints($property, $dto, $typeName); - $cast = $this->caster($property, $dto, $typeName, $builtin, $listItem, $listItemBuiltin); - $this->checkListDefault($class, $name, $default, $listItem, $listItemBuiltin); + $cast = $this->caster($property, $dto, $typeName, $builtin, $listItem); + if ($list !== null) { + $default = $this->listDefault($class, $name, $default, $list); + } return new Field( property: $name, externalName: $external, source: $source['source'], typeName: $typeName, - builtin: $builtin, nullable: $nullable, hasDefault: $hasDefault, default: $default, description: $source['attribute']->description, examples: $this->examples($source['attribute'], $class, $name), listItem: $listItem, - listItemBuiltin: $listItemBuiltin, - enumClass: $enumClass, - enumInt: $enumInt, - enumValues: $enumValues, - constraints: $constraints['instances'], - constraintSpecs: $constraints['specs'], + enumClass: $enum['class'] ?? null, + enumInt: $enum['int'] ?? false, + enumValues: $enum['values'] ?? [], + constraints: $constraints, casterClass: $cast['class'], casterArguments: $cast['arguments'], casterSchema: $cast['schema'], @@ -517,28 +517,23 @@ private function type(\ReflectionProperty $property, \ReflectionClass $dto): arr /** * @param \ReflectionClass<*> $dto - * @return array{source: Source, attribute: Query|Path|Header|Body|File} + * @return array{source: Source, attribute: SourceAttribute} */ private function source(\ReflectionProperty $property, \ReflectionClass $dto, bool $root): array { $found = []; - foreach ($property->getAttributes() as $attribute) { - $name = $attribute->getName(); - if (!is_a($name, Query::class, true) && !is_a($name, Path::class, true) && !is_a($name, Header::class, true) && !is_a($name, Body::class, true) && !is_a($name, File::class, true)) { - continue; - } + foreach ($property->getAttributes(SourceAttribute::class, \ReflectionAttribute::IS_INSTANCEOF) as $attribute) { try { - $instance = $attribute->newInstance(); + $found[] = $attribute->newInstance(); } catch (\Throwable $exception) { $this->fail(sprintf( '%s::$%s attribute %s is invalid: %s.', $dto->getName(), $property->getName(), - new \ReflectionClass($name)->getShortName(), + new \ReflectionClass($attribute->getName())->getShortName(), $exception->getMessage(), )); } - $found[] = $this->sourceAttribute($instance); } if ($found === []) { $this->fail(sprintf( @@ -556,13 +551,7 @@ private function source(\ReflectionProperty $property, \ReflectionClass $dto, bo } $attribute = $found[0]; - $source = match (true) { - $attribute instanceof Query => Source::Query, - $attribute instanceof Path => Source::Path, - $attribute instanceof Header => Source::Header, - $attribute instanceof Body => Source::Body, - $attribute instanceof File => Source::File, - }; + $source = $attribute->source(); if (!$root && $source === Source::File) { $this->fail(sprintf( 'Nested DTO %s::$%s uses #[File]. Uploads are read only on the root DTO; move the property to the input DTO of the handler, for example #[File] public FileUpload $%s.', @@ -583,28 +572,7 @@ private function source(\ReflectionProperty $property, \ReflectionClass $dto, bo return ['source' => $source, 'attribute' => $attribute]; } - private function sourceAttribute(object $instance): Query|Path|Header|Body|File - { - if ($instance instanceof Query) { - return $instance; - } - if ($instance instanceof Path) { - return $instance; - } - if ($instance instanceof Header) { - return $instance; - } - if ($instance instanceof Body) { - return $instance; - } - if ($instance instanceof File) { - return $instance; - } - - throw new \LogicException(sprintf('Attribute %s is not an input source. Use #[Query], #[Path], #[Header], #[Body] or #[File].', $instance::class)); - } - - private function externalName(Query|Path|Header|Body|File $attribute, string $property, string $class): string + private function externalName(SourceAttribute $attribute, string $property, string $class): string { $name = $attribute->name ?? $property; if ($name === '') { @@ -651,7 +619,7 @@ private function externalName(Query|Path|Header|Body|File $attribute, string $pr /** * @return array */ - private function examples(Query|Path|Header|Body|File $attribute, string $class, string $property): array + private function examples(SourceAttribute $attribute, string $class, string $property): array { $examples = []; foreach ($attribute->examples as $name => $example) { @@ -674,10 +642,11 @@ private function examples(Query|Path|Header|Body|File $attribute, string $class, */ private function list(\ReflectionProperty $property, \ReflectionClass $dto, string $typeName): ?array { - $documented = $this->documentedType($property, $dto); - if ($documented === null) { + $found = $this->documentedType($property, $dto); + if ($found === null) { return null; } + $documented = $found['type']; // nullability comes from the native type, so `?list`, `list|null` and `null|list` mean list $type = preg_replace('/^\?\s*|\s*\|\s*null$|^null\s*\|\s*/i', '', $documented) ?? $documented; @@ -723,7 +692,8 @@ private function list(\ReflectionProperty $property, \ReflectionClass $dto, stri )); } - $resolved = TypeName::resolve($item, $dto); + // relative to the class that declares the docblock, which is a parent when the constructor is inherited + $resolved = TypeName::resolve($item, $found['scope']); $builtin = in_array($resolved, ['string', 'int', 'float', 'bool'], true); if (!$builtin && !class_exists($resolved)) { $this->fail(sprintf( @@ -740,48 +710,76 @@ private function list(\ReflectionProperty $property, \ReflectionClass $dto, stri /** * The documented type of a property: `@param` of the constructor or the property, `@var` of the property. * `@phpstan-param` and `@psalm-param` win over `@param`, because they are the more precise ones. + * The scope is the class that declares the docblock, whose namespace and imports resolve a class name in it. * * @param \ReflectionClass<*> $dto + * @return array{type: string, scope: \ReflectionClass<*>}|null */ - private function documentedType(\ReflectionProperty $property, \ReflectionClass $dto): ?string + private function documentedType(\ReflectionProperty $property, \ReflectionClass $dto): ?array { $propertyDoc = $property->getDocComment() ?: ''; + $propertyScope = $property->getDeclaringClass(); $constructor = $dto->getConstructor(); - $constructorDoc = $constructor instanceof \ReflectionMethod ? ($constructor->getDocComment() ?: '') : ''; - $doc = sprintf("%s\n%s", $propertyDoc, $constructorDoc); + $docs = [[$propertyDoc, $propertyScope]]; + if ($constructor instanceof \ReflectionMethod) { + $docs[] = [$constructor->getDocComment() ?: '', $constructor->getDeclaringClass()]; + } $name = $property->getName(); foreach (['(?:phpstan|psalm)-param', 'param'] as $tag) { - if (preg_match('/@' . $tag . '\s+([^$]*?)\s*\$' . $name . '\b/s', $doc, $match) === 1 && $match[1] !== '') { - return $match[1]; + foreach ($docs as [$doc, $scope]) { + if (preg_match('/@' . $tag . '\s+([^$]*?)\s*\$' . $name . '\b/s', $doc, $match) === 1 && $match[1] !== '') { + return ['type' => $match[1], 'scope' => $scope]; + } } } // one type, possibly with spaces inside its brackets, and then maybe a description: `@var list Names` if (preg_match('/@(?:phpstan-|psalm-)?var\s+((?:[^\s<>{}()*]|(?[<{(](?:[^<>{}()]|(?&b))*[>})]))+)/', $propertyDoc, $match) === 1) { - return $match[1]; + return ['type' => $match[1], 'scope' => $propertyScope]; } return null; } + /** + * A backed enum type, or null for a type that is not an enum. A pure enum has no wire value, so it fails. + * + * @return array{class: class-string<\BackedEnum>, int: bool, values: list}|null + */ + private function enum(string $typeName, string $class, string $property): ?array + { + if (!enum_exists($typeName)) { + return null; + } + if (!is_a($typeName, \BackedEnum::class, true)) { + $this->fail(sprintf( + '%s::$%s uses %s, which is not a backed enum. Give the enum a string or int backing (`enum Status: string`) or accept the backing value as a string.', + $class, + $property, + $typeName, + )); + } + $reflection = new \ReflectionEnum($typeName); + $this->touch($reflection); + $backing = $reflection->getBackingType(); + + return [ + 'class' => $typeName, + 'int' => $backing instanceof \ReflectionNamedType && $backing->getName() === 'int', + 'values' => ScalarCoercer::enumValues($typeName), + ]; + } + /** * @param array{name: string, builtin: bool} $list */ - private function itemField(array $list, Source $source, string $class, string $property, bool $root): Field + private function itemField(array $list, Source $source, string $class, string $property): Field { $itemName = $list['name']; $builtin = $list['builtin']; $children = []; - $enumClass = null; - $enumInt = false; - $enumValues = []; - if (!$builtin && is_a($itemName, \BackedEnum::class, true)) { - $enumClass = $itemName; - $this->touch(new \ReflectionEnum($itemName)); - $backing = new \ReflectionEnum($itemName)->getBackingType(); - $enumInt = $backing instanceof \ReflectionNamedType && $backing->getName() === 'int'; - $enumValues = ScalarCoercer::enumValues($itemName); - } elseif (!$builtin && $itemName !== FileUpload::class && $itemName !== \DateTimeImmutable::class) { + $enum = $builtin ? null : $this->enum($itemName, $class, $property); + if (!$builtin && $enum === null && $itemName !== FileUpload::class && $itemName !== \DateTimeImmutable::class) { $children = $this->dto($itemName, false); } @@ -790,19 +788,16 @@ private function itemField(array $list, Source $source, string $class, string $p externalName: $property, source: $source, typeName: $itemName, - builtin: $builtin, nullable: false, hasDefault: false, default: null, description: null, examples: [], listItem: null, - listItemBuiltin: false, - enumClass: $enumClass, - enumInt: $enumInt, - enumValues: $enumValues, + enumClass: $enum['class'] ?? null, + enumInt: $enum['int'] ?? false, + enumValues: $enum['values'] ?? [], constraints: [], - constraintSpecs: [], casterClass: null, casterArguments: [], casterSchema: null, @@ -814,17 +809,12 @@ enumValues: $enumValues, /** * @param \ReflectionClass<*> $dto - * @return array{instances: list, specs: list, args: array}>} + * @return list */ private function constraints(\ReflectionProperty $property, \ReflectionClass $dto, string $typeName): array { $instances = []; - $specs = []; - foreach ($property->getAttributes() as $attribute) { - $name = $attribute->getName(); - if (!is_a($name, ConstraintInterface::class, true)) { - continue; - } + foreach ($property->getAttributes(ConstraintInterface::class, \ReflectionAttribute::IS_INSTANCEOF) as $attribute) { try { $instance = $attribute->newInstance(); } catch (\Throwable $exception) { @@ -832,30 +822,16 @@ private function constraints(\ReflectionProperty $property, \ReflectionClass $dt '%s::$%s constraint %s is invalid: %s.', $dto->getName(), $property->getName(), - new \ReflectionClass($name)->getShortName(), + new \ReflectionClass($attribute->getName())->getShortName(), $exception->getMessage(), )); } - if (!$instance instanceof ConstraintInterface) { - $this->fail(sprintf( - '%s::$%s attribute %s must implement %s to be used as a constraint.', - $dto->getName(), - $property->getName(), - $name, - ConstraintInterface::class, - )); - } $this->constraintApplies($instance, $typeName, $dto->getName(), $property->getName()); $this->touch(new \ReflectionClass($instance)); - $arguments = []; - foreach ($attribute->getArguments() as $key => $argument) { - $arguments[$key] = $argument; - } $instances[] = $instance; - $specs[] = ['class' => $instance::class, 'args' => $arguments]; } - return ['instances' => $instances, 'specs' => $specs]; + return $instances; } private function constraintApplies(ConstraintInterface $constraint, string $typeName, string $class, string $property): void @@ -888,7 +864,7 @@ private function constraintApplies(ConstraintInterface $constraint, string $type * @param \ReflectionClass<*> $dto * @return array{class: class-string|null, arguments: array, schema: array|null} */ - private function caster(\ReflectionProperty $property, \ReflectionClass $dto, string $typeName, bool $builtin, ?string $listItem, bool $listBuiltin): array + private function caster(\ReflectionProperty $property, \ReflectionClass $dto, string $typeName, bool $builtin, ?string $listItem): array { $found = $property->getAttributes(Cast::class); if (count($found) > 1) { @@ -998,7 +974,8 @@ private function casterReturn(\ReflectionClass $caster, \ReflectionClass $dto, s } $documented = $this->documentedList($method); $expected = $listItem; - if ($documented === null || TypeName::resolve($documented, $caster) !== $expected) { + // relative to the class that declares cast(), which is a parent when the method is inherited + if ($documented === null || TypeName::resolve($documented, $method->getDeclaringClass()) !== $expected) { $this->fail(sprintf( '%s::cast() must document `@return list<%s>` because %s::$%s is that list%s. The check reads the docblock of cast().', $caster->getName(), @@ -1104,12 +1081,16 @@ private function checkDefaultValue(string $class, string $property, mixed $defau /** * A list default is a PHP value of the result type, so every item has to have the declared item type. + * An int in a list default becomes a float, as a request value would. + * + * @param array{name: string, builtin: bool} $list */ - private function checkListDefault(string $class, string $property, mixed $default, ?string $listItem, bool $listItemBuiltin): void + private function listDefault(string $class, string $property, mixed $default, array $list): mixed { - if (!is_array($default) || $listItem === null) { - return; + if (!is_array($default)) { + return $default; } + ['name' => $listItem, 'builtin' => $listItemBuiltin] = $list; if (!array_is_list($default)) { $this->fail(sprintf('%s::$%s default must be a list, for example [], because the property is list<%s>.', $class, $property, $listItem)); } @@ -1132,6 +1113,8 @@ private function checkListDefault(string $class, string $property, mixed $defaul )); } } + + return $listItem === 'float' ? array_map(static fn (mixed $item): mixed => is_int($item) ? (float) $item : $item, $default) : $default; } /** diff --git a/src/Input/DtoMapper.php b/src/Input/DtoMapper.php index a21e9b899..f9199fcb2 100644 --- a/src/Input/DtoMapper.php +++ b/src/Input/DtoMapper.php @@ -80,7 +80,7 @@ private function evaluate(): void } $result = $this->convert($field, RequestInput::read($field), $field->externalName); if ($result['errors'] !== []) { - self::merge($this->errors, $result['errors'], $result['value']); + self::merge($this->errors, $result['errors']); continue; } $converted[$field->property] = $result['value']; @@ -143,11 +143,11 @@ private function convert(Field $field, mixed $raw, string $path): array return ['value' => $value, 'errors' => []]; } - if ($field->source === Source::File || $field->typeName === FileUpload::class) { + if ($field->source === Source::File) { return $this->file($field, $raw, $path); } if ($field->item instanceof Field) { - return $this->list($field, $raw, $path); + return $this->list($field, $field->item, $raw, $path); } if ($field->children !== []) { return $this->object($field, $raw, $path); @@ -177,7 +177,7 @@ private function object(Field $field, mixed $raw, string $path): array $childRaw = array_key_exists($child->externalName, $raw) ? $raw[$child->externalName] : new MissingValue(); $result = $this->convert($child, $childRaw, sprintf('%s.%s', $path, $child->externalName)); if ($result['errors'] !== []) { - self::merge($errors, $result['errors'], $result['value']); + self::merge($errors, $result['errors']); continue; } $converted[$child->property] = $result['value']; @@ -197,13 +197,13 @@ private function object(Field $field, mixed $raw, string $path): array return ['value' => null, 'errors' => $errors]; } - return ['value' => $this->instantiate($field->typeName, $field->children, $converted), 'errors' => []]; + return ['value' => DtoMetadata::construct($field->typeName, $field->children, static fn (Field $child): mixed => $converted[$child->property]), 'errors' => []]; } /** * @return array{value: mixed, errors: array>} */ - private function list(Field $field, mixed $raw, string $path): array + private function list(Field $field, Field $item, mixed $raw, string $path): array { if (!is_array($raw) || !array_is_list($raw)) { return $this->fail($path, 'Value must be a list'); @@ -217,15 +217,13 @@ private function list(Field $field, mixed $raw, string $path): array } } - $item = $field->itemField(); - $values = []; $errors = []; $index = 0; foreach ($this->untilTruncated($raw) as $value) { $result = $this->convert($item, $value, sprintf('%s[%d]', $path, $index++)); if ($result['errors'] !== []) { - self::merge($errors, $result['errors'], $result['value']); + self::merge($errors, $result['errors']); continue; } $values[] = $result['value']; @@ -258,7 +256,7 @@ private function file(Field $field, mixed $raw, string $path): array return $this->fail($path, 'Value must be a file upload'); } - return ['value' => FileUpload::fromFile(self::fileEntry(is_array($raw) ? $raw : [])), 'errors' => []]; + return ['value' => FileUpload::fromFile(is_array($raw) ? $raw : []), 'errors' => []]; } /** @@ -268,7 +266,7 @@ private function file(Field $field, mixed $raw, string $path): array private static function fileList(array $file): array { if (!is_array($file['name'] ?? null)) { - return [self::fileEntry($file)]; + return [$file]; } $result = []; @@ -285,20 +283,6 @@ private static function fileList(array $file): array return $result; } - /** - * @param array $file - * @return array - */ - private static function fileEntry(array $file): array - { - $entry = []; - foreach ($file as $key => $value) { - $entry[$key] = $value; - } - - return $entry; - } - private function scalar(Field $field, mixed $raw): mixed { if ($field->enumClass !== null) { @@ -321,20 +305,6 @@ private function scalar(Field $field, mixed $raw): mixed return ScalarCoercer::toDateTime($raw); } - /** - * @param list $children - * @param array $values - */ - private function instantiate(string $class, array $children, array $values): object - { - $arguments = []; - foreach ($children as $child) { - $arguments[$child->property] = $values[$child->property]; - } - - return new $class(...$arguments); - } - /** * @param list $properties * @param array $values @@ -391,12 +361,8 @@ private function fail(string $path, string $message): array * @param array> $left * @param array> $right */ - private static function merge(array &$left, array $right, mixed $value): void + private static function merge(array &$left, array $right): void { - if ($value !== null) { - throw new \LogicException('A field error is reported without discarding the converted value.'); - } - foreach ($right as $path => $messages) { foreach ($messages as $message) { $left[$path][] = $message; diff --git a/src/Input/DtoMetadata.php b/src/Input/DtoMetadata.php index d42565e58..e29df1ef2 100644 --- a/src/Input/DtoMetadata.php +++ b/src/Input/DtoMetadata.php @@ -15,7 +15,6 @@ /** * @param list $fields root properties, in constructor order * @param list $contentTypes - * @param list $files absolute paths of the handler and DTO files, so editing one rebuilds the container */ public function __construct( public string $handler, @@ -25,7 +24,6 @@ public function __construct( public bool $bodyRequired, public bool $readsBody, public ?string $firstBody, - public array $files, ) { } @@ -47,13 +45,24 @@ public function inputParams(): array * @param array $values values keyed by the external name, already converted */ public function instantiate(array $values): object + { + return self::construct($this->class, $this->fields, static fn (Field $field): mixed => $values[$field->externalName]); + } + + /** + * Creates a DTO with each field's value passed as the named constructor argument. + * + * @param list $fields + * @param \Closure(Field): mixed $value + */ + public static function construct(string $class, array $fields, \Closure $value): object { $arguments = []; - foreach ($this->fields as $field) { - $arguments[$field->property] = $values[$field->externalName]; + foreach ($fields as $field) { + $arguments[$field->property] = $value($field); } - return new ($this->class)(...$arguments); + return new $class(...$arguments); } /** @@ -70,64 +79,4 @@ public function pathNames(): array return $names; } - - /** - * @return array - */ - public function export(): array - { - return [ - 'handler' => $this->handler, - 'class' => $this->class, - 'fields' => array_map(static fn (Field $field): array => $field->export(), $this->fields), - 'contentTypes' => $this->contentTypes, - 'bodyRequired' => $this->bodyRequired, - 'readsBody' => $this->readsBody, - 'firstBody' => $this->firstBody, - 'files' => $this->files, - ]; - } - - /** - * @param array $data - */ - public static function import(array $data): self - { - $fields = []; - $exportedFields = $data['fields'] ?? null; - if (!is_array($exportedFields)) { - throw new \LogicException('Compiled DTO metadata has no fields. Rebuild the DI container.'); - } - foreach ($exportedFields as $field) { - if (!is_array($field)) { - throw new \LogicException('Compiled DTO metadata has a field that is not an array. Rebuild the DI container.'); - } - $fields[] = Field::import(self::stringKeyed($field)); - } - - return new self( - is_string($data['handler']) ? $data['handler'] : '', - is_string($data['class']) ? $data['class'] : '', - $fields, - is_array($data['contentTypes']) ? array_values(array_filter($data['contentTypes'], is_string(...))) : [], - (bool) $data['bodyRequired'], - (bool) $data['readsBody'], - is_string($data['firstBody']) ? $data['firstBody'] : null, - is_array($data['files']) ? array_values(array_filter($data['files'], is_string(...))) : [], - ); - } - - /** - * @param array $data - * @return array - */ - private static function stringKeyed(array $data): array - { - $keyed = []; - foreach ($data as $key => $value) { - $keyed[$key] = $value; - } - - return $keyed; - } } diff --git a/src/Input/DtoMetadataRegistry.php b/src/Input/DtoMetadataRegistry.php index b35482fb6..9cf6da329 100644 --- a/src/Input/DtoMetadataRegistry.php +++ b/src/Input/DtoMetadataRegistry.php @@ -8,27 +8,26 @@ /** * DTO metadata compiled with the DI container, or once per process when the extension is not used. + * The container installs every handler serialized; a handler is unserialized when it is first used. */ final class DtoMetadataRegistry { - /** @var array */ - private array $handlers = []; + /** @var array serialized DtoMetadata from the container, keyed by the handler */ + private static array $installed = []; - /** @var array */ - private static array $runtime = []; + private static bool $isInstalled = false; - private static ?self $installed = null; + /** @var array */ + private static array $metadata = []; /** - * @param array> $exported + * @param array $serialized serialize() of each handler's DtoMetadata */ - public static function install(array $exported): void + public static function install(array $serialized): void { - $registry = new self(); - foreach ($exported as $handler => $data) { - $registry->handlers[$handler] = DtoMetadata::import($data); - } - self::$installed = $registry; + self::$installed = $serialized; + self::$isInstalled = true; + self::$metadata = []; } /** @@ -36,7 +35,7 @@ public static function install(array $exported): void */ public static function installed(): bool { - return self::$installed !== null; + return self::$isInstalled; } /** @@ -44,7 +43,7 @@ public static function installed(): bool */ public static function installs(string $handler): bool { - return self::$installed !== null && isset(self::$installed->handlers[$handler]); + return isset(self::$installed[$handler]); } /** @@ -52,14 +51,20 @@ public static function installs(string $handler): bool */ public static function forHandler(string $handler): DtoMetadata { - if (self::$installed !== null && isset(self::$installed->handlers[$handler])) { - return self::$installed->handlers[$handler]; + if (isset(self::$metadata[$handler])) { + return self::$metadata[$handler]; + } + if (!isset(self::$installed[$handler])) { + return self::$metadata[$handler] = DtoCompiler::compile($handler); } - if (isset(self::$runtime[$handler])) { - return self::$runtime[$handler]; + + // the container is generated code, so its payload is trusted + $metadata = unserialize(self::$installed[$handler]); + if (!$metadata instanceof DtoMetadata) { + throw new \LogicException(sprintf('Compiled DTO metadata of %s is invalid. Rebuild the DI container.', $handler)); } - return self::$runtime[$handler] = DtoCompiler::compile($handler); + return self::$metadata[$handler] = $metadata; } /** @@ -67,7 +72,8 @@ public static function forHandler(string $handler): DtoMetadata */ public static function reset(): void { - self::$installed = null; - self::$runtime = []; + self::$installed = []; + self::$isInstalled = false; + self::$metadata = []; } } diff --git a/src/Input/EndpointTemplate.php b/src/Input/EndpointTemplate.php index 24a8fb5be..2ad884dba 100644 --- a/src/Input/EndpointTemplate.php +++ b/src/Input/EndpointTemplate.php @@ -16,8 +16,9 @@ public static function placeholders(string $url): array { $names = []; foreach (self::segments($url) as $segment) { - if (preg_match('/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/', $segment, $match) === 1) { - $names[] = $match[1]; + $name = self::placeholderName($segment); + if ($name !== null) { + $names[] = $name; } } @@ -32,12 +33,15 @@ public static function isComposite(string $value): bool if (!str_contains($value, '{') || !str_contains($value, '/')) { return false; } - return array_all(explode('/', $value), fn($segment): bool => !(preg_match('/^(?:[A-Za-z0-9_.-]+|\{[A-Za-z_][A-Za-z0-9_]*\})$/', $segment) !== 1)); + return array_all( + explode('/', $value), + static fn (string $segment): bool => self::placeholderName($segment) !== null || preg_match('/^[A-Za-z0-9_.-]+$/', $segment) === 1, + ); } /** * Captured path parameters when $path matches $template, otherwise null. - * Both values are endpoint URLs such as v1/users/{id}/detail and v1/users/42/detail. + * Both values are endpoint URLs such as v1/users/{id}/detail and v1/users/42/detail; $path is still URL-encoded. * * @return array|null */ @@ -51,14 +55,17 @@ public static function match(string $template, string $path): ?array $captured = []; foreach ($expected as $index => $segment) { - if (preg_match('/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/', $segment, $match) === 1) { - if ($actual[$index] === '') { + // decoded per segment, so an encoded slash (%2F) stays inside its value + $value = rawurldecode($actual[$index]); + $name = self::placeholderName($segment); + if ($name !== null) { + if ($value === '') { return null; } - $captured[$match[1]] = $actual[$index]; + $captured[$name] = $value; continue; } - if ($segment !== $actual[$index]) { + if ($segment !== $value) { return null; } } @@ -68,11 +75,12 @@ public static function match(string $template, string $path): ?array /** * Request path reduced to the endpoint URL (v1/users/42), or null when the version is not in the path. + * Segments stay URL-encoded; match() decodes them one by one. */ public static function normalize(string $requestPath, string $version): ?string { $path = parse_url($requestPath, PHP_URL_PATH); - $path = rawurldecode(is_string($path) ? $path : $requestPath); + $path = is_string($path) ? $path : $requestPath; $marker = sprintf('/v%s/', $version); $position = strpos($path, $marker); if ($position === false) { @@ -105,7 +113,7 @@ public static function assert(string $url, array $declared, string $where): void } foreach (self::segments($url) as $segment) { - if (str_contains($segment, '{') && preg_match('/^\{[A-Za-z_][A-Za-z0-9_]*\}$/', $segment) !== 1) { + if (str_contains($segment, '{') && self::placeholderName($segment) === null) { throw new \LogicException(sprintf( "%s: '%s' is not a path parameter in the endpoint URL '%s'. Write a name in braces, for example {id}, as its own URL segment.", $where, @@ -170,9 +178,7 @@ public static function overlaps(string $left, string $right): bool foreach ($leftSegments as $index => $segment) { $other = $rightSegments[$index]; - $leftPlaceholder = preg_match('/^\{[A-Za-z_][A-Za-z0-9_]*\}$/', $segment) === 1; - $rightPlaceholder = preg_match('/^\{[A-Za-z_][A-Za-z0-9_]*\}$/', $other) === 1; - if (!$leftPlaceholder && !$rightPlaceholder && $segment !== $other) { + if (self::placeholderName($segment) === null && self::placeholderName($other) === null && $segment !== $other) { return false; } } @@ -180,6 +186,14 @@ public static function overlaps(string $left, string $right): bool return true; } + /** + * The name of a {name} segment, null for a static segment. + */ + private static function placeholderName(string $segment): ?string + { + return preg_match('/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/', $segment, $match) === 1 ? $match[1] : null; + } + /** * @return list */ diff --git a/src/Input/Field.php b/src/Input/Field.php index 32cd6a912..755595e73 100644 --- a/src/Input/Field.php +++ b/src/Input/Field.php @@ -16,7 +16,6 @@ * @param array $examples * @param list $enumValues * @param list $constraints - * @param list, args: array}> $constraintSpecs * @param array $casterArguments * @param array|null $casterSchema * @param list $children @@ -28,19 +27,16 @@ public function __construct( public string $externalName, public Source $source, public string $typeName, - public bool $builtin, public bool $nullable, public bool $hasDefault, public mixed $default, public ?string $description, public array $examples, public ?string $listItem, - public bool $listItemBuiltin, public ?string $enumClass, public bool $enumInt, public array $enumValues, public array $constraints, - public array $constraintSpecs, public ?string $casterClass, public array $casterArguments, public ?array $casterSchema, @@ -55,273 +51,8 @@ public function required(): bool return !$this->nullable && !$this->hasDefault; } - public function itemField(): self - { - if (!$this->item instanceof self) { - throw new \LogicException(sprintf( - 'List property %s::$%s has no item type. Declare it with /** @param list $%s */ using list, list, list, list, list or a DTO.', - $this->dtoClass, - $this->property, - $this->property, - )); - } - - return $this->item; - } - public function readsBody(): bool { return $this->source === Source::Body || $this->source === Source::File; } - - /** - * @return array - */ - public function export(): array - { - return [ - 'property' => $this->property, - 'externalName' => $this->externalName, - 'source' => $this->source->value, - 'typeName' => $this->typeName, - 'builtin' => $this->builtin, - 'nullable' => $this->nullable, - 'hasDefault' => $this->hasDefault, - 'default' => ValueExport::export($this->default), - 'description' => $this->description, - 'examples' => ValueExport::export($this->examples), - 'listItem' => $this->listItem, - 'listItemBuiltin' => $this->listItemBuiltin, - 'enumClass' => $this->enumClass, - 'enumInt' => $this->enumInt, - 'enumValues' => $this->enumValues, - 'constraintSpecs' => ValueExport::export($this->constraintSpecs), - 'casterClass' => $this->casterClass, - 'casterArguments' => ValueExport::export($this->casterArguments), - 'casterSchema' => $this->casterSchema, - 'children' => array_map(static fn (self $child): array => $child->export(), $this->children), - 'item' => $this->item?->export(), - 'dtoClass' => $this->dtoClass, - ]; - } - - /** - * @param array $data - */ - public static function import(array $data): self - { - $constraints = self::importConstraints($data); - $children = []; - foreach (self::rows($data, 'children') as $child) { - $children[] = self::import(self::stringKeyed($child)); - } - $item = $data['item'] ?? null; - $enumClass = self::nullableString($data, 'enumClass'); - if ($enumClass !== null && !is_a($enumClass, \BackedEnum::class, true)) { - throw new \LogicException(sprintf("Compiled field metadata has enum '%s', which is not a backed enum. Rebuild the DI container.", $enumClass)); - } - $casterClass = self::nullableString($data, 'casterClass'); - if ($casterClass !== null && !is_a($casterClass, CasterInterface::class, true)) { - throw new \LogicException(sprintf("Compiled field metadata has caster '%s', which does not implement %s. Rebuild the DI container.", $casterClass, CasterInterface::class)); - } - - return new self( - self::string($data, 'property'), - self::string($data, 'externalName'), - Source::from(self::string($data, 'source')), - self::string($data, 'typeName'), - self::bool($data, 'builtin'), - self::bool($data, 'nullable'), - self::bool($data, 'hasDefault'), - ValueExport::import($data['default'] ?? null), - self::nullableString($data, 'description'), - self::stringMap(ValueExport::import($data['examples'] ?? [])), - self::nullableString($data, 'listItem'), - self::bool($data, 'listItemBuiltin'), - $enumClass, - self::bool($data, 'enumInt'), - self::enumValues($data), - $constraints['instances'], - $constraints['specs'], - $casterClass, - self::mixedList(ValueExport::import($data['casterArguments'] ?? [])), - self::optionalMap($data['casterSchema'] ?? null), - $children, - is_array($item) ? self::import(self::stringKeyed($item)) : null, - self::string($data, 'dtoClass'), - ); - } - - /** - * @param array $data - * @return array{instances: list, specs: list, args: array}>} - */ - private static function importConstraints(array $data): array - { - $imported = ValueExport::import($data['constraintSpecs'] ?? []); - if (!is_array($imported)) { - throw new \LogicException('Compiled field metadata is missing constraints. Rebuild the DI container.'); - } - $instances = []; - $specs = []; - foreach ($imported as $spec) { - if (!is_array($spec) || !is_string($spec['class'] ?? null) || !is_array($spec['args'] ?? null) || !is_a($spec['class'], ConstraintInterface::class, true)) { - throw new \LogicException('Compiled constraint metadata is invalid. Rebuild the DI container.'); - } - $class = $spec['class']; - $args = []; - foreach ($spec['args'] as $key => $argument) { - $args[$key] = $argument; - } - $instances[] = new $class(...$args); - $specs[] = ['class' => $class, 'args' => $args]; - } - - return ['instances' => $instances, 'specs' => $specs]; - } - - /** - * @param array $data - * @return list> - */ - private static function rows(array $data, string $key): array - { - $rows = $data[$key] ?? []; - if (!is_array($rows)) { - throw new \LogicException(sprintf('Compiled field metadata "%s" is not a list. Rebuild the DI container.', $key)); - } - $list = []; - foreach ($rows as $row) { - if (!is_array($row)) { - throw new \LogicException(sprintf('Compiled field metadata "%s" has an item that is not an array. Rebuild the DI container.', $key)); - } - $list[] = $row; - } - - return $list; - } - - /** - * @param array $data - * @return array - */ - private static function stringKeyed(array $data): array - { - $keyed = []; - foreach ($data as $key => $value) { - $keyed[$key] = $value; - } - - return $keyed; - } - - /** - * @param array $data - */ - private static function string(array $data, string $key): string - { - $value = $data[$key] ?? null; - if (!is_string($value) || $value === '') { - throw new \LogicException(sprintf('Compiled field metadata is missing "%s". Rebuild the DI container.', $key)); - } - - return $value; - } - - /** - * @param array $data - */ - private static function nullableString(array $data, string $key): ?string - { - $value = $data[$key] ?? null; - if ($value === null) { - return null; - } - if (!is_string($value)) { - throw new \LogicException(sprintf('Compiled field metadata "%s" must be a string or null. Rebuild the DI container.', $key)); - } - - return $value === '' ? null : $value; - } - - /** - * @param array $data - */ - private static function bool(array $data, string $key): bool - { - $value = $data[$key] ?? null; - if (!is_bool($value)) { - throw new \LogicException(sprintf('Compiled field metadata "%s" must be a boolean. Rebuild the DI container.', $key)); - } - - return $value; - } - - /** - * @param mixed $value - * @return array - */ - private static function stringMap(mixed $value): array - { - if (!is_array($value)) { - throw new \LogicException('Compiled field metadata examples must be an array. Rebuild the DI container.'); - } - $mapped = []; - foreach ($value as $key => $item) { - if (!is_string($key)) { - throw new \LogicException('Compiled field metadata examples must be named. Rebuild the DI container.'); - } - $mapped[$key] = $item; - } - - return $mapped; - } - - /** - * @param mixed $value - * @return array - */ - private static function mixedList(mixed $value): array - { - if (!is_array($value)) { - throw new \LogicException('Compiled field metadata arguments must be an array. Rebuild the DI container.'); - } - - return $value; - } - - /** - * @return array|null - */ - private static function optionalMap(mixed $value): ?array - { - if ($value === null) { - return null; - } - if (!is_array($value)) { - throw new \LogicException('Compiled field metadata schema must be an array. Rebuild the DI container.'); - } - return array_filter($value, is_string(...), ARRAY_FILTER_USE_KEY); - } - - /** - * @param array $data - * @return list - */ - private static function enumValues(array $data): array - { - $values = $data['enumValues'] ?? []; - if (!is_array($values)) { - throw new \LogicException('Compiled field metadata enum values must be a list. Rebuild the DI container.'); - } - $list = []; - foreach ($values as $value) { - if (!is_int($value) && !is_string($value)) { - throw new \LogicException('Compiled field metadata enum values must be strings or integers. Rebuild the DI container.'); - } - $list[] = $value; - } - - return $list; - } } diff --git a/src/Input/File.php b/src/Input/File.php index d61ad823a..39559e4c0 100644 --- a/src/Input/File.php +++ b/src/Input/File.php @@ -8,7 +8,7 @@ * Reads an uploaded file into a FileUpload (or a list of them). Multipart only. */ #[\Attribute(\Attribute::TARGET_PROPERTY)] -final readonly class File +final readonly class File implements SourceAttribute { /** * @param array $examples named examples, the same pairs as InputParam::addExample() @@ -19,4 +19,10 @@ public function __construct( public array $examples = [], ) { } + + #[\Override] + public function source(): Source + { + return Source::File; + } } diff --git a/src/Input/Header.php b/src/Input/Header.php index d96bc2c91..c773897c6 100644 --- a/src/Input/Header.php +++ b/src/Input/Header.php @@ -9,7 +9,7 @@ * #[Header('X-Request-Id')] reads that header, not a header named after the property. */ #[\Attribute(\Attribute::TARGET_PROPERTY)] -final readonly class Header +final readonly class Header implements SourceAttribute { /** * @param array $examples named examples, the same pairs as InputParam::addExample() @@ -20,4 +20,10 @@ public function __construct( public array $examples = [], ) { } + + #[\Override] + public function source(): Source + { + return Source::Header; + } } diff --git a/src/Input/Path.php b/src/Input/Path.php index a9cb9f8d2..2e8970d9c 100644 --- a/src/Input/Path.php +++ b/src/Input/Path.php @@ -9,7 +9,7 @@ * A path property is required: it cannot be nullable and cannot have a default. */ #[\Attribute(\Attribute::TARGET_PROPERTY)] -final readonly class Path +final readonly class Path implements SourceAttribute { /** * @param array $examples named examples, the same pairs as InputParam::addExample() @@ -20,4 +20,10 @@ public function __construct( public array $examples = [], ) { } + + #[\Override] + public function source(): Source + { + return Source::Path; + } } diff --git a/src/Input/Query.php b/src/Input/Query.php index 601910ee6..0a849fa41 100644 --- a/src/Input/Query.php +++ b/src/Input/Query.php @@ -8,7 +8,7 @@ * Reads a promoted DTO property from the query string. The external name defaults to the property name. */ #[\Attribute(\Attribute::TARGET_PROPERTY)] -final readonly class Query +final readonly class Query implements SourceAttribute { /** * @param array $examples named examples, the same pairs as InputParam::addExample() @@ -19,4 +19,10 @@ public function __construct( public array $examples = [], ) { } + + #[\Override] + public function source(): Source + { + return Source::Query; + } } diff --git a/src/Input/RequestInput.php b/src/Input/RequestInput.php index 232cb2db4..8f6d23671 100644 --- a/src/Input/RequestInput.php +++ b/src/Input/RequestInput.php @@ -65,8 +65,8 @@ public static function boot(string $handler, array $consumes, bool $bodyRequired return; } - self::$handler = $handler; - self::$query = self::stringMap($_GET); + self::$handler = null; + self::$query = $_GET; self::$body = []; self::$files = []; self::$failure = null; @@ -74,6 +74,8 @@ public static function boot(string $handler, array $consumes, bool $bodyRequired if ($readsBody) { self::loadBody($consumes, $bodyRequired); } + // only after the body was accepted: a 415 must not leave an empty body behind for the next read + self::$handler = $handler; } public static function failure(): ?string @@ -154,10 +156,7 @@ private static function file(string $name): mixed */ private static function loadBody(array $consumes, bool $bodyRequired): void { - $header = $_SERVER['CONTENT_TYPE'] ?? null; - if (!is_string($header)) { - $header = isset($_SERVER['HTTP_CONTENT_TYPE']) && is_string($_SERVER['HTTP_CONTENT_TYPE']) ? $_SERVER['HTTP_CONTENT_TYPE'] : null; - } + $header = HeaderBag::get('Content-Type'); $type = MediaTypes::normalize($header); if ($type === '') { // a body that arrives without a type is never read silently: it would be dropped without a word @@ -227,15 +226,16 @@ private static function loadJson(): void return; } - self::$body = self::objectProperties($decoded); + // nested objects stay stdClass and nested arrays stay lists, so {} and [] remain different when a field is mapped + self::$body = get_object_vars($decoded); } private static function loadForm(): void { $method = $_SERVER['REQUEST_METHOD'] ?? 'GET'; if ($method === 'POST' || $_POST !== [] || $_FILES !== []) { - self::$body = self::stringMap($_POST); - self::$files = self::stringMap($_FILES); + self::$body = $_POST; + self::$files = $_FILES; // PHP drops the variables over max_input_vars without a word, so a form that was cut is found by parsing its body again if (self::$mediaType === MediaTypes::FORM && count($_POST, COUNT_RECURSIVE) >= self::maxInputVars()) { $raw = self::rawBody(); @@ -259,8 +259,8 @@ private static function loadForm(): void $parsed = []; } } - self::$body = self::stringMap($parsed); - self::$files = self::stringMap($_FILES); + self::$body = $parsed; + self::$files = $_FILES; } private static function maxInputVars(): int @@ -286,36 +286,6 @@ private static function parseForm(string $raw): ?array return $exceeded ? null : $parsed; } - /** - * Top-level properties of a JSON object. Nested objects stay stdClass and nested arrays stay lists, - * so {} and [] remain different when a field is mapped. - * - * @return array - */ - private static function objectProperties(\stdClass $object): array - { - $mapped = []; - foreach (get_object_vars($object) as $key => $value) { - $mapped[$key] = $value; - } - - return $mapped; - } - - /** - * @param array $values - * @return array - */ - private static function stringMap(array $values): array - { - $mapped = []; - foreach ($values as $key => $value) { - $mapped[$key] = $value; - } - - return $mapped; - } - public static function rawContents(): string|false { return self::rawBody(); diff --git a/src/Input/ScalarCoercer.php b/src/Input/ScalarCoercer.php index b3b06a240..bfffbe728 100644 --- a/src/Input/ScalarCoercer.php +++ b/src/Input/ScalarCoercer.php @@ -99,7 +99,8 @@ public static function toDateTime(mixed $value): \DateTimeImmutable $match[1] = strtoupper($match[1]); $fraction = $match[2]; - $offset = strtoupper($match[3]) === 'Z' ? '+00:00' : $match[3]; + // RFC 3339 writes UTC as Z, +00:00 or -00:00 (UTC with an unknown local offset); PHP formats all of them as +00:00 + $offset = in_array(strtoupper($match[3]), ['Z', '-00:00'], true) ? '+00:00' : $match[3]; if ($fraction === '') { $formatted = sprintf('%s%s', $match[1], $offset); $format = 'Y-m-d\TH:i:sP'; diff --git a/src/Input/SchemaBuilder.php b/src/Input/SchemaBuilder.php index 159a5b5d6..c948fd8fb 100644 --- a/src/Input/SchemaBuilder.php +++ b/src/Input/SchemaBuilder.php @@ -44,6 +44,8 @@ public static function build(Field $field, bool $nullOnWire): array $schema = ['type' => self::scalarType($field->typeName)]; } + // constraints are checked on the result of a caster (DtoMapper validates the cast value), not on what the client sends, + // so for a property with a caster they say nothing about the wire value this schema describes if ($field->casterSchema === null) { foreach ($field->constraints as $constraint) { if ($constraint instanceof Range) { diff --git a/src/Input/SourceAttribute.php b/src/Input/SourceAttribute.php new file mode 100644 index 000000000..bdcb0a257 --- /dev/null +++ b/src/Input/SourceAttribute.php @@ -0,0 +1,20 @@ + */ + public array $examples { get; } + + public function source(): Source; +} diff --git a/src/Input/ValueExport.php b/src/Input/ValueExport.php deleted file mode 100644 index 7919e7f5a..000000000 --- a/src/Input/ValueExport.php +++ /dev/null @@ -1,58 +0,0 @@ - 'enum', 'class' => $value::class, 'value' => $value->value]; - } - if (!is_array($value)) { - if (is_object($value)) { - throw new \LogicException(sprintf( - 'A %s cannot be stored in the compiled container. Use null, a scalar, an array or a backed enum as a DTO default.', - $value::class, - )); - } - - return $value; - } - - $exported = []; - foreach ($value as $key => $item) { - $exported[$key] = self::export($item); - } - - return $exported; - } - - public static function import(mixed $value): mixed - { - if (!is_array($value)) { - return $value; - } - if (($value['__netteApi'] ?? null) === 'enum' && is_string($value['class'] ?? null) && (is_int($value['value'] ?? null) || is_string($value['value'] ?? null))) { - $enum = $value['class']; - $case = $enum::tryFrom($value['value']); - if (!$case instanceof \BackedEnum) { - throw new \LogicException(sprintf("Cannot restore the default of backed enum %s from '%s'.", $enum, (string) $value['value'])); - } - - return $case; - } - - $imported = []; - foreach ($value as $key => $item) { - $imported[$key] = self::import($item); - } - - return $imported; - } -} diff --git a/src/Link/ApiLink.php b/src/Link/ApiLink.php index 22e8ff49c..a98fcdfac 100644 --- a/src/Link/ApiLink.php +++ b/src/Link/ApiLink.php @@ -20,7 +20,8 @@ public function __construct(private readonly LinkGenerator $linkGenerator) /** * Create link to specified api endpoint * - * A {name} segment of a URL template stays literal, which is the OpenAPI path template. + * A {name} segment of a URL template is filled from $params[name] (URL-encoded). Without a value it stays + * literal, which is the OpenAPI path template. * * @param array $params * @throws InvalidLinkException @@ -63,7 +64,16 @@ private function templateLink(EndpointInterface $endpoint, array $params): strin )); } - $url = substr($sample, 0, $position) . '/' . $endpoint->getUrl(); + $path = preg_replace_callback('/\{([A-Za-z_][A-Za-z0-9_]*)\}/', static function (array $match) use (&$params): string { + if (!isset($params[$match[1]]) || !is_scalar($params[$match[1]])) { + return $match[0]; + } + $value = rawurlencode((string) $params[$match[1]]); + unset($params[$match[1]]); + + return $value; + }, rtrim($endpoint->getUrl(), '/')); + $url = substr($sample, 0, $position) . '/' . $path; unset($params['version'], $params['package'], $params['apiAction']); if ($params !== []) { $url = sprintf('%s?%s', $url, http_build_query($params)); diff --git a/src/OpenApi/RequestBodyBuilder.php b/src/OpenApi/RequestBodyBuilder.php index d32bff4ef..38d820bb7 100644 --- a/src/OpenApi/RequestBodyBuilder.php +++ b/src/OpenApi/RequestBodyBuilder.php @@ -5,9 +5,11 @@ namespace Tomaj\NetteApi\OpenApi; use Tomaj\NetteApi\Handlers\ApiHandlerInterface; +use Tomaj\NetteApi\Input\MediaTypes; use Tomaj\NetteApi\Misc\TypeHelper; use Tomaj\NetteApi\Params\InputParam; use Tomaj\NetteApi\Params\JsonInputParam; +use Tomaj\NetteApi\Params\ParamInterface; use Tomaj\NetteApi\Params\RawInputParam; /** @@ -31,11 +33,12 @@ public function build(ApiHandlerInterface $handler, SchemaRegistry $schemaRegist $typedProperties = []; $typedRequired = []; $typedTypes = []; - $typedAnyRequired = false; $typedFiles = []; foreach ($handler->params() as $param) { - if ($param instanceof InputParam && $param->getOpenApiSchema() !== null && ($param->getType() === InputParam::TYPE_BODY || $param->getType() === InputParam::TYPE_FILE)) { - $schema = $param->getOpenApiSchema(); + // a body param declared in params() without a schema is documented like a POST param: a string (or a list of them) + $isBody = $param->getType() === InputParam::TYPE_BODY; + if ($param instanceof InputParam && ($isBody || ($param->getType() === InputParam::TYPE_FILE && $param->getOpenApiSchema() !== null))) { + $schema = $param->getOpenApiSchema() ?? $this->formProperty($param); if ($param->getDescription() !== '' && !isset($schema['description'])) { $schema['description'] = $param->getDescription(); } @@ -45,7 +48,6 @@ public function build(ApiHandlerInterface $handler, SchemaRegistry $schemaRegist } if ($param->isRequired()) { $typedRequired[] = $param->getKey(); - $typedAnyRequired = true; } if ($param->getContentTypes() !== []) { $typedTypes = $param->getContentTypes(); @@ -93,31 +95,7 @@ public function build(ApiHandlerInterface $handler, SchemaRegistry $schemaRegist } if ($param->getType() === InputParam::TYPE_POST || $param->getType() === InputParam::TYPE_PUT) { - $property = [ - 'type' => $param->isMulti() ? 'array' : 'string', - ]; - if ($param->isMulti()) { - $property['items'] = ['type' => 'string']; - } - - $descriptionParts = []; - if ($param->getDescription()) { - $descriptionParts[] = $param->getDescription(); - } - - $availableValues = $param->getAvailableValues(); - if ($availableValues) { - $property['enum'] = array_keys($availableValues); - if (array_keys($availableValues) !== array_values($availableValues)) { - foreach ($availableValues as $availableKey => $availableValue) { - $descriptionParts[] = ' * `' . $availableKey . '` - ' . TypeHelper::toString($availableValue); - } - } - } - - if ($descriptionParts !== []) { - $property['description'] = implode("\n", $descriptionParts); - } + $property = $this->formProperty($param); $requestBody['properties'][$param->getKey() . ($param->isMulti() ? '[]' : '')] = $property; if ($param->isRequired()) { @@ -169,33 +147,200 @@ public function build(ApiHandlerInterface $handler, SchemaRegistry $schemaRegist } if ($typedProperties !== []) { - $typedSchema = [ - 'type' => 'object', - 'properties' => $typedProperties, - ]; - if ($typedRequired !== []) { - $typedSchema['required'] = $typedRequired; - } - // files can only be sent as multipart/form-data, so the other media types do not list them - $withoutFiles = ['type' => 'object']; - $propertiesWithoutFiles = array_diff_key($typedProperties, array_flip($typedFiles)); - if ($propertiesWithoutFiles !== []) { - $withoutFiles['properties'] = $propertiesWithoutFiles; + $result['required'] = ($result['required'] ?? false) === true || $typedRequired !== []; + // a required file cannot be sent as JSON, so such a request could only be answered with 400: only multipart is advertised + if (array_intersect($typedRequired, $typedFiles) !== []) { + $advertised = [MediaTypes::MULTIPART]; + } elseif ($typedTypes !== []) { + $advertised = $typedTypes; + } else { + $advertised = [MediaTypes::JSON, $typedFiles === [] && !$filesInBody ? MediaTypes::FORM : MediaTypes::MULTIPART]; } - // the other media types are advertised only when no file is required, so `typedRequired` has none - if ($typedRequired !== []) { - $withoutFiles['required'] = $typedRequired; + // OpenAPI 3.0 cannot describe a list of objects (or deeper nesting) in a form body, so such a body is documented + // as JSON only, unless no other media type is left + if (!$this->formDescribable($typedProperties)) { + $describable = array_values(array_diff($advertised, [MediaTypes::FORM, MediaTypes::MULTIPART])); + $advertised = $describable !== [] ? $describable : $advertised; } - $result['required'] = $typedAnyRequired; - // a required file cannot be sent as JSON, so such a request could only be answered with 400: only multipart is advertised - $advertised = array_intersect($typedRequired, $typedFiles) !== [] - ? ['multipart/form-data'] - : ($typedTypes === [] ? ['application/json', 'application/x-www-form-urlencoded'] : $typedTypes); foreach ($advertised as $contentType) { - $result['content'][$contentType] = ['schema' => $contentType === 'multipart/form-data' ? $typedSchema : $withoutFiles]; + // files can only be sent as multipart/form-data, so the other media types do not list them + $properties = $contentType === MediaTypes::MULTIPART ? $typedProperties : array_diff_key($typedProperties, array_flip($typedFiles)); + if ($contentType !== MediaTypes::FORM && $contentType !== MediaTypes::MULTIPART) { + $result['content'][$contentType] = ['schema' => $this->objectSchema($properties, $typedRequired)]; + continue; + } + $mediaType = $this->formMediaType($properties, $typedRequired); + // POST, PUT and file params without a schema already described this form: one body carries them all + $legacy = TypeHelper::toArray($result['content'][$contentType]['schema'] ?? null); + if ($legacy !== []) { + $mediaType['schema'] = $this->mergeObjects($legacy, $mediaType['schema']); + } + $result['content'][$contentType] = $mediaType; } } return $result ?: null; } + + /** + * @return array + */ + private function formProperty(ParamInterface $param): array + { + $property = [ + 'type' => $param->isMulti() ? 'array' : 'string', + ]; + if ($param->isMulti()) { + $property['items'] = ['type' => 'string']; + } + + $descriptionParts = []; + if ($param->getDescription()) { + $descriptionParts[] = $param->getDescription(); + } + + $availableValues = $param->getAvailableValues(); + if ($availableValues) { + $property['enum'] = array_keys($availableValues); + if (array_keys($availableValues) !== array_values($availableValues)) { + foreach ($availableValues as $availableKey => $availableValue) { + $descriptionParts[] = ' * `' . $availableKey . '` - ' . TypeHelper::toString($availableValue); + } + } + } + + if ($descriptionParts !== []) { + $property['description'] = implode("\n", $descriptionParts); + } + + return $property; + } + + /** + * @param array> $properties + * @param list $required + * @return array + */ + private function objectSchema(array $properties, array $required): array + { + $schema = ['type' => 'object']; + if ($properties !== []) { + $schema['properties'] = $properties; + } + // only properties that are listed can be required (a file is never listed outside multipart, and then it is not required) + $required = array_values(array_intersect($required, array_keys($properties))); + if ($required !== []) { + $schema['required'] = $required; + } + + return $schema; + } + + /** + * @param array $first + * @param array $second + * @return array + */ + private function mergeObjects(array $first, array $second): array + { + $merged = $first; + $merged['properties'] = TypeHelper::toArray($first['properties'] ?? null) + TypeHelper::toArray($second['properties'] ?? null); + $required = array_values(array_unique([...TypeHelper::toStringList($first['required'] ?? null), ...TypeHelper::toStringList($second['required'] ?? null)])); + if ($required !== []) { + $merged['required'] = $required; + } + + return $merged; + } + + /** + * The form wire shape PHP parses: a list is sent as `tags[]=a&tags[]=b`, so it is named `tags[]` (as POST params are), + * an object as `address[street]=...`, which is the deepObject style. Null cannot be sent in a form, so nothing is nullable. + * + * @param array> $properties + * @param list $required + * @return array{schema: array, encoding?: array} + */ + private function formMediaType(array $properties, array $required): array + { + $formProperties = []; + $formRequired = []; + $encoding = []; + foreach ($properties as $name => $schema) { + $schema = self::withoutNull($schema); + $type = $schema['type'] ?? null; + $formName = $type === 'array' ? $name . '[]' : $name; + $formProperties[$formName] = $schema; + if (in_array($name, $required, true)) { + $formRequired[] = $formName; + } + if ($type === 'object') { + $encoding[$formName] = ['style' => 'deepObject', 'explode' => true]; + } + } + + $mediaType = ['schema' => $this->objectSchema($formProperties, $formRequired)]; + if ($encoding !== []) { + $mediaType['encoding'] = $encoding; + } + + return $mediaType; + } + + /** + * A form can carry a scalar, a list of scalars (`tags[]`) and an object of scalars (deepObject); OpenAPI 3.0 defines no + * serialization for anything nested deeper. + * + * @param array> $properties + */ + private function formDescribable(array $properties): bool + { + foreach ($properties as $schema) { + $type = $schema['type'] ?? null; + if ($type === 'array' && self::isComposite(TypeHelper::toArray($schema['items'] ?? null))) { + return false; + } + if ($type === 'object') { + foreach (TypeHelper::toArray($schema['properties'] ?? null) as $child) { + if (self::isComposite(TypeHelper::toArray($child))) { + return false; + } + } + } + } + + return true; + } + + /** + * @param array $schema + */ + private static function isComposite(array $schema): bool + { + return in_array($schema['type'] ?? null, ['array', 'object'], true); + } + + /** + * @param array $schema + * @return array + */ + private static function withoutNull(array $schema): array + { + if (($schema['nullable'] ?? false) === true) { + unset($schema['nullable']); + if (isset($schema['enum']) && is_array($schema['enum'])) { + $schema['enum'] = array_values(array_filter($schema['enum'], static fn (mixed $value): bool => $value !== null)); + } + } + if (isset($schema['properties']) && is_array($schema['properties'])) { + foreach ($schema['properties'] as $name => $child) { + $schema['properties'][$name] = is_array($child) ? self::withoutNull($child) : $child; + } + } + if (isset($schema['items']) && is_array($schema['items'])) { + $schema['items'] = self::withoutNull($schema['items']); + } + + return $schema; + } } diff --git a/src/Params/BodyInputParam.php b/src/Params/BodyInputParam.php index c03442ff2..ddc4433c0 100644 --- a/src/Params/BodyInputParam.php +++ b/src/Params/BodyInputParam.php @@ -18,34 +18,34 @@ class BodyInputParam extends InputParam #[\Override] public function getValue(): mixed { - $value = $_POST[$this->getKey()] ?? null; - if ($value === null && MediaTypes::normalize(is_string($_SERVER['CONTENT_TYPE'] ?? null) ? $_SERVER['CONTENT_TYPE'] : null) === MediaTypes::JSON) { - $decoded = self::json(); - if (is_array($decoded)) { - $value = $decoded[$this->getKey()] ?? null; - } - } - $value ??= $this->default; + $value = self::body()[$this->getKey()] ?? $this->default; return new InputValidator()->transformType($value, $this->valueType, $this->isRequired()); } /** - * @return array|null + * @return array */ - private static function json(): ?array + private static function body(): array { - $raw = RequestInput::rawContents(); - $raw = is_string($raw) ? $raw : ''; - $decoded = json_decode($raw); - if (json_last_error() !== JSON_ERROR_NONE || !$decoded instanceof \stdClass) { - return null; + $type = MediaTypes::normalize(HeaderBag::get('Content-Type')); + if ($type === MediaTypes::JSON) { + $raw = RequestInput::rawContents(); + $decoded = json_decode(is_string($raw) ? $raw : ''); + + return $decoded instanceof \stdClass ? get_object_vars($decoded) : []; } - $body = []; - foreach (get_object_vars($decoded) as $key => $value) { - $body[$key] = $value; + if ($_POST !== [] || ($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') { + return $_POST; + } + if ($type === MediaTypes::FORM) { + // PHP fills $_POST only for POST, a PUT or PATCH form is parsed here + $raw = RequestInput::rawContents(); + parse_str(is_string($raw) ? $raw : '', $parsed); + + return $parsed; } - return $body; + return []; } } diff --git a/src/Params/MappedInputParam.php b/src/Params/MappedInputParam.php index 27d2a9736..98a1221b3 100644 --- a/src/Params/MappedInputParam.php +++ b/src/Params/MappedInputParam.php @@ -45,8 +45,10 @@ public function __construct( if (SchemaBuilder::documentsDefault($field)) { $this->setDefault(SchemaBuilder::wire($field->default)); } - if ($field->enumValues !== []) { - $this->setAvailableValues($field->enumValues); + // a list offers the values of its items + $enumValues = $field->item->enumValues ?? $field->enumValues; + if ($enumValues !== []) { + $this->setAvailableValues($enumValues); } // a caster reads the whole wire value (for example Split reads "a,b"), so it is one input, not a list of inputs if ($field->listItem !== null && $field->casterClass === null) { diff --git a/src/Validation/Pattern.php b/src/Validation/Pattern.php index 7d69e5884..cda6a09ad 100644 --- a/src/Validation/Pattern.php +++ b/src/Validation/Pattern.php @@ -51,13 +51,22 @@ public function expression(): ?string return preg_match(self::portable(str_contains($flags, 'u')), $expression) === 1 ? $expression : null; } + /** + * A PCRE pattern matching the portable subset described at expression(). (?) recurses for groups and lookaheads. + */ private static function portable(bool $unicode): string { + // characters that are escaped in the expression to stand for themselves $punctuation = '\\\\^$.*+?()\[\]{}|\/'; + // a printable ASCII character that has no special meaning $literal = '[^\\\\.\[\](){}*+?|^$\x00-\x1F\x7F-\xFF]'; + // an escaped punctuation character, \n \r \t, and \d \w only where they are ASCII in PCRE $escape = '\\\\[' . $punctuation . 'nrt' . ($unicode ? '' : 'dw') . ']'; + // a positive character class of literals, escapes and ranges (the `-` is literal or a range in both dialects) $class = '\[(?!\^)(?:[^\\\\\[\]\x00-\x1F\x7F-\xFF]|\\\\[' . $punctuation . '\-nrt])+\]'; + // a literal, escape, class or (non-capturing) group with an optional greedy or lazy quantifier $atom = '(?:' . $literal . '|' . $escape . '|' . $class . '|\((?:\?:)?(?&alt)\))(?:[*+?]|\{\d+(?:,\d*)?\})?\??'; + // anchors, lookahead and \b only where it is ASCII in PCRE $assertion = '\^|\$|\((?:\?[=!])(?&alt)\)' . ($unicode ? '' : '|\\\\b'); return '/\A(?(?(?:' . $atom . '|' . $assertion . ')*)(?:\|(?&seq))*)\z/'; diff --git a/src/Validation/Range.php b/src/Validation/Range.php index 4db13591b..b08e3c930 100644 --- a/src/Validation/Range.php +++ b/src/Validation/Range.php @@ -14,6 +14,12 @@ public function __construct( public int|float|null $min = null, public int|float|null $max = null, ) { + foreach (['min' => $this->min, 'max' => $this->max] as $name => $bound) { + // INF cannot be written to the OpenAPI document (json_encode fails) and every comparison with NAN is false + if (is_float($bound) && !is_finite($bound)) { + throw new \LogicException(sprintf('Range %s must be a finite number, %s given. Omit the bound instead.', $name, $this->number($bound))); + } + } if ($this->min === null && $this->max === null) { throw new \InvalidArgumentException('Range needs min, max or both, for example #[Range(min: 1, max: 100)].'); } diff --git a/tests/ApiDeciderTest.php b/tests/ApiDeciderTest.php index 0fe9a5a19..182f31384 100644 --- a/tests/ApiDeciderTest.php +++ b/tests/ApiDeciderTest.php @@ -34,6 +34,32 @@ public function testDefaultHandlerWithNoRegisteredHandlers(): void $this->assertInstanceOf(DefaultHandler::class, $result->getHandler()); } + public function testAPlainHandlerOnAStaticUrlIsNotAskedForItsParams(): void + { + $handler = new class extends AlwaysOkHandler { + public int $calls = 0; + + public function params(): array + { + $this->calls++; + return parent::params(); + } + }; + $apiDecider = new ApiDecider($this->container); + $apiDecider->addApi(new EndpointIdentifier('GET', 1, 'users', 'list'), $handler, new NoAuthorization()); + + $this->assertSame($handler, $apiDecider->getApi('GET', '1', 'users', 'list')->getHandler()); + $this->assertSame(0, $handler->calls, 'the presenter reads params() once, the lookup must not add a call'); + } + + public function testALiteralPlaceholderInTheRequestDoesNotMatchATemplate(): void + { + $apiDecider = new ApiDecider($this->container); + $apiDecider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id}'), new AlwaysOkHandler(), new NoAuthorization()); + + $this->assertInstanceOf(DefaultHandler::class, $apiDecider->getApi('GET', '1', 'users', '{id}')->getHandler()); + } + public function testFindRightHandler(): void { $apiDecider = new ApiDecider($this->container); diff --git a/tests/DI/TypedInputExtensionTest.php b/tests/DI/TypedInputExtensionTest.php index 5719c0bd5..980d04df5 100644 --- a/tests/DI/TypedInputExtensionTest.php +++ b/tests/DI/TypedInputExtensionTest.php @@ -4,14 +4,35 @@ namespace Tomaj\NetteApi\Test\DI; +use Nette\DI\Container; use Tomaj\NetteApi\Params\ParamsProcessor; use PHPUnit\Framework\TestCase; use Tomaj\NetteApi\ApiDecider; use Tomaj\NetteApi\Input\RequestInput; +use Tomaj\NetteApi\Handlers\TypedHandler; +use Tomaj\NetteApi\Input\Body; +use Tomaj\NetteApi\Input\DtoCompiler; +use Tomaj\NetteApi\Input\DtoMetadataRegistry; +use Tomaj\NetteApi\Response\JsonApiResponse; +use Tomaj\NetteApi\Response\ResponseInterface; use Tomaj\NetteApi\Test\Input\Fixtures\ListUsersHandler; +use Tomaj\NetteApi\Test\Input\Fixtures\ScheduleHandler; +use Tomaj\NetteApi\Validation\ConstraintContext; +use Tomaj\NetteApi\Validation\ConstraintInterface; +use Nette\DI\Compiler; +use Tomaj\NetteApi\DI\NetteApiExtension; +use Tomaj\NetteApi\Handlers\AlwaysOkHandler; +use Tomaj\NetteApi\Input\Path; +use Tomaj\NetteApi\Test\Input\Fixtures\CreateOrderHandler; +use Tomaj\NetteApi\Test\Input\Fixtures\Separate\NoteHandler; final class TypedInputExtensionTest extends TestCase { + protected function setUp(): void + { + DtoMetadataRegistry::reset(); + } + public function testDiscoveryCompilesTypedHandlers(): void { $dir = dirname(__DIR__) . '/Input/Fixtures'; @@ -59,4 +80,198 @@ public function testPathPlaceholderMustMatchTheDto(): void - {method: GET, version: 1, package: users, action: detail, handler: Tomaj\NetteApi\Test\Input\Fixtures\UserDetailHandler} NEON); } + + public function testContainerInstallsSerializedMetadataAndUnpacksItOnFirstUse(): void + { + DtoMetadataRegistry::reset(); + $code = ContainerFactory::compile(<<<'NEON' +api: + endpoints: + - {method: GET, version: 1, package: people, handler: Tomaj\NetteApi\Test\Input\Fixtures\ListUsersHandler} + - {method: POST, version: 1, package: schedule, handler: Tomaj\NetteApi\Test\Input\Fixtures\ScheduleHandler} +NEON); + $this->assertStringContainsString('DtoMetadataRegistry::install(', $code); + $this->assertStringNotContainsString('Handlers.php', $code, 'compile-time file paths are not part of the runtime payload'); + + preg_match('~class (ApiTestContainer\w+)~', $code, $match); + eval($code); + $container = new $match[1](); + $this->assertInstanceOf(Container::class, $container); + $container->initialize(); + $this->assertTrue(DtoMetadataRegistry::installs(ScheduleHandler::class)); + $unpacked = new \ReflectionProperty(DtoMetadataRegistry::class, 'metadata'); + $this->assertSame([], $unpacked->getValue(), 'nothing is unserialized until a handler is used'); + + // ScheduleHandler has a constraint with a private property, which serialize() writes with NUL bytes + $this->assertEquals(DtoCompiler::compile(ScheduleHandler::class), DtoMetadataRegistry::forHandler(ScheduleHandler::class)); + $this->assertSame([ScheduleHandler::class], array_keys((array) $unpacked->getValue())); + DtoMetadataRegistry::reset(); + } + + public function testAConstraintThatCannotBeSerializedFailsContainerCompilation(): void + { + $this->expectException(\LogicException::class); + $this->expectExceptionMessage(sprintf("The typed input of %s cannot be stored in the compiled container: Serialization of 'Closure' is not allowed.", ClosureConstraintHandler::class)); + ContainerFactory::compile(<<<'NEON' +api: + endpoints: + - {method: POST, version: 1, package: closure, handler: Tomaj\NetteApi\Test\DI\ClosureConstraintHandler} +NEON); + } + + public function testExtensionInstallsTypedHandlersAndTheirFiles(): void + { + $container = ContainerFactory::create(<<<'NEON' +services: + listUsers: Tomaj\NetteApi\Test\Input\Fixtures\ListUsersHandler +api: + endpoints: + - {method: GET, version: 1, package: people, handler: @listUsers} + - {method: POST, version: 1, package: orders, handler: Tomaj\NetteApi\Test\Input\Fixtures\CreateOrderHandler()} +NEON); + $container->initialize(); + $this->assertTrue(DtoMetadataRegistry::installed()); + $this->assertTrue(DtoMetadataRegistry::installs(ListUsersHandler::class)); + $this->assertTrue(DtoMetadataRegistry::installs(CreateOrderHandler::class)); + $urls = []; + foreach ($container->getByType(ApiDecider::class)->getApis() as $api) { + $urls[] = $api->getEndpoint()->getUrl(); + } + $this->assertContains('v1/people/', $urls); + $this->assertContains('v1/orders/', $urls); + + DtoMetadataRegistry::reset(); + $empty = ContainerFactory::create("api:\n endpoints: []\n"); + $empty->initialize(); + $this->assertFalse(DtoMetadataRegistry::installed()); + + $compiler = new Compiler(); + $compiler->addExtension('api', new NetteApiExtension()); + $compiler->addConfig([ + 'api' => [ + 'endpoints' => [[ + 'method' => 'POST', + 'version' => 1, + 'package' => 'orders', + 'handler' => CreateOrderHandler::class, + ]], + ], + ]); + $compiler->compile(); + $this->assertStringContainsString('Handlers.php', serialize($compiler->exportDependencies())); + } + + public function testBackslashHandlerIsInstalledUnderItsRealName(): void + { + $container = ContainerFactory::create(<<<'NEON' +api: + endpoints: + - {method: GET, version: 1, package: people, action: list, handler: \Tomaj\NetteApi\Test\Input\Fixtures\ListUsersHandler} +NEON); + $container->initialize(); + $this->assertTrue(DtoMetadataRegistry::installs(ListUsersHandler::class)); + } + + public function testContainerKeepsTypedHandlersAfterAPlainOneAndRejectsOverlap(): void + { + $container = ContainerFactory::create(<<<'NEON' +services: + listUsers: Tomaj\NetteApi\Test\Input\Fixtures\ListUsersHandler +api: + endpoints: + - {method: GET, version: 1, package: ping, handler: Tomaj\NetteApi\Handlers\AlwaysOkHandler} + - {method: GET, version: 1, package: people, action: list, handler: @listUsers} + - {method: POST, version: 1, package: notes, handler: \Tomaj\NetteApi\Test\Input\Fixtures\Separate\NoteHandler()} +NEON); + $container->initialize(); + $this->assertTrue(DtoMetadataRegistry::installs(ListUsersHandler::class)); + $this->assertTrue(DtoMetadataRegistry::installs(NoteHandler::class)); + $this->assertInstanceOf(AlwaysOkHandler::class, $container->getByType(AlwaysOkHandler::class)); + + $compiler = new Compiler(); + $compiler->addExtension('api', new NetteApiExtension()); + $compiler->addConfig([ + 'api' => [ + 'endpoints' => [[ + 'method' => 'POST', + 'version' => 1, + 'package' => 'notes', + 'handler' => NoteHandler::class, + ]], + ], + ]); + $compiler->compile(); + $this->assertStringContainsString('NoteInput.php', serialize($compiler->exportDependencies())); + + $this->expectException(\LogicException::class); + $this->expectExceptionMessage('can match the same request'); + ContainerFactory::create(<<<'NEON' +api: + endpoints: + - {method: GET, version: 1, package: users, action: '{id}', handler: Tomaj\NetteApi\Test\DI\IdOnlyHandler} + - {method: GET, version: 1, package: users, action: '{slug}', handler: Tomaj\NetteApi\Test\DI\SlugOnlyHandler} +NEON); + } +} + +#[\Attribute(\Attribute::TARGET_PROPERTY)] +final readonly class ClosureConstraint implements ConstraintInterface +{ + private \Closure $check; + + public function __construct() + { + $this->check = static fn (mixed $value): bool => $value !== ''; + } + + #[\Override] + public function validate(mixed $value, ConstraintContext $context): ?string + { + return ($this->check)($value) ? null : 'Value must not be empty'; + } +} + +final readonly class ClosureConstraintInput +{ + public function __construct(#[Body] #[ClosureConstraint] public string $name) + { + } +} + +final class ClosureConstraintHandler extends TypedHandler +{ + public function handleDto(ClosureConstraintInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class IdOnlyInput +{ + public function __construct(#[Path] public string $id) + { + } +} + +final class IdOnlyHandler extends TypedHandler +{ + public function handleDto(IdOnlyInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class SlugOnlyInput +{ + public function __construct(#[Path] public string $slug) + { + } +} + +final class SlugOnlyHandler extends TypedHandler +{ + public function handleDto(SlugOnlyInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } } diff --git a/tests/Input/BehaviorPinTest.php b/tests/Input/BehaviorPinTest.php deleted file mode 100644 index 1c245bb46..000000000 --- a/tests/Input/BehaviorPinTest.php +++ /dev/null @@ -1,827 +0,0 @@ -export(); - $files = $export['files']; - unset($export['files']); - $expected = json_decode((string) file_get_contents(__DIR__ . '/Fixtures/create-order-export.json'), true); - $this->assertSame($expected, $export); - $this->assertTrue(array_is_list($files)); - $this->assertContains(realpath(__DIR__ . '/Fixtures/Handlers.php') ?: '', array_map(realpath(...), $files)); - } - - public function testImportedMetadataRoundTrips(): void - { - $compiled = DtoCompiler::compile(CreateOrderHandler::class); - $export = $compiled->export(); - $export['contentTypes'][] = 5; - $export['files'] = [2 => '/tmp/a.php', 4 => '/tmp/b.php']; - $imported = DtoMetadata::import($export); - $this->assertSame($compiled->handler, $imported->handler); - $this->assertSame($compiled->class, $imported->class); - $this->assertSame($compiled->contentTypes, $imported->contentTypes); - $this->assertTrue(array_is_list($imported->files)); - $this->assertSame(['/tmp/a.php', '/tmp/b.php'], $imported->files); - $again = $imported->export(); - unset($export['files'], $again['files'], $export['contentTypes'], $again['contentTypes']); - $this->assertEquals($export, $again); - - $examples = DtoCompiler::compile(TwoExamplesHandler::class); - $restored = DtoMetadata::import($examples->export()); - $this->assertSame(['one' => 1, 'two' => 2], $restored->fields[0]->examples); - $this->assertSame([1, 2], DtoCompiler::compile(ListUsersHandler::class)->fields[3]->enumValues); - $priority = DtoMetadata::import(DtoCompiler::compile(ListUsersHandler::class)->export()); - $this->assertSame([1, 2], $priority->fields[3]->enumValues); - } - - public function testQueryOnlyHandlerDoesNotReadABody(): void - { - $metadata = DtoCompiler::compile(ListUsersHandler::class); - $this->assertFalse($metadata->readsBody); - $this->assertFalse($metadata->bodyRequired); - $this->assertNull($metadata->firstBody); - $this->assertFalse($metadata->fields[0]->listItemBuiltin); - $this->assertFalse($metadata->fields[0]->enumInt); - $this->assertTrue($metadata->fields[3]->enumInt); - $this->assertSame([1, 2], $metadata->fields[3]->enumValues); - } - - public function testSameInstanceIsReusedUntilReset(): void - { - $first = DtoMetadataRegistry::forHandler(ListUsersHandler::class); - $again = DtoMetadataRegistry::forHandler(ListUsersHandler::class); - $this->assertSame($first, $again); - - $export = $first->export(); - $export['firstBody'] = 'from-install'; - DtoMetadataRegistry::reset(); - DtoMetadataRegistry::install([ListUsersHandler::class => $export]); - $this->assertTrue(DtoMetadataRegistry::installs(ListUsersHandler::class)); - $this->assertSame('from-install', DtoMetadataRegistry::forHandler(ListUsersHandler::class)->firstBody); - $this->assertFalse(DtoMetadataRegistry::installs(CreateOrderHandler::class)); - $this->assertSame(CreateOrderHandler::class, DtoMetadataRegistry::forHandler(CreateOrderHandler::class)->handler); - } - - public function testMissingHandlerNamesTheClass(): void - { - $this->expectException(\LogicException::class); - $this->expectExceptionMessage("Typed handler 'Missing\\Handler' does not exist. Check the class name and the autoload section of composer.json."); - DtoCompiler::compile('Missing\\Handler'); - } - - public function testCycleNamesEveryStep(): void - { - try { - DtoCompiler::compile(CyclePinHandler::class); - $this->fail('cycle'); - } catch (\LogicException $exception) { - $this->assertSame( - sprintf( - 'DTO %s refers to itself (%s -> %s). Nested DTOs cannot form a cycle; keep the nesting one way.', - CyclePinInput::class, - CyclePinInput::class, - CyclePinInput::class, - ), - $exception->getMessage(), - ); - } - } - - public function testDeclarationsThatCannotBeMapped(): void - { - $cases = [ - PrivateHandler::class => 'must be a public instance method', - StaticHandler::class => 'must be a public instance method', - StdClassReturnHandler::class => 'must return', - AbstractDtoHandler::class => 'cannot be an input DTO', - EnumDtoHandler::class => 'cannot be an input DTO', - InterfaceDtoHandler::class => 'cannot be an input DTO', - IterableHandler::class => 'has type iterable', - FileOnQueryHandler::class => 'needs #[File]', - BareFileUploadHandler::class => 'needs #[File]', - ]; - foreach ($cases as $handler => $needle) { - try { - DtoCompiler::compile($handler); - $this->fail($handler); - } catch (\LogicException $exception) { - $this->assertStringContainsString($needle, $exception->getMessage(), $handler); - } - } - - $examples = DtoCompiler::compile(TwoExamplesHandler::class)->fields[0]->examples; - $this->assertSame(['one' => 1, 'two' => 2], $examples); - - $twin = DtoCompiler::compile(TwinHandler::class); - $this->assertSame('left', $twin->firstBody); - $this->assertTrue($twin->readsBody); - $address = realpath(new \ReflectionClass(AddressInput::class)->getFileName() ?: ''); - $this->assertCount(1, array_filter($twin->files, static fn (string $file): bool => realpath($file) === $address)); - $this->assertSame(['id', 'slug'], DtoCompiler::compile(TwoPathsHandler::class)->pathNames()); - $this->assertSame( - [MediaTypes::JSON, MediaTypes::MULTIPART], - DtoCompiler::compile(AvatarHandler::class)->contentTypes, - ); - $described = DtoCompiler::compile(DescribedHandler::class); - $this->assertFalse($described->bodyRequired); - $this->assertTrue($described->readsBody); - $this->assertSame([MediaTypes::JSON], $described->contentTypes); - } - - public function testBoundsAcceptTheInclusiveEdge(): void - { - $range = new Range(min: 1, max: 1); - $this->assertNull($range->validate(1, new ConstraintContext('n', 'Dto', ['n'], ['n' => 1]))); - $this->assertSame('1.5', new Range(min: 1.5, max: 2.5)->validate(1.5, new ConstraintContext('n', 'Dto', ['n'], ['n' => 1.5])) === null ? '1.5' : 'rejected'); - new Length(min: 2, max: 2); - new Length(max: 0); - $length = new Length(min: 0, max: 2); - $this->assertNull($length->validate('', new ConstraintContext('s', 'Dto', ['s'], ['s' => '']))); - $this->assertNull($length->validate('ab', new ConstraintContext('s', 'Dto', ['s'], ['s' => 'ab']))); - $this->assertSame('Value must have between 0 and 2 characters', $length->validate('abc', new ConstraintContext('s', 'Dto', ['s'], ['s' => 'abc']))); - $this->assertSame('Value must have at most 2 characters', new Length(max: 2)->validate('abc', new ConstraintContext('s', 'Dto', ['s'], ['s' => 'abc']))); - $this->assertSame('^[0-9]{5}$', new Pattern('/^[0-9]{5}$/')->expression()); - try { - new Length(max: -1); - $this->fail('negative'); - } catch (\InvalidArgumentException $exception) { - $this->assertStringContainsString('zero or greater', $exception->getMessage()); - } - $this->assertSame('Value must be at least 1.5', new Range(min: 1.5)->validate(1, new ConstraintContext('n', 'Dto', ['n'], ['n' => 1]))); - - try { - new ConstraintContext('page', 'Dto', ['page'], [])->value('missing'); - $this->fail('unknown'); - } catch (\LogicException $exception) { - $this->assertStringContainsString("value('page')", $exception->getMessage()); - } - } - - public function testDateAndEnumMessages(): void - { - $date = new DateFormat('d.m.Y')->cast('24.12.2026'); - $this->assertSame('2026-12-24T00:00:00+00:00', $date->format('c')); - $parsed = ScalarCoercer::toDateTime('2026-12-24T00:00:00.1Z'); - $this->assertSame('100000', $parsed->format('u')); - $longer = ScalarCoercer::toDateTime('2026-12-24T00:00:00.1234567Z'); - $this->assertSame('123456', $longer->format('u')); - $this->assertSame('Value must be one of: 1, 2', ScalarCoercer::enumMessage(Priority::class)); - $this->assertSame( - ['__netteApi' => 'enum', 'class' => Priority::class, 'value' => 1.5], - ValueExport::import(['__netteApi' => 'enum', 'class' => Priority::class, 'value' => 1.5]), - ); - $this->assertSame('application/json', MediaTypes::normalize(' Application/JSON ; charset=utf-8')); - } - - public function testSchemaObjectCopiesDescription(): void - { - $field = DtoCompiler::compile(ListUsersHandler::class)->fields[0]; - $schema = SchemaBuilder::object([$field]); - $this->assertSame('Page number', $schema['properties']['page']['description']); - $this->assertSame('integer', $schema['properties']['page']['type']); - $this->assertArrayNotHasKey('required', $schema); - $id = DtoCompiler::compile(UserDetailHandler::class)->fields[0]; - $required = SchemaBuilder::object([$id]); - $this->assertSame(['id'], $required['required']); - $this->assertSame('integer', $required['properties']['id']['type']); - } - - public function testHeadersIgnoreServerInternals(): void - { - $_SERVER['HTTP_X_REQUEST_ID'] = 'abc'; - $_SERVER['HTTP_X_TRACE'] = 'xyz'; - $_SERVER['SCRIPT_NAME'] = '/index.php'; - $_SERVER['CONTENT_TYPE'] = 'application/json'; - $this->assertSame('abc', HeaderBag::get('x-request-id')); - $this->assertSame('xyz', HeaderBag::get('X-Trace')); - $this->assertFalse(HeaderBag::has('t-name')); - $this->assertSame('application/json', HeaderBag::get('Content-Type')); - } - - public function testFileUploadReplacesNonStrings(): void - { - $file = FileUpload::fromFile(['name' => 1, 'type' => 2, 'tmp_name' => 3, 'size' => '12']); - $this->assertSame('', $file->originalName); - $this->assertSame('', $file->clientContentType); - $this->assertSame('', $file->temporaryPath); - $this->assertSame(0, $file->size); - $this->assertSame(\UPLOAD_ERR_NO_FILE, $file->error); - } - - public function testNestedDefaultsRoundTrip(): void - { - $exported = ValueExport::export(['flag' => true, 'nested' => ['n' => 2], 'status' => Priority::High]); - $this->assertSame(2, ValueExport::import($exported)['nested']['n']); - $this->assertSame(Priority::High, ValueExport::import($exported)['status']); - } - - public function testPathCaptureDoesNotLeakIntoTheNextEndpoint(): void - { - $decider = new ApiDecider(new Container()); - $decider->enableGlobalPreflight(); - $decider->addApi(new EndpointIdentifier('GET', 1, 'users', 'list'), new AlwaysOkHandler(), new NoAuthorization()); - $decider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), new UserDetailHandler(), new NoAuthorization()); - $decider->addApi(new EndpointIdentifier('GET', 2, 'users', '{id}/detail'), new UserDetailHandler(), new NoAuthorization()); - - $matched = self::resolve($decider, 'GET', '1', 'users', '42', '/api/v1/users/42/detail'); - $id = null; - foreach ($matched->getHandler()->params() as $param) { - if ($param->getKey() === 'id') { - $id = $param->getValue(); - } - } - $this->assertSame(42, $id); - - $static = self::resolve($decider, 'GET', '1', 'users', 'list', '/api/v1/users/list'); - $this->assertInstanceOf(AlwaysOkHandler::class, $static->getHandler()); - foreach (new UserDetailHandler()->params() as $param) { - if ($param->getKey() === 'id') { - $this->assertNull($param->getValue()); - } - } - - $post = self::resolve($decider, 'POST', '1', 'users', '42', '/api/v1/users/42/detail'); - $this->assertInstanceOf(DefaultHandler::class, $post->getHandler()); - $withPreflight = self::resolve($decider, 'GET', '1', 'users', '7', '/api/v1/users/7/detail'); - $this->assertInstanceOf(UserDetailHandler::class, $withPreflight->getHandler()); - $otherVersion = self::resolve($decider, 'GET', '1', 'users', '7', '/api/v2/users/7/detail'); - $this->assertInstanceOf(DefaultHandler::class, $otherVersion->getHandler()); - - $decider->addApi(new EndpointIdentifier('GET', 1, 'users', 'detail'), new UserDetailHandler(), new NoAuthorization()); - $this->expectException(\LogicException::class); - $decider->getApi('GET', '1', 'users', 'detail'); - } - - private static function resolve(ApiDecider $decider, string $method, string $version, string $package, string $apiAction, string $path): Api - { - $api = $decider->getApi($method, $version, $package, $apiAction); - - return $api->getHandler() instanceof DefaultHandler ? ($decider->matchPath($method, $version, $package, $apiAction, $path) ?? $api) : $api; - } - - public function testPresenterDropsAStaleBody(): void - { - RequestInput::setRawBody('{"customerEmail":"ada@example.com","address":{"street":"Main","postalCode":"81101"},"items":[{"sku":"A","quantity":1}]}'); - $_SERVER['CONTENT_TYPE'] = 'application/json'; - $_SERVER['REQUEST_METHOD'] = 'POST'; - $decider = new ApiDecider(new Container()); - $decider->addApi(new EndpointIdentifier('POST', 1, 'orders'), new CreateOrderHandler(), new NoAuthorization()); - $presenter = new ApiPresenter(); - $presenter->apiDecider = $decider; - $presenter->response = new HttpResponse(); - $presenter->context = new Container(); - $presenter->outputConfigurator = new DebuggerConfigurator(); - $presenter->errorHandler = new DefaultErrorHandler($presenter->outputConfigurator); - $result = $presenter->run(new Request('Api:Api:default', 'POST', ['version' => '1', 'package' => 'orders'])); - $this->assertSame(400, $result->getCode()); - } - - public function testASecondBootOfTheSameHandlerKeepsTheFirstRead(): void - { - $_GET = ['page' => '4']; - $first = $this->payload(new ListUsersHandler()); - $_GET = ['page' => '9']; - $second = $this->payload(new ListUsersHandler()); - $this->assertSame(4, $first['page']); - $this->assertSame(4, $second['page']); - - RequestInput::reset(); - $_GET = ['page' => '9']; - $this->assertSame(9, $this->payload(new ListUsersHandler())['page']); - } - - public function testFieldErrorsStayOnTheirOwnName(): void - { - $params = new PrefixHandler()->params(); - $byName = []; - foreach ($params as $param) { - $result = $param->validate(); - $this->assertFalse($result->isOk()); - $byName[$param->getKey()] = $result->getErrors(); - } - $this->assertSame(['a' => ['Field is required']], $byName['a']); - $this->assertSame(['ab' => ['Field is required']], $byName['ab']); - $this->assertSame('', $params[0]->getDescription()); - $page = new ListUsersHandler()->params()[0]; - $this->assertSame('Page number', $page->getDescription()); - $this->assertFalse($page->isMulti()); - $items = new CreateOrderHandler()->params()[2]; - $this->assertTrue($items->isMulti()); - $this->assertNotSame([], $items->getContentTypes()); - } - - public function testMalformedJsonStillChecksQueryFields(): void - { - $_GET = ['page' => '1a']; - RequestInput::setRawBody('{"email":'); - $_SERVER['CONTENT_TYPE'] = 'application/json'; - $_SERVER['REQUEST_METHOD'] = 'POST'; - $errors = $this->errors(new QueryAfterBodyHandler()); - $this->assertStringStartsWith('Syntax error', $errors['body'][0]); - $this->assertSame(['Value must be an integer'], $errors['page']); - } - - public function testInvalidIntegerKeepsTheDefaultForTheValue(): void - { - $_GET = ['page' => '1a']; - $page = new ListUsersHandler()->params()[0]; - $page->validate(); - $this->assertSame(1, $page->getValue()); - } - - public function testEveryNestedErrorIsReported(): void - { - $this->json([ - 'customerEmail' => 'ada@example.com', - 'address' => ['street' => '', 'postalCode' => 'abc'], - 'items' => [ - ['sku' => 'A', 'quantity' => 0], - ['sku' => 'B', 'quantity' => 0], - ], - ]); - $errors = $this->errors(new CreateOrderHandler()); - $this->assertArrayHasKey('address.street', $errors); - $this->assertArrayHasKey('address.postalCode', $errors); - $this->assertArrayHasKey('items[0].quantity', $errors); - $this->assertArrayHasKey('items[1].quantity', $errors); - - RequestInput::reset(); - $_SERVER['CONTENT_TYPE'] = 'application/json'; - $_SERVER['REQUEST_METHOD'] = 'POST'; - RequestInput::setRawBody('{"customerEmail":"ada@example.com","address":{},"items":[{"sku":"A","quantity":1}]}'); - $emptyObject = $this->errors(new CreateOrderHandler()); - $this->assertSame(['Field is required'], $emptyObject['address.street']); - $this->assertArrayNotHasKey('address', $emptyObject); - - RequestInput::reset(); - $_SERVER['CONTENT_TYPE'] = 'application/json'; - RequestInput::setRawBody('{"customerEmail":"ada@example.com","address":[],"items":[{"sku":"A","quantity":1}]}'); - $this->assertSame(['Value must be an object'], $this->errors(new CreateOrderHandler())['address']); - - RequestInput::reset(); - $_SERVER['CONTENT_TYPE'] = 'application/json'; - RequestInput::setRawBody('{"customerEmail":"ada@example.com","address":{"street":"Main 1","postalCode":"81101"},"items":{}}'); - $this->assertSame(['Value must be a list'], $this->errors(new CreateOrderHandler())['items']); - - RequestInput::reset(); - $_SERVER['CONTENT_TYPE'] = 'application/json'; - RequestInput::setRawBody('[]'); - $this->assertSame(['body' => ['Value must be an object']], $this->errors(new CreateOrderHandler())); - } - - public function testEmptyObjectAndFloat(): void - { - RequestInput::setRawBody('{}'); - $_SERVER['CONTENT_TYPE'] = 'application/json'; - $_SERVER['REQUEST_METHOD'] = 'POST'; - $errors = $this->errors(new CreateOrderHandler()); - $this->assertArrayNotHasKey('body', $errors); - $this->assertSame(['Field is required'], $errors['customerEmail']); - - RequestInput::reset(); - $_GET = ['ratio' => '1.5']; - $this->assertEqualsWithDelta(1.5, $this->payload(new FloatHandler())['ratio'], PHP_FLOAT_EPSILON); - } - - public function testUploadErrorShapes(): void - { - $_SERVER['REQUEST_METHOD'] = 'POST'; - $_SERVER['CONTENT_TYPE'] = 'multipart/form-data'; - $_FILES = ['avatar' => ['name' => '', 'type' => '', 'tmp_name' => '', 'error' => \UPLOAD_ERR_NO_FILE, 'size' => 0]]; - $_POST = ['displayName' => 'Ada']; - $this->assertSame(['avatar' => ['Field is required']], $this->errors(new AvatarHandler())); - - RequestInput::reset(); - $_FILES = ['avatar' => ['name' => 'a.png', 'type' => '', 'tmp_name' => '/tmp/a', 'error' => \UPLOAD_ERR_NO_FILE, 'size' => 4]]; - $this->assertSame('a.png', $this->payload(new AvatarHandler())['file']); - - RequestInput::reset(); - $_FILES = ['avatar' => ['error' => \UPLOAD_ERR_NO_FILE, 'size' => 0]]; - $this->assertSame(['avatar' => ['Field is required']], $this->errors(new AvatarHandler())); - } - - public function testBodyParamReadsJsonObjectsOnly(): void - { - RequestInput::setRawBody('{"note":"hi","1":"n"}'); - $_SERVER['CONTENT_TYPE'] = 'application/json'; - $param = new BodyInputParam('note'); - $this->assertSame('hi', $param->getValue()); - $numeric = new BodyInputParam('1'); - $this->assertSame('n', $numeric->getValue()); - - RequestInput::reset(); - RequestInput::setRawBody('[1, 2]'); - $_SERVER['CONTENT_TYPE'] = 'application/json'; - $this->assertNull(new BodyInputParam('note')->getValue()); - - RequestInput::reset(); - RequestInput::setRawBody(''); - $this->assertNull(new BodyInputParam('note')->getValue()); - } - - public function testOpenApiUsesTheDeclaredBodyMediaTypeAndDescription(): void - { - $builder = new RequestBodyBuilder(); - $body = $builder->build(new DescribedHandler(), new SchemaRegistry()); - $this->assertIsArray($body); - $this->assertSame(['application/json'], array_keys($body['content'])); - $this->assertSame('Customer email', $body['content']['application/json']['schema']['properties']['email']['description']); - $this->assertFalse($body['required']); - } - - public function testLinkKeepsASlashInThePackage(): void - { - $link = ApiFixtures::apiLink()->link(new EndpointIdentifier('GET', 1, 'acme/widgets', 'show'), ['q' => 'a b']); - $this->assertSame('https://example.com/api/v1/acme/widgets/show?q=a+b', $link); - } - - public function testExtensionInstallsTypedHandlersAndTheirFiles(): void - { - $container = ContainerFactory::create(<<<'NEON' -services: - listUsers: Tomaj\NetteApi\Test\Input\Fixtures\ListUsersHandler -api: - endpoints: - - {method: GET, version: 1, package: people, handler: @listUsers} - - {method: POST, version: 1, package: orders, handler: Tomaj\NetteApi\Test\Input\Fixtures\CreateOrderHandler()} -NEON); - $container->initialize(); - $this->assertTrue(DtoMetadataRegistry::installed()); - $this->assertTrue(DtoMetadataRegistry::installs(ListUsersHandler::class)); - $this->assertTrue(DtoMetadataRegistry::installs(CreateOrderHandler::class)); - $urls = []; - foreach ($container->getByType(ApiDecider::class)->getApis() as $api) { - $urls[] = $api->getEndpoint()->getUrl(); - } - $this->assertContains('v1/people/', $urls); - $this->assertContains('v1/orders/', $urls); - - DtoMetadataRegistry::reset(); - $empty = ContainerFactory::create("api:\n endpoints: []\n"); - $empty->initialize(); - $this->assertFalse(DtoMetadataRegistry::installed()); - - $compiler = new Compiler(); - $compiler->addExtension('api', new NetteApiExtension()); - $compiler->addConfig([ - 'api' => [ - 'endpoints' => [[ - 'method' => 'POST', - 'version' => 1, - 'package' => 'orders', - 'handler' => CreateOrderHandler::class, - ]], - ], - ]); - $compiler->compile(); - $this->assertStringContainsString('Handlers.php', serialize($compiler->exportDependencies())); - } - - public function testBackslashHandlerIsInstalledUnderItsRealName(): void - { - $container = ContainerFactory::create(<<<'NEON' -api: - endpoints: - - {method: GET, version: 1, package: people, action: list, handler: \Tomaj\NetteApi\Test\Input\Fixtures\ListUsersHandler} -NEON); - $container->initialize(); - $this->assertTrue(DtoMetadataRegistry::installs(ListUsersHandler::class)); - } - - /** - * @param array $body - */ - private function json(array $body): void - { - RequestInput::reset(); - RequestInput::setRawBody((string) json_encode($body)); - $_SERVER['CONTENT_TYPE'] = 'application/json'; - $_SERVER['REQUEST_METHOD'] = 'POST'; - $_GET = []; - $_POST = []; - } - - /** - * @return array - */ - private function payload(object $handler): array - { - $processor = new ParamsProcessor($handler->params()); - $this->assertFalse($processor->isError(), (string) json_encode($processor->getErrors())); - - return $handler->handle($processor->getValues())->getPayload(); - } - - /** - * @return array> - */ - private function errors(object $handler): array - { - $processor = new ParamsProcessor($handler->params()); - $this->assertTrue($processor->isError()); - - return $processor->getErrors(); - } -} - -final readonly class CyclePinInput -{ - public function __construct(#[Body] public CyclePinInput $child) - { - } -} - -final class CyclePinHandler extends TypedHandler -{ - public function handleDto(CyclePinInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final class PrivateHandler extends TypedHandler -{ - private function handleDto(CyclePinInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final class StaticHandler extends TypedHandler -{ - public static function handleDto(CyclePinInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final class StdClassReturnHandler extends TypedHandler -{ - public function handleDto(CyclePinInput $input): \stdClass - { - return new \stdClass(); - } -} - -abstract readonly class AbstractPinInput -{ - public function __construct(#[Query] public string $name) - { - } -} - -final class AbstractDtoHandler extends TypedHandler -{ - public function handleDto(AbstractPinInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final class EnumDtoHandler extends TypedHandler -{ - public function handleDto(Priority $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -interface PinContract -{ -} - -final class InterfaceDtoHandler extends TypedHandler -{ - public function handleDto(PinContract $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class IterableInput -{ - public function __construct(#[Query] public iterable $name) - { - } -} - -final class IterableHandler extends TypedHandler -{ - public function handleDto(IterableInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class FileOnQueryInput -{ - public function __construct(#[Query] public FileUpload $file) - { - } -} - -final class FileOnQueryHandler extends TypedHandler -{ - public function handleDto(FileOnQueryInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class BareFileUploadInput -{ - /** @param list $files */ - public function __construct(#[Query] public array $files) - { - } -} - -final class BareFileUploadHandler extends TypedHandler -{ - public function handleDto(BareFileUploadInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class TwoExamplesInput -{ - public function __construct(#[Query(examples: ['one' => 1, 'two' => 2])] public int $page = 1) - { - } -} - -final class TwoExamplesHandler extends TypedHandler -{ - public function handleDto(TwoExamplesInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class TwinInput -{ - public function __construct( - #[Body] public AddressInput $left, - #[Body] public AddressInput $right, - ) { - } -} - -final class TwinHandler extends TypedHandler -{ - public function handleDto(TwinInput $input): ResponseInterface - { - return new JsonApiResponse(200, ['street' => $input->left->street]); - } -} - -final readonly class TwoPathsInput -{ - public function __construct( - #[Path] public string $id, - #[Path] public string $slug, - ) { - } -} - -final class TwoPathsHandler extends TypedHandler -{ - public function handleDto(TwoPathsInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class PrefixInput -{ - public function __construct( - #[Query(description: '')] public string $a, - #[Query] public string $ab, - ) { - } -} - -final class PrefixHandler extends TypedHandler -{ - public function handleDto(PrefixInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class QueryAfterBodyInput -{ - public function __construct( - #[Body] public string $email, - #[Query] public int $page = 1, - ) { - } -} - -final class QueryAfterBodyHandler extends TypedHandler -{ - public function handleDto(QueryAfterBodyInput $input): ResponseInterface - { - return new JsonApiResponse(200, ['page' => $input->page]); - } -} - -final readonly class FloatInput -{ - public function __construct(#[Query] public float $ratio) - { - } -} - -final class FloatHandler extends TypedHandler -{ - public function handleDto(FloatInput $input): ResponseInterface - { - return new JsonApiResponse(200, ['ratio' => $input->ratio]); - } -} - -final readonly class DescribedInput -{ - public function __construct( - #[Body(description: 'Customer email')] public ?string $email = null, - ) { - } -} - -#[Consumes('application/json')] -final class DescribedHandler extends TypedHandler -{ - public function handleDto(DescribedInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} diff --git a/tests/Input/BodyParsingTest.php b/tests/Input/BodyParsingTest.php new file mode 100644 index 000000000..7ef13569b --- /dev/null +++ b/tests/Input/BodyParsingTest.php @@ -0,0 +1,294 @@ +expectException(UnsupportedMediaTypeException::class); + $this->expectExceptionMessage('Content-Type is missing'); + new ParamsProcessor(new OptionalHandler()->params())->isError(); + } + + public function testAnEmptyRequestWithoutAContentTypeStillSucceedsWhenAllFieldsAreOptional(): void + { + unset($_SERVER['CONTENT_TYPE']); + $_SERVER['REQUEST_METHOD'] = 'POST'; + RequestInput::setRawBody(''); + + $this->assertFalse(new ParamsProcessor(new OptionalHandler()->params())->isError()); + } + + public function testMultipartWithPutAnswersWithTheReasonInsteadOfMissingFields(): void + { + $_SERVER['CONTENT_TYPE'] = 'multipart/form-data; boundary=x'; + $_SERVER['REQUEST_METHOD'] = 'PUT'; + RequestInput::setRawBody("--x\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\nv\r\n--x--\r\n"); + + $processor = new ParamsProcessor(new MultipartHandler()->params()); + $this->assertTrue($processor->isError()); + $this->assertSame( + ['body' => ['multipart/form-data is only parsed by PHP for POST requests, but this one is PUT. Send it with POST, or use application/json']], + $processor->getErrors(), + ); + } + + public function testAnEmptyMultipartPutIsNotAnError(): void + { + $_SERVER['CONTENT_TYPE'] = 'multipart/form-data; boundary=x'; + $_SERVER['REQUEST_METHOD'] = 'PUT'; + RequestInput::setRawBody(''); + + $this->assertFalse(new ParamsProcessor(new MultipartHandler()->params())->isError()); + } + + public function testTooManyFormFieldsDoNotReachTheErrorHandlerOfTheApplication(): void + { + $limit = (int) ini_get('max_input_vars'); + $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; + $_SERVER['REQUEST_METHOD'] = 'PUT'; + RequestInput::setRawBody(implode('&', array_map(static fn (int $i): string => 'f' . $i . '=1', range(1, $limit + 1)))); + + $seen = []; + set_error_handler(static function (int $level, string $message) use (&$seen): bool { + $seen[] = $message; + + return true; + }); + error_clear_last(); + try { + $this->assertTrue(new ParamsProcessor(new FormHandler()->params())->isError()); + $afterwards = $seen; + // the handler of the application is back in place: it receives the next warning + hex2bin('abc'); + } finally { + restore_error_handler(); + } + + // PHP's own handler runs only when ours declines the warning, and it would leave it in error_get_last() + $this->assertNull(error_get_last()); + $this->assertSame([], $afterwards); + $this->assertCount(1, $seen); + } + + public function testTooManyFormFieldsAreAnErrorInsteadOfAWarning(): void + { + $limit = (int) ini_get('max_input_vars'); + $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; + $_SERVER['REQUEST_METHOD'] = 'PUT'; + RequestInput::setRawBody(implode('&', array_map(static fn (int $i): string => 'f' . $i . '=1', range(1, $limit + 1)))); + + $processor = new ParamsProcessor(new FormHandler()->params()); + $this->assertTrue($processor->isError()); + $this->assertSame(['body' => ['Too many form fields']], $processor->getErrors()); + } + + public function testExactlyTheLimitOfFormFieldsIsAccepted(): void + { + $limit = (int) ini_get('max_input_vars'); + $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; + $_SERVER['REQUEST_METHOD'] = 'PUT'; + RequestInput::setRawBody(implode('&', array_map(static fn (int $i): string => 'f' . $i . '=1', range(1, $limit)))); + + $this->assertFalse(new ParamsProcessor(new FormHandler()->params())->isError()); + } + + public function testAPostFormWithMoreFieldsThanMaxInputVarsIsRejected(): void + { + $limit = (int) ini_get('max_input_vars'); + // PHP keeps the first `limit` variables and drops the rest without a word + $_POST = array_fill_keys(array_map(static fn (int $i): string => 'f' . $i, range(1, $limit)), '1'); + + $errors = $this->post('application/x-www-form-urlencoded', self::pairs('f', $limit + 1), new BodyFieldHandler()); + + $this->assertSame(['body' => ['Too many form fields']], $errors); + } + + public function testAPostFormWithExactlyTheLimitIsAccepted(): void + { + $limit = (int) ini_get('max_input_vars'); + $_POST = array_fill_keys(array_map(static fn (int $i): string => 'f' . $i, range(1, $limit)), '1'); + + $this->assertNull($this->post('application/x-www-form-urlencoded', self::pairs('f', $limit), new BodyFieldHandler())); + } + + public function testAPostFormIsCountedWithItsNestedValues(): void + { + $limit = (int) ini_get('max_input_vars'); + $_POST = ['a' => array_fill(0, $limit, '1')]; + $raw = implode('&', array_map(static fn (int $i): string => 'a[]=' . $i, range(1, $limit + 1))); + + $this->assertSame(['body' => ['Too many form fields']], $this->post('application/x-www-form-urlencoded', $raw, new BodyFieldHandler())); + } + + public function testASmallPostFormIsNotParsedAgain(): void + { + $limit = (int) ini_get('max_input_vars'); + $_POST = ['a' => 'x']; + + // the body is not even looked at: PHP cannot have cut a form that fits + $this->assertNull($this->post('application/x-www-form-urlencoded', self::pairs('f', $limit + 1), new BodyFieldHandler())); + } + + public function testAMultipartPostIsLeftToPhp(): void + { + $limit = (int) ini_get('max_input_vars'); + $_POST = array_fill_keys(array_map(static fn (int $i): string => 'f' . $i, range(1, $limit)), '1'); + + // PHP does not give a multipart body back, so a form that was cut cannot be told from a complete one + $this->assertNull($this->post('multipart/form-data; boundary=x', self::pairs('f', $limit + 1), new BodyFieldMultipartHandler())); + } + + public function testAJsonCharsetOtherThanUtf8IsRejected(): void + { + foreach (['application/json; charset=ISO-8859-1' => 'iso-8859-1', 'application/json;charset="latin1"' => 'latin1', 'application/json; CHARSET=latin1' => 'latin1'] as $contentType => $charset) { + RequestInput::reset(); + $_SERVER['CONTENT_TYPE'] = $contentType; + $_SERVER['REQUEST_METHOD'] = 'POST'; + RequestInput::setRawBody('{"a":"x"}'); + + $processor = new ParamsProcessor(new FormHandler()->params()); + $this->assertTrue($processor->isError(), $contentType); + $this->assertSame(['JSON must be UTF-8; the request says charset=' . $charset], $processor->getErrors()['body']); + } + + foreach (['application/json; charset=UTF-8', 'application/json; Charset="utf-8"', 'application/json'] as $contentType) { + RequestInput::reset(); + $_SERVER['CONTENT_TYPE'] = $contentType; + RequestInput::setRawBody('{"a":"x"}'); + $this->assertFalse(new ParamsProcessor(new FormHandler()->params())->isError(), $contentType); + } + } + + #[DataProvider('charsets')] + public function testJsonCharsets(string $contentType, ?string $rejected): void + { + $errors = $this->post($contentType, '{"a":"x"}', new BodyFieldHandler()); + + if ($rejected === null) { + $this->assertNull($errors, $contentType); + } else { + $this->assertSame(['body' => ['JSON must be UTF-8; the request says charset=' . $rejected]], $errors, $contentType); + } + } + + /** + * @return \Iterator + */ + public static function charsets(): \Iterator + { + yield 'utf-8' => ['application/json; charset=utf-8', null]; + yield 'utf8 spelling' => ['application/json; charset=utf8', null]; + yield 'UTF8 upper case' => ['application/json; charset=UTF8', null]; + yield 'us-ascii' => ['application/json; charset=US-ASCII', null]; + yield 'quoted' => ['application/json; charset="utf-8"', null]; + yield 'spaces around the equals sign' => ['application/json; charset = utf-8', null]; + yield 'trailing space' => ['application/json; charset="UTF-8" ', null]; + yield 'quoted value that only looks like a charset' => ['application/json; foo="a;charset=latin1"', null]; + yield 'the first charset wins' => ['application/json; charset=utf-8; charset=latin1', null]; + yield 'another parameter first' => ['application/json; foo=1; charset=latin1', 'latin1']; + yield 'latin1' => ['application/json; charset=ISO-8859-1', 'iso-8859-1']; + yield 'quoted latin1' => ['application/json;charset="latin1"', 'latin1']; + yield 'long value is cut' => ['application/json; charset=' . str_repeat('X', 100), str_repeat('x', 30)]; + yield 'value of exactly the shown length' => ['application/json; charset=' . str_repeat('y', 30), str_repeat('y', 30)]; + } + + private static function pairs(string $name, int $count): string + { + return implode('&', array_map(static fn (int $i): string => $name . $i . '=1', range(1, $count))); + } + + /** + * @return array>|null + */ + private function post(string $contentType, string $raw, TypedHandler $handler): ?array + { + $_SERVER['CONTENT_TYPE'] = $contentType; + $_SERVER['REQUEST_METHOD'] = 'POST'; + RequestInput::setRawBody($raw); + $processor = new ParamsProcessor($handler->params()); + + return $processor->isError() ? $processor->getErrors() : null; + } + +} + +final readonly class OptionalInput +{ + public function __construct( + #[Body] public ?string $a = null, + #[Body] public ?Color $c = null, + ) { + } +} + +final class OptionalHandler extends TypedHandler +{ + public function handleDto(OptionalInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +#[Consumes(MediaTypes::MULTIPART)] +final class MultipartHandler extends TypedHandler +{ + public function handleDto(FormInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +enum Color: string +{ + case Red = 'red'; +} + +#[Consumes(MediaTypes::MULTIPART)] +final class BodyFieldMultipartHandler extends TypedHandler +{ + public function handleDto(BodyFieldInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} diff --git a/tests/Input/CasterTest.php b/tests/Input/CasterTest.php index a41a95413..36a17e1ad 100644 --- a/tests/Input/CasterTest.php +++ b/tests/Input/CasterTest.php @@ -9,9 +9,43 @@ use Tomaj\NetteApi\Input\DateFormat; use Tomaj\NetteApi\Input\Split; use Tomaj\NetteApi\Input\UnixTimestamp; +use Tomaj\NetteApi\Handlers\TypedHandler; +use Tomaj\NetteApi\Input\Body; +use Tomaj\NetteApi\Input\Cast; +use Tomaj\NetteApi\Input\CasterInterface; +use Tomaj\NetteApi\Input\DtoCompiler; +use Tomaj\NetteApi\Input\DtoMetadata; +use Tomaj\NetteApi\Input\DtoMetadataRegistry; +use Tomaj\NetteApi\Input\OpenApiCasterInterface; +use Tomaj\NetteApi\Input\Query; +use Tomaj\NetteApi\Input\RequestInput; +use Tomaj\NetteApi\Input\SchemaBuilder; +use Tomaj\NetteApi\OpenApi\ParameterBuilder; +use Tomaj\NetteApi\Params\ParamsProcessor; +use Tomaj\NetteApi\Response\JsonApiResponse; +use Tomaj\NetteApi\Response\ResponseInterface; +use Tomaj\NetteApi\Test\Input\Fixtures\NamedCaster; +use Tomaj\NetteApi\Test\Input\Fixtures\SplitHandler; final class CasterTest extends TestCase { + protected function setUp(): void + { + RequestInput::reset(); + DtoMetadataRegistry::reset(); + $_GET = []; + $_POST = []; + $_FILES = []; + } + + protected function tearDown(): void + { + RequestInput::reset(); + DtoMetadataRegistry::reset(); + $_GET = []; + unset($_SERVER['CONTENT_TYPE'], $_SERVER['REQUEST_METHOD']); + } + public function testDateFormat(): void { $caster = new DateFormat('d.m.Y'); @@ -65,4 +99,231 @@ public function testSplitRejectsAnEmptySeparator(): void $this->expectException(\InvalidArgumentException::class); new Split(''); } + + public function testValueObjectCasterIsNotCompiledAsADto(): void + { + $this->json(['price' => '12.50', 'prices' => ['1.00', '2.25']]); + $handler = new MoneyHandler(); + $processor = new ParamsProcessor($handler->params()); + $this->assertFalse($processor->isError(), (string) json_encode($processor->getErrors())); + $this->assertSame(['price' => 1250, 'prices' => [100, 225]], $handler->handle($processor->getValues())->getPayload()); + + $fields = DtoCompiler::compile(MoneyHandler::class)->fields; + $this->assertSame([], $fields[0]->children); + $this->assertSame(['type' => 'string', 'example' => '12.50'], SchemaBuilder::build($fields[0], true)); + $this->assertNull($fields[1]->item); + + $this->json(['price' => 'abc', 'prices' => []]); + $this->assertSame(['price' => ['Use a decimal amount, for example 12.50']], $this->errors(new MoneyHandler())); + } + + public function testNamedCasterArgumentsSurviveTheCompiledContainer(): void + { + $_GET = ['value' => 'X', 'other' => 'Y']; + $this->assertSame(['value' => 'STARTXEND', 'other' => 'AYB'], $this->payload(new NamedCasterHandler())); + $compiled = DtoCompiler::compile(WireSchemaHandler::class); + $imported = unserialize(serialize($compiled)); + $this->assertInstanceOf(DtoMetadata::class, $imported); + $this->assertSame($compiled->fields[0]->casterSchema, $imported->fields[0]->casterSchema); + $this->assertSame('integer', $imported->fields[0]->casterSchema['type'] ?? null); + + DtoMetadataRegistry::install([NamedCasterHandler::class => serialize(DtoCompiler::compile(NamedCasterHandler::class))]); + $this->assertTrue(DtoMetadataRegistry::installs(NamedCasterHandler::class)); + $this->assertSame(['value' => 'STARTXEND', 'other' => 'AYB'], $this->payload(new NamedCasterHandler())); + } + + public function testNulByteIsAFieldError(): void + { + try { + new DateFormat('d.m.Y')->cast("24.12.2026\0"); + $this->fail('NUL byte was accepted'); + } catch (CastException $exception) { + $this->assertSame('Date must match d.m.Y, for example 24.12.2026', $exception->getMessage()); + } + + $this->json(['day' => "24.12.2026\u{0}"]); + $this->assertSame(['day' => ['Date must match d.m.Y, for example 24.12.2026']], $this->errors(new NulDateHandler())); + } + + public function testCompiledCasterSchemaUsesTheWireType(): void + { + $fields = DtoCompiler::compile(WireSchemaHandler::class)->fields; + $this->assertSame('integer', SchemaBuilder::build($fields[0], true)['type']); + $this->assertSame(new UnixTimestamp()->openApiSchema()['example'], SchemaBuilder::build($fields[0], true)['example']); + $this->assertSame(['type' => 'string'], SchemaBuilder::build($fields[1], true)); + } + + public function testSplitPropertyIsOneStringInputWithoutAnArrayDefault(): void + { + $param = new SplitHandler()->params()[0]; + $this->assertFalse($param->isMulti()); + $this->assertNull($param->getDefault()); + $this->assertSame(['type' => 'string', 'example' => 'red,green,blue'], $param->getOpenApiSchema()); + + $parameters = new ParameterBuilder()->build(new SplitHandler()); + $this->assertSame(['tags', 'label'], array_column($parameters, 'name')); + $this->assertSame('plain', $parameters[1]['schema']['default']); + $this->assertSame('plain', new SplitHandler()->params()[1]->getDefault()); + + $_GET = ['tags' => 'a,b']; + $this->assertSame(['tags' => ['a', 'b']], $this->payload(new SplitHandler())); + RequestInput::reset(); + $_GET = []; + $this->assertSame(['tags' => []], $this->payload(new SplitHandler())); + } + + /** + * @param array $body + */ + private function json(array $body): void + { + RequestInput::reset(); + RequestInput::setRawBody((string) json_encode($body)); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + } + + /** + * @return array + */ + private function payload(TypedHandler $handler): array + { + $processor = new ParamsProcessor($handler->params()); + $this->assertFalse($processor->isError(), (string) json_encode($processor->getErrors())); + + return $handler->handle($processor->getValues())->getPayload(); + } + + /** + * @return array + */ + private function errors(TypedHandler $handler): array + { + $processor = new ParamsProcessor($handler->params()); + $this->assertTrue($processor->isError()); + + return $processor->getErrors(); + } +} + +final readonly class Money +{ + private function __construct(public int $cents) + { + } + + public static function fromCents(int $cents): self + { + return new self($cents); + } +} + +final readonly class MoneyCaster implements CasterInterface, OpenApiCasterInterface +{ + public function cast(mixed $value): Money + { + if (!is_string($value) || preg_match('/^\d+\.\d{2}\z/', $value) !== 1) { + throw new CastException('Use a decimal amount, for example 12.50'); + } + + return Money::fromCents((int) str_replace('.', '', $value)); + } + + /** + * @return array{type: string, example: string} + */ + public function openApiSchema(): array + { + return ['type' => 'string', 'example' => '12.50']; + } +} + +final readonly class MoneyListCaster implements CasterInterface +{ + /** + * @return list + */ + public function cast(mixed $value): array + { + if (!is_array($value)) { + throw new CastException('Use a list of amounts'); + } + + return array_values(array_map(static fn (mixed $item): Money => new MoneyCaster()->cast($item), $value)); + } +} + +final readonly class MoneyInput +{ + /** @param list $prices */ + public function __construct( + #[Body] #[Cast(MoneyCaster::class)] public Money $price, + #[Body] #[Cast(MoneyListCaster::class)] public array $prices, + ) { + } +} + +final class MoneyHandler extends TypedHandler +{ + public function handleDto(MoneyInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['price' => $input->price->cents, 'prices' => array_map(static fn (Money $money): int => $money->cents, $input->prices)]); + } +} + +final readonly class NamedCasterInput +{ + public function __construct( + #[Query] #[Cast(NamedCaster::class, suffix: 'END', prefix: 'START')] public string $value, + #[Query] #[Cast(NamedCaster::class)] public string $other, + ) { + } +} + +final class NamedCasterHandler extends TypedHandler +{ + public function handleDto(NamedCasterInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['value' => $input->value, 'other' => $input->other]); + } +} + +final readonly class NulDateInput +{ + public function __construct(#[Body] #[Cast(DateFormat::class, 'd.m.Y')] public \DateTimeImmutable $day) + { + } +} + +final class NulDateHandler extends TypedHandler +{ + public function handleDto(NulDateInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class TextToIntCaster implements CasterInterface +{ + public function cast(mixed $value): int + { + return $value === 'one' ? 1 : 0; + } +} + +final readonly class WireSchemaInput +{ + public function __construct( + #[Query] #[Cast(UnixTimestamp::class)] public \DateTimeImmutable $at, + #[Query] #[Cast(TextToIntCaster::class)] public int $count, + ) { + } +} + +final class WireSchemaHandler extends TypedHandler +{ + public function handleDto(WireSchemaInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } } diff --git a/tests/Input/ConstraintTest.php b/tests/Input/ConstraintTest.php index 53bcfc589..9df7ed031 100644 --- a/tests/Input/ConstraintTest.php +++ b/tests/Input/ConstraintTest.php @@ -46,6 +46,18 @@ public function testRangeConstructorRejectsEmptyAndInvertedBounds(): void new Range(min: 5, max: 1); } + public function testRangeConstructorRejectsInfiniteAndNanBounds(): void + { + foreach ([['min' => INF], ['max' => INF], ['min' => -INF], ['max' => NAN], ['min' => 1, 'max' => NAN]] as $bounds) { + try { + new Range(...$bounds); + $this->fail('non finite bound ' . var_export($bounds, true)); + } catch (\LogicException $exception) { + $this->assertStringContainsString('must be a finite number', $exception->getMessage()); + } + } + } + public function testLengthCountsCharactersAndItems(): void { $text = new Length(min: 1, max: 3); @@ -118,4 +130,63 @@ public function testContextReadsSiblingsAndRejectsUnknownNames(): void $this->expectException(\LogicException::class); $this->context->value('nope'); } + + public function testBoundsAcceptTheInclusiveEdge(): void + { + $range = new Range(min: 1, max: 1); + $this->assertNull($range->validate(1, new ConstraintContext('n', 'Dto', ['n'], ['n' => 1]))); + $this->assertSame('1.5', new Range(min: 1.5, max: 2.5)->validate(1.5, new ConstraintContext('n', 'Dto', ['n'], ['n' => 1.5])) === null ? '1.5' : 'rejected'); + new Length(min: 2, max: 2); + new Length(max: 0); + $length = new Length(min: 0, max: 2); + $this->assertNull($length->validate('', new ConstraintContext('s', 'Dto', ['s'], ['s' => '']))); + $this->assertNull($length->validate('ab', new ConstraintContext('s', 'Dto', ['s'], ['s' => 'ab']))); + $this->assertSame('Value must have between 0 and 2 characters', $length->validate('abc', new ConstraintContext('s', 'Dto', ['s'], ['s' => 'abc']))); + $this->assertSame('Value must have at most 2 characters', new Length(max: 2)->validate('abc', new ConstraintContext('s', 'Dto', ['s'], ['s' => 'abc']))); + $this->assertSame('^[0-9]{5}$', new Pattern('/^[0-9]{5}$/')->expression()); + try { + new Length(max: -1); + $this->fail('negative'); + } catch (\InvalidArgumentException $exception) { + $this->assertStringContainsString('zero or greater', $exception->getMessage()); + } + $this->assertSame('Value must be at least 1.5', new Range(min: 1.5)->validate(1, new ConstraintContext('n', 'Dto', ['n'], ['n' => 1]))); + + try { + new ConstraintContext('page', 'Dto', ['page'], [])->value('missing'); + $this->fail('unknown'); + } catch (\LogicException $exception) { + $this->assertStringContainsString("value('page')", $exception->getMessage()); + } + } + + public function testLengthCountsUtf8CharactersWhateverTheInternalEncoding(): void + { + $encoding = mb_internal_encoding(); + mb_internal_encoding('ISO-8859-1'); + try { + $this->assertNull(new Length(max: 3)->validate('čšž', new ConstraintContext('x', self::class, [], []))); + } finally { + mb_internal_encoding($encoding); + } + } + + public function testASmallRangeBoundIsNotPrintedAsZero(): void + { + $context = new ConstraintContext('x', self::class, [], []); + $this->assertSame('Value must be at most 1.0E-12', new Range(max: 1.0E-12)->validate(1.0, $context)); + $this->assertSame('Value must be at least -2.0E-11', new Range(min: -2.0E-11)->validate(-1.0, $context)); + $this->assertSame('Value must be at most 0.5', new Range(max: 0.5)->validate(1.0, $context)); + $this->assertSame('Value must be at least 0', new Range(min: 0)->validate(-1, $context)); + $this->assertSame('Value must be at most 0', new Range(max: 0.0)->validate(1, $context)); + $this->assertSame('Value must be at most 100', new Range(max: 100.0)->validate(101, $context)); + $this->assertSame('Value must be at most 9223372036854775806', new Range(max: PHP_INT_MAX - 1)->validate(PHP_INT_MAX, $context)); + } + + public function testRangePrintsMinusZeroAsZero(): void + { + $context = new ConstraintContext('x', self::class, [], []); + + $this->assertSame('Value must be at most 0', new Range(max: -0.0)->validate(1, $context)); + } } diff --git a/tests/Input/CompilerBranchTest.php b/tests/Input/DtoAttributeTest.php similarity index 59% rename from tests/Input/CompilerBranchTest.php rename to tests/Input/DtoAttributeTest.php index a704e075c..f04ace643 100644 --- a/tests/Input/CompilerBranchTest.php +++ b/tests/Input/DtoAttributeTest.php @@ -4,70 +4,33 @@ namespace Tomaj\NetteApi\Test\Input; -use Tomaj\NetteApi\ValidationResult\ValidationResult; -use Tomaj\NetteApi\Params\ParamsProcessor; -use Tomaj\NetteApi\Input\Field; -use Tomaj\NetteApi\Input\DtoMetadata; -use Tomaj\NetteApi\DI\NetteApiExtension; -use MissingDto\Nope; -use Tomaj\NetteApi\Input\Path; -use Nette\DI\Compiler; use PHPUnit\Framework\TestCase; -use Tomaj\NetteApi\Handlers\AlwaysOkHandler; +use MissingDto\Nope; use Tomaj\NetteApi\Handlers\TypedHandler; use Tomaj\NetteApi\Input\Body; use Tomaj\NetteApi\Input\Cast; use Tomaj\NetteApi\Input\CasterInterface; -use Tomaj\NetteApi\Input\DateFormat; use Tomaj\NetteApi\Input\DtoCompiler; -use Tomaj\NetteApi\Input\RequestInput; -use Tomaj\NetteApi\Input\DtoMetadataRegistry; -use Tomaj\NetteApi\Input\EndpointTemplate; +use Tomaj\NetteApi\Input\Field; use Tomaj\NetteApi\Input\File; use Tomaj\NetteApi\Input\FileUpload; -use Tomaj\NetteApi\Input\MediaTypes; use Tomaj\NetteApi\Input\OpenApiCasterInterface; use Tomaj\NetteApi\Input\Query; -use Tomaj\NetteApi\Input\SchemaBuilder; -use Tomaj\NetteApi\Input\ValueExport; use Tomaj\NetteApi\Response\JsonApiResponse; use Tomaj\NetteApi\Response\ResponseInterface; -use Tomaj\NetteApi\Test\DI\ContainerFactory; -use Tomaj\NetteApi\Test\Input\Fixtures\CreateOrderHandler; -use Tomaj\NetteApi\Test\Input\Fixtures\ListUsersHandler; +use Tomaj\NetteApi\Test\Input\Fixtures\DateHintHandler; +use Tomaj\NetteApi\Test\Input\Fixtures\FloatRangeHandler; +use Tomaj\NetteApi\Test\Input\Fixtures\Priority; use Tomaj\NetteApi\Test\Input\Fixtures\UserStatus; use Tomaj\NetteApi\Validation\ConstraintContext; use Tomaj\NetteApi\Validation\ConstraintInterface; -use Tomaj\NetteApi\Test\Input\Fixtures\Priority; -use Tomaj\NetteApi\Test\Input\Fixtures\Separate\NoteHandler; -use Tomaj\NetteApi\Test\Input\Fixtures\Separate\NoteInput; use Tomaj\NetteApi\Validation\Email; use Tomaj\NetteApi\Validation\Length; use Tomaj\NetteApi\Validation\Pattern; use Tomaj\NetteApi\Validation\Range; -final class CompilerBranchTest extends TestCase +final class DtoAttributeTest extends TestCase { - protected function setUp(): void - { - DtoMetadataRegistry::reset(); - } - - public function testQueryBeforeBodyStillReadsTheBody(): void - { - $metadata = DtoCompiler::compile(QueryThenBodyHandler::class); - $this->assertTrue($metadata->readsBody); - $this->assertTrue($metadata->bodyRequired); - $this->assertSame('email', $metadata->firstBody); - } - - public function testHandlerAndDtoFilesAreBothRecorded(): void - { - $files = array_map(realpath(...), DtoCompiler::compile(NoteHandler::class)->files); - $this->assertContains(realpath(new \ReflectionClass(NoteHandler::class)->getFileName() ?: ''), $files); - $this->assertContains(realpath(new \ReflectionClass(NoteInput::class)->getFileName() ?: ''), $files); - } - public function testCompileFailuresNameTheExactProblem(): void { $this->assertCompileFails(MissingDtoHandler::class, "DTO 'MissingDto\\Nope' does not exist"); @@ -98,7 +61,6 @@ public function testAcceptedShapes(): void $this->assertSame('name', DtoCompiler::compile(BoomThenQueryHandler::class)->fields[0]->externalName); $varList = DtoCompiler::compile(VarListHandler::class)->fields[0]; $this->assertSame('string', $varList->listItem); - $this->assertTrue($varList->listItemBuiltin); $priorities = DtoCompiler::compile(PriorityListHandler::class)->fields[0]->item; $this->assertInstanceOf(Field::class, $priorities); $this->assertSame(Priority::class, $priorities->enumClass); @@ -120,118 +82,6 @@ public function testAcceptedShapes(): void $this->assertSame(['type' => 'string'], $plain->casterSchema, 'without a hint the wire value is a string'); } - public function testSchemaTypes(): void - { - $float = SchemaBuilder::build(DtoCompiler::compile(FloatRangeHandler::class)->fields[0], true); - $this->assertSame('number', $float['type']); - $bool = SchemaBuilder::build(DtoCompiler::compile(BoolHandler::class)->fields[0], true); - $this->assertSame('boolean', $bool['type']); - $date = SchemaBuilder::build(DtoCompiler::compile(DateHintHandler::class)->fields[0], true); - $this->assertSame('string', $date['type']); - $this->assertArrayNotHasKey('format', $date); - } - - public function testImportDropsNonStringsAndReindexes(): void - { - $export = DtoCompiler::compile(ListUsersHandler::class)->export(); - $export['contentTypes'] = [0 => MediaTypes::JSON, 2 => MediaTypes::FORM]; - $export['files'] = [0 => '/tmp/a.php', 1 => 5, 2 => '/tmp/b.php']; - $imported = DtoMetadata::import($export); - $this->assertSame([MediaTypes::JSON, MediaTypes::FORM], $imported->contentTypes); - $this->assertTrue(array_is_list($imported->contentTypes)); - $this->assertSame(['/tmp/a.php', '/tmp/b.php'], $imported->files); - } - - public function testEnumRoundTripRejectsAForeignMarker(): void - { - $restored = ValueExport::import(['__netteApi' => 'enum', 'class' => Priority::class, 'value' => 2]); - $this->assertSame(Priority::High, $restored); - $notAnEnum = ValueExport::import(['__netteApi' => 'other', 'class' => Priority::class, 'value' => 2]); - $this->assertIsArray($notAnEnum); - } - - public function testEndpointMessagesUseTheRealUrl(): void - { - $this->assertSame('v1/users', EndpointTemplate::normalize('/api/v1/users/', '1')); - foreach (['v1/x{id}', 'v1/{id}x'] as $url) { - try { - EndpointTemplate::assert($url, [], 'Handler'); - $this->fail($url); - } catch (\LogicException $exception) { - $this->assertStringContainsString($url, $exception->getMessage()); - } - } - try { - EndpointTemplate::assert('v1/users/{id}/', [], 'Handler'); - $this->fail('slash'); - } catch (\LogicException $exception) { - $this->assertStringContainsString("endpoint URL 'v1/users/{id}'", $exception->getMessage()); - $this->assertStringNotContainsString("endpoint URL 'v1/users/{id}/'", $exception->getMessage()); - } - try { - EndpointTemplate::assert('v1/{id}/x/{id}/y/{id}/', ['id'], 'Handler'); - $this->fail('duplicate'); - } catch (\LogicException $exception) { - $this->assertStringContainsString('repeats {id}.', $exception->getMessage()); - $this->assertStringContainsString("endpoint URL 'v1/{id}/x/{id}/y/{id}'", $exception->getMessage()); - } - try { - EndpointTemplate::assert('v1/users/{id-1}/', [], 'Handler'); - $this->fail('malformed'); - } catch (\LogicException $exception) { - $this->assertStringContainsString("endpoint URL 'v1/users/{id-1}'", $exception->getMessage()); - $this->assertStringNotContainsString('{id-1}/', $exception->getMessage()); - } - EndpointTemplate::assertDisjoint(['GET' => ['v1/static', 'v1/users/{id}', 'v1/orders/{id}']]); - try { - EndpointTemplate::assertDisjoint(['GET' => ['v1/users/{id}/', 'v1/users/{slug}/']]); - $this->fail('overlap'); - } catch (\LogicException $exception) { - $this->assertStringContainsString("endpoints 'v1/users/{id}' and 'v1/users/{slug}'", $exception->getMessage()); - } - } - - public function testContainerKeepsTypedHandlersAfterAPlainOneAndRejectsOverlap(): void - { - $container = ContainerFactory::create(<<<'NEON' -services: - listUsers: Tomaj\NetteApi\Test\Input\Fixtures\ListUsersHandler -api: - endpoints: - - {method: GET, version: 1, package: ping, handler: Tomaj\NetteApi\Handlers\AlwaysOkHandler} - - {method: GET, version: 1, package: people, action: list, handler: @listUsers} - - {method: POST, version: 1, package: notes, handler: \Tomaj\NetteApi\Test\Input\Fixtures\Separate\NoteHandler()} -NEON); - $container->initialize(); - $this->assertTrue(DtoMetadataRegistry::installs(ListUsersHandler::class)); - $this->assertTrue(DtoMetadataRegistry::installs(NoteHandler::class)); - $this->assertInstanceOf(AlwaysOkHandler::class, $container->getByType(AlwaysOkHandler::class)); - - $compiler = new Compiler(); - $compiler->addExtension('api', new NetteApiExtension()); - $compiler->addConfig([ - 'api' => [ - 'endpoints' => [[ - 'method' => 'POST', - 'version' => 1, - 'package' => 'notes', - 'handler' => NoteHandler::class, - ]], - ], - ]); - $compiler->compile(); - $this->assertStringContainsString('NoteInput.php', serialize($compiler->exportDependencies())); - - $this->expectException(\LogicException::class); - $this->expectExceptionMessage('can match the same request'); - ContainerFactory::create(<<<'NEON' -api: - endpoints: - - {method: GET, version: 1, package: users, action: '{id}', handler: Tomaj\NetteApi\Test\Input\IdOnlyHandler} - - {method: GET, version: 1, package: users, action: '{slug}', handler: Tomaj\NetteApi\Test\Input\SlugOnlyHandler} -NEON); - } - public function testWrongConstraintHintsAndFileListTypes(): void { $this->assertCompileFails(BadFileListHandler::class, 'list'); @@ -252,100 +102,6 @@ public function testWrongConstraintHintsAndFileListTypes(): void $this->assertCompileFails(FileListHandler::class, 'Uploads are read only on the root DTO'); } - public function testConstraintAndBodyErrorsStayOnTheirFields(): void - { - $_GET = []; - RequestInput::reset(); - $ok = new ListUsersHandler()->params()[0]->validate(); - $this->assertInstanceOf(ValidationResult::class, $ok); - - RequestInput::reset(); - $_GET = ['page' => '1a', 'limit' => '0']; - $errors = $this->errors(new ListUsersHandler()); - $this->assertSame(['Value must be an integer'], $errors['page']); - $this->assertSame(['Value must be between 1 and 100'], $errors['limit']); - - RequestInput::reset(); - $_SERVER['CONTENT_TYPE'] = 'application/json'; - $_SERVER['REQUEST_METHOD'] = 'POST'; - RequestInput::setRawBody('{"customerEmail":'); - $bodyErrors = []; - foreach (new CreateOrderHandler()->params() as $param) { - $result = $param->validate(); - if (!$result->isOk()) { - $bodyErrors[$param->getKey()] = $result->getErrors(); - } - } - $this->assertArrayHasKey('body', $bodyErrors['customerEmail']); - $this->assertArrayNotHasKey('body', $bodyErrors['address'] ?? []); - - RequestInput::reset(); - RequestInput::reset(); - $_GET = ['page' => '1a']; - $both = $this->errors(new QueryThenBodyHandler()); - $this->assertArrayHasKey('page', $both); - $this->assertArrayHasKey('email', $both); - - RequestInput::reset(); - $_SERVER['CONTENT_TYPE'] = 'application/json'; - $_SERVER['REQUEST_METHOD'] = 'POST'; - $_POST = []; - RequestInput::setRawBody(''); - $emptyBody = $this->errors(new CreateOrderHandler()); - $this->assertArrayHasKey('customerEmail', $emptyBody); - $this->assertArrayNotHasKey('body', $emptyBody); - - RequestInput::reset(); - $_SERVER['REQUEST_METHOD'] = 'GET'; - $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; - $_POST = ['customerEmail' => 'ada@example.com', 'address' => ['street' => 'Main 1', 'postalCode' => '81101'], 'items' => [['sku' => 'A', 'quantity' => 1]]]; - RequestInput::setRawBody(''); - $this->assertSame('ada@example.com', $this->payload(new CreateOrderHandler())['email']); - - $_GET = ['name' => 'ab']; - $_SERVER['REQUEST_METHOD'] = 'GET'; - unset($_SERVER['CONTENT_TYPE']); - $length = $this->errors(new TwoConstraintHandler()); - $this->assertCount(2, $length['name']); - } - - public function testGeneratedParamsExposeDefaultEnumAndExamples(): void - { - $params = new ListUsersHandler()->params(); - $this->assertSame(1, $params[0]->getDefault()); - $values = $params[2]->getAvailableValues(); - $this->assertIsArray($values); - $this->assertContains('active', $values); - $this->assertContains('disabled', $values); - $this->assertTrue($params[0]->validate()->isOk()); - $examples = new TwoExampleParamHandler()->params()[0]->getExamples(); - $this->assertCount(2, $examples); - $this->assertArrayHasKey('one', $examples); - $this->assertArrayHasKey('two', $examples); - } - - /** - * @return array - */ - private function payload(object $handler): array - { - $processor = new ParamsProcessor($handler->params()); - $this->assertFalse($processor->isError(), (string) json_encode($processor->getErrors())); - - return $handler->handle($processor->getValues())->getPayload(); - } - - /** - * @return array> - */ - private function errors(object $handler): array - { - $processor = new ParamsProcessor($handler->params()); - $this->assertTrue($processor->isError()); - - return $processor->getErrors(); - } - private function assertCompileFails(string $handler, string $needle): void { try { @@ -357,23 +113,6 @@ private function assertCompileFails(string $handler, string $needle): void } } -final readonly class QueryThenBodyInput -{ - public function __construct( - #[Query] public int $page, - #[Body] public string $email, - ) { - } -} - -final class QueryThenBodyHandler extends TypedHandler -{ - public function handleDto(QueryThenBodyInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - final class MissingDtoHandler extends TypedHandler { public function handleDto(Nope $input): ResponseInterface @@ -573,21 +312,6 @@ public function handleDto(UnknownListItemInput $input): ResponseInterface } } -final readonly class FloatRangeInput -{ - public function __construct(#[Query] #[Range(min: 0.5, max: 2.5)] public float $ratio = 1.0) - { - } -} - -final class FloatRangeHandler extends TypedHandler -{ - public function handleDto(FloatRangeInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - final readonly class StringLengthInput { public function __construct(#[Query] #[Length(min: 1, max: 3)] public string $name = 'ab') @@ -633,21 +357,6 @@ public function handleDto(EmailPinInput $input): ResponseInterface } } -final readonly class BoolPinInput -{ - public function __construct(#[Query] public bool $flag = false) - { - } -} - -final class BoolHandler extends TypedHandler -{ - public function handleDto(BoolPinInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - final class IntForString implements CasterInterface { public function cast(mixed $value): int @@ -769,21 +478,6 @@ public function handleDto(ListDocCasterInput $input): ResponseInterface } } -final readonly class DateHintInput -{ - public function __construct(#[Query] #[Cast(DateFormat::class, 'd.m.Y')] public \DateTimeImmutable $day) - { - } -} - -final class DateHintHandler extends TypedHandler -{ - public function handleDto(DateHintInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - final class EmptyHintCaster implements CasterInterface, OpenApiCasterInterface { public function cast(mixed $value): string @@ -857,51 +551,6 @@ public function handleDto(NestedFileInput $input): ResponseInterface } } -final readonly class TwoExampleParamInput -{ - public function __construct(#[Query(examples: ['one' => 1, 'two' => 2])] public int $page = 1) - { - } -} - -final class TwoExampleParamHandler extends TypedHandler -{ - public function handleDto(TwoExampleParamInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class IdOnlyInput -{ - public function __construct(#[Path] public string $id) - { - } -} - -final class IdOnlyHandler extends TypedHandler -{ - public function handleDto(IdOnlyInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class SlugOnlyInput -{ - public function __construct(#[Path] public string $slug) - { - } -} - -final class SlugOnlyHandler extends TypedHandler -{ - public function handleDto(SlugOnlyInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - final readonly class RangeOnStringPinInput { public function __construct(#[Query] #[Range(min: 1)] public string $name) @@ -1101,22 +750,3 @@ public function handleDto(FileListInput $input): ResponseInterface return new JsonApiResponse(200, []); } } - -final readonly class TwoConstraintInput -{ - public function __construct( - #[Query] - #[Length(min: 3)] - #[Pattern('/^z+$/')] - public string $name, - ) { - } -} - -final class TwoConstraintHandler extends TypedHandler -{ - public function handleDto(TwoConstraintInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} diff --git a/tests/Input/DtoCompilerTest.php b/tests/Input/DtoCompilerTest.php index f09d27b57..fe7ba1778 100644 --- a/tests/Input/DtoCompilerTest.php +++ b/tests/Input/DtoCompilerTest.php @@ -18,6 +18,13 @@ use Tomaj\NetteApi\Input\Query; use Tomaj\NetteApi\Response\ResponseInterface; use Tomaj\NetteApi\Validation\Range; +use Tomaj\NetteApi\Input\Header; +use Tomaj\NetteApi\Input\MediaTypes; +use Tomaj\NetteApi\Test\Input\Fixtures\AddressInput; +use Tomaj\NetteApi\Test\Input\Fixtures\AvatarHandler; +use Tomaj\NetteApi\Test\Input\Fixtures\DescribedHandler; +use Tomaj\NetteApi\Test\Input\Fixtures\Priority; +use Tomaj\NetteApi\Test\Input\Fixtures\TwoExamplesHandler; final class DtoCompilerTest extends TestCase { @@ -71,6 +78,102 @@ public function testMissingClass(): void $this->expectException(\LogicException::class); DtoCompiler::compile('Missing\\Handler'); } + + public function testMissingHandlerNamesTheClass(): void + { + $this->expectException(\LogicException::class); + $this->expectExceptionMessage("Typed handler 'Missing\\Handler' does not exist. Check the class name and the autoload section of composer.json."); + DtoCompiler::compile('Missing\\Handler'); + } + + public function testCycleNamesEveryStep(): void + { + try { + DtoCompiler::compile(CyclePinHandler::class); + $this->fail('cycle'); + } catch (\LogicException $exception) { + $this->assertSame( + sprintf( + 'DTO %s refers to itself (%s -> %s). Nested DTOs cannot form a cycle; keep the nesting one way.', + CyclePinInput::class, + CyclePinInput::class, + CyclePinInput::class, + ), + $exception->getMessage(), + ); + } + } + + public function testDeclarationsThatCannotBeMapped(): void + { + $cases = [ + PrivateHandler::class => 'must be a public instance method', + StaticHandler::class => 'must be a public instance method', + StdClassReturnHandler::class => 'must return', + AbstractDtoHandler::class => 'cannot be an input DTO', + EnumDtoHandler::class => 'cannot be an input DTO', + InterfaceDtoHandler::class => 'cannot be an input DTO', + IterableHandler::class => 'has type iterable', + FileOnQueryHandler::class => 'needs #[File]', + BareFileUploadHandler::class => 'needs #[File]', + ]; + foreach ($cases as $handler => $needle) { + try { + DtoCompiler::compile($handler); + $this->fail($handler); + } catch (\LogicException $exception) { + $this->assertStringContainsString($needle, $exception->getMessage(), $handler); + } + } + + $examples = DtoCompiler::compile(TwoExamplesHandler::class)->fields[0]->examples; + $this->assertSame(['one' => 1, 'two' => 2], $examples); + + $twin = DtoCompiler::compile(TwinHandler::class); + $this->assertSame('left', $twin->firstBody); + $this->assertTrue($twin->readsBody); + $address = realpath(new \ReflectionClass(AddressInput::class)->getFileName() ?: ''); + $twinFiles = DtoCompiler::compileWithFiles(TwinHandler::class)['files']; + $this->assertCount(1, array_filter($twinFiles, static fn (string $file): bool => realpath($file) === $address)); + $this->assertSame(['id', 'slug'], DtoCompiler::compile(TwoPathsHandler::class)->pathNames()); + $this->assertSame( + [MediaTypes::JSON, MediaTypes::MULTIPART], + DtoCompiler::compile(AvatarHandler::class)->contentTypes, + ); + $described = DtoCompiler::compile(DescribedHandler::class); + $this->assertFalse($described->bodyRequired); + $this->assertTrue($described->readsBody); + $this->assertSame([MediaTypes::JSON], $described->contentTypes); + } + + public function testHeaderNamesCollideCaseInsensitively(): void + { + $this->expectException(\LogicException::class); + $this->expectExceptionMessage("HeaderCaseInput properties \$first and \$second both use the external name 'x-trace'"); + DtoCompiler::compile(HeaderCaseHandler::class); + } + + public function testHeaderAndQueryWithTheSameLetterCaseStillCollide(): void + { + $this->expectException(\LogicException::class); + $this->expectExceptionMessage("both use the external name 'trace'"); + DtoCompiler::compile(HeaderQueryHandler::class); + } + + public function testNativeListsAndObjectsCannotComeFromAPathOrHeader(): void + { + $this->assertCompileFails(HeaderListHandler::class, "HeaderListInput::\$tags reads #[Header], which is one string, so it cannot be list. Use a scalar type or split the string, for example #[Cast(Split::class, ',')]."); + } + + private function assertCompileFails(string $handler, string $needle): void + { + try { + DtoCompiler::compile($handler); + $this->fail($handler); + } catch (\LogicException $exception) { + $this->assertStringContainsString($needle, $exception->getMessage(), $handler); + } + } } final class MissingMethodHandler extends TypedHandler @@ -452,3 +555,207 @@ public function handleDto(CycleInput $input): ResponseInterface return new JsonApiResponse(200, []); } } + +final readonly class HeaderListInput +{ + /** @param list $tags */ + public function __construct(#[Header('X-Tags')] public array $tags = []) + { + } +} + +final class HeaderListHandler extends TypedHandler +{ + public function handleDto(HeaderListInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class CyclePinInput +{ + public function __construct(#[Body] public CyclePinInput $child) + { + } +} + +final class CyclePinHandler extends TypedHandler +{ + public function handleDto(CyclePinInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final class PrivateHandler extends TypedHandler +{ + private function handleDto(CyclePinInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final class StaticHandler extends TypedHandler +{ + public static function handleDto(CyclePinInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final class StdClassReturnHandler extends TypedHandler +{ + public function handleDto(CyclePinInput $input): \stdClass + { + return new \stdClass(); + } +} + +abstract readonly class AbstractPinInput +{ + public function __construct(#[Query] public string $name) + { + } +} + +final class AbstractDtoHandler extends TypedHandler +{ + public function handleDto(AbstractPinInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final class EnumDtoHandler extends TypedHandler +{ + public function handleDto(Priority $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +interface PinContract +{ +} + +final class InterfaceDtoHandler extends TypedHandler +{ + public function handleDto(PinContract $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class IterableInput +{ + public function __construct(#[Query] public iterable $name) + { + } +} + +final class IterableHandler extends TypedHandler +{ + public function handleDto(IterableInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class FileOnQueryInput +{ + public function __construct(#[Query] public FileUpload $file) + { + } +} + +final class FileOnQueryHandler extends TypedHandler +{ + public function handleDto(FileOnQueryInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BareFileUploadInput +{ + /** @param list $files */ + public function __construct(#[Query] public array $files) + { + } +} + +final class BareFileUploadHandler extends TypedHandler +{ + public function handleDto(BareFileUploadInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class TwinInput +{ + public function __construct( + #[Body] public AddressInput $left, + #[Body] public AddressInput $right, + ) { + } +} + +final class TwinHandler extends TypedHandler +{ + public function handleDto(TwinInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['street' => $input->left->street]); + } +} + +final readonly class TwoPathsInput +{ + public function __construct( + #[Path] public string $id, + #[Path] public string $slug, + ) { + } +} + +final class TwoPathsHandler extends TypedHandler +{ + public function handleDto(TwoPathsInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class HeaderCaseInput +{ + public function __construct( + #[Header('X-Trace')] public string $first, + #[Header('x-trace')] public string $second, + ) { + } +} + +final class HeaderCaseHandler extends TypedHandler +{ + public function handleDto(HeaderCaseInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class HeaderQueryInput +{ + public function __construct( + #[Header('trace')] public string $first, + #[Query('trace')] public string $second, + ) { + } +} + +final class HeaderQueryHandler extends TypedHandler +{ + public function handleDto(HeaderQueryInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} diff --git a/tests/Input/DtoConstructorTest.php b/tests/Input/DtoConstructorTest.php new file mode 100644 index 000000000..602ec7e2a --- /dev/null +++ b/tests/Input/DtoConstructorTest.php @@ -0,0 +1,341 @@ +assertCompileFails(SecretArgumentHandler::class, 'SecretArgumentInput::__construct() has the required parameter $secret that is not a promoted property'); + $this->assertCompileFails(VariadicArgumentHandler::class, 'VariadicArgumentInput::__construct() parameter $rest is variadic'); + $this->assertCompileFails(ReferenceArgumentHandler::class, 'ReferenceArgumentInput::__construct() parameter $page is passed by reference'); + $this->assertCount(1, DtoCompiler::compile(OptionalArgumentHandler::class)->fields); + } + + public function testSiblingDefaultsAreVisibleToConstraints(): void + { + $this->assertCount(2, DtoCompiler::compile(SiblingDefaultsHandler::class)->fields); + $this->assertCompileFails(BadSiblingDefaultsHandler::class, 'BadSiblingDefaultsInput::$right default does not satisfy #[SameAs]: Must equal left'); + } + + public function testDefaultsAfterARequiredFieldAreChecked(): void + { + $this->assertCompileFails(RequiredThenBadDefaultHandler::class, 'RequiredThenBadDefaultInput::$right default does not satisfy #[SameAs]'); + } + + public function testValidListDefaultsOfEveryItemType(): void + { + $fields = DtoCompiler::compile(ListDefaultsHandler::class)->fields; + // an int in a list default becomes a float, as the same value from a request would + $this->assertSame([[1.0, 2.5], [true], ['a'], [UserStatus::Active], ['x']], array_map(static fn (Field $field): mixed => $field->default, $fields)); + $this->assertCompileFails(BadFloatListDefaultHandler::class, 'default item 1 is string, but the property is list'); + $this->assertCompileFails(BadBoolListDefaultHandler::class, 'default item 0 is int, but the property is list'); + $this->assertCompileFails(BadStringListDefaultHandler::class, 'default item 0 is int, but the property is list'); + $this->assertCompileFails(BadEnumListDefaultHandler::class, 'default item 0 is string, but the property is list<' . UserStatus::class . '>'); + $this->assertCompileFails(BadCastListDefaultHandler::class, 'default item 0 is int, but the property is list'); + } + + public function testListDefaultItemsAreChecked(): void + { + $this->assertCompileFails(BadListDefaultHandler::class, "BadListDefaultInput::\$items default item 1 is string, but the property is list"); + $this->assertCompileFails(MapDefaultHandler::class, 'MapDefaultInput::$items default must be a list'); + } + + public function testIntItemsOfAFloatListDefaultAreFloats(): void + { + $default = DtoCompiler::compile(FloatListDefaultHandler::class)->fields[0]->default; + $this->assertSame([1.0, 2.5, 3.0], $default); + } + + private function assertCompileFails(string $handler, string $needle): void + { + try { + DtoCompiler::compile($handler); + $this->fail($handler); + } catch (\LogicException $exception) { + $this->assertStringContainsString($needle, $exception->getMessage(), $handler); + } + } +} + +#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_PARAMETER)] +final readonly class SameAs implements ConstraintInterface +{ + public function __construct(private string $other) + { + } + + public function validate(mixed $value, ConstraintContext $context): ?string + { + return $value === $context->value($this->other) ? null : 'Must equal ' . $this->other; + } +} + +final readonly class SiblingDefaultsInput +{ + public function __construct( + #[Query] public string $left = 'same', + #[Query] #[SameAs('left')] public string $right = 'same', + ) { + } +} + +final class SiblingDefaultsHandler extends TypedHandler +{ + public function handleDto(SiblingDefaultsInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BadSiblingDefaultsInput +{ + public function __construct( + #[Query] #[SameAs('left')] public string $right = 'other', + #[Query] public string $left = 'same', + ) { + } +} + +final class BadSiblingDefaultsHandler extends TypedHandler +{ + public function handleDto(BadSiblingDefaultsInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BadListDefaultInput +{ + /** @param list $items */ + public function __construct(#[Query] public array $items = [1, 'not-an-int']) + { + } +} + +final class BadListDefaultHandler extends TypedHandler +{ + public function handleDto(BadListDefaultInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class MapDefaultInput +{ + /** @param list $items */ + public function __construct(#[Query] public array $items = ['a' => 1]) + { + } +} + +final class MapDefaultHandler extends TypedHandler +{ + public function handleDto(MapDefaultInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class SecretArgumentInput +{ + public function __construct(#[Query] public int $page, string $secret) + { + unset($secret); + } +} + +final class SecretArgumentHandler extends TypedHandler +{ + public function handleDto(SecretArgumentInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class VariadicArgumentInput +{ + public function __construct(#[Query] public int $page, string ...$rest) + { + unset($rest); + } +} + +final class VariadicArgumentHandler extends TypedHandler +{ + public function handleDto(VariadicArgumentInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final class ReferenceArgumentInput +{ + public function __construct(#[Query] public int &$page) + { + } +} + +final class ReferenceArgumentHandler extends TypedHandler +{ + public function handleDto(ReferenceArgumentInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class RequiredThenBadDefaultInput +{ + public function __construct( + #[Query] public string $left, + #[Query] #[SameAs('left')] public string $right = 'x', + ) { + } +} + +final class RequiredThenBadDefaultHandler extends TypedHandler +{ + public function handleDto(RequiredThenBadDefaultInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class ListDefaultsInput +{ + /** + * @param list $floats + * @param list $flags + * @param list $names + * @param list $statuses + * @param list $split + */ + public function __construct( + #[Query] public array $floats = [1, 2.5], + #[Query] public array $flags = [true], + #[Query] public array $names = ['a'], + #[Query] public array $statuses = [UserStatus::Active], + #[Query] #[Cast(Split::class, ',')] public array $split = ['x'], + ) { + } +} + +final class ListDefaultsHandler extends TypedHandler +{ + public function handleDto(ListDefaultsInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BadFloatListDefaultInput +{ + /** @param list $items */ + public function __construct(#[Query] public array $items = [1.5, 'x']) + { + } +} + +final class BadFloatListDefaultHandler extends TypedHandler +{ + public function handleDto(BadFloatListDefaultInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BadBoolListDefaultInput +{ + /** @param list $items */ + public function __construct(#[Query] public array $items = [1]) + { + } +} + +final class BadBoolListDefaultHandler extends TypedHandler +{ + public function handleDto(BadBoolListDefaultInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BadStringListDefaultInput +{ + /** @param list $items */ + public function __construct(#[Query] public array $items = [1]) + { + } +} + +final class BadStringListDefaultHandler extends TypedHandler +{ + public function handleDto(BadStringListDefaultInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BadEnumListDefaultInput +{ + /** @param list $items */ + public function __construct(#[Query] public array $items = ['active']) + { + } +} + +final class BadEnumListDefaultHandler extends TypedHandler +{ + public function handleDto(BadEnumListDefaultInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BadCastListDefaultInput +{ + /** @param list $items */ + public function __construct(#[Query] #[Cast(Split::class, ',')] public array $items = [1]) + { + } +} + +final class BadCastListDefaultHandler extends TypedHandler +{ + public function handleDto(BadCastListDefaultInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class FloatListDefaultInput +{ + /** @param list $weights */ + public function __construct(#[Query] public array $weights = [1, 2.5, 3]) + { + } +} + +final class FloatListDefaultHandler extends TypedHandler +{ + public function handleDto(FloatListDefaultInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} diff --git a/tests/Input/DtoHandlerTest.php b/tests/Input/DtoHandlerTest.php index 76faa5528..8a2f3a579 100644 --- a/tests/Input/DtoHandlerTest.php +++ b/tests/Input/DtoHandlerTest.php @@ -17,6 +17,18 @@ use Tomaj\NetteApi\Test\Input\Fixtures\ReportHandler; use Tomaj\NetteApi\Test\Input\Fixtures\ScheduleHandler; use Tomaj\NetteApi\Test\Input\Fixtures\UserDetailHandler; +use Tomaj\NetteApi\Handlers\TypedHandler; +use Tomaj\NetteApi\Input\Body; +use Tomaj\NetteApi\Input\DtoMetadataRegistry; +use Tomaj\NetteApi\Input\Query; +use Tomaj\NetteApi\Response\JsonApiResponse; +use Tomaj\NetteApi\Response\ResponseInterface; +use Tomaj\NetteApi\Test\Input\Fixtures\OptionalArgumentHandler; +use Tomaj\NetteApi\Test\Input\Fixtures\Priority; +use Tomaj\NetteApi\Test\Input\Fixtures\QueryThenBodyHandler; +use Tomaj\NetteApi\ValidationResult\ValidationResult; +use Tomaj\NetteApi\Validation\Length; +use Tomaj\NetteApi\Validation\Pattern; final class DtoHandlerTest extends TestCase { @@ -29,6 +41,7 @@ protected function setUp(): void unset($_SERVER['CONTENT_TYPE'], $_SERVER['HTTP_X_REQUEST_ID']); RequestInput::reset(); PathValues::reset(); + DtoMetadataRegistry::reset(); } public function testQueryDefaultsEnumAndStrictInteger(): void @@ -337,4 +350,351 @@ private function processor(object $handler): ParamsProcessor { return new ParamsProcessor($handler->params()); } + + public function testRfc3339AcceptsLowercaseSeparators(): void + { + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + foreach (['2024-05-01t10:00:00z' => '2024-05-01T10:00:00+00:00', '2024-05-01t10:00:00.5+02:00' => '2024-05-01T10:00:00+02:00'] as $input => $expected) { + RequestInput::reset(); + RequestInput::setRawBody((string) json_encode(['at' => $input])); + $processor = new ParamsProcessor(new DateHandler()->params()); + $this->assertFalse($processor->isError(), $input); + $at = $processor->getValues()['at']; + $this->assertInstanceOf(\DateTimeImmutable::class, $at); + $this->assertSame($expected, $at->format('c')); + } + + RequestInput::reset(); + RequestInput::setRawBody('{"at":"2016-12-31T23:59:60Z"}'); + $this->assertTrue(new ParamsProcessor(new DateHandler()->params())->isError()); + } + + public function testLengthOnAListIsCheckedBeforeItsItems(): void + { + $_GET = ['ids' => ['x', 'y', 'z']]; + $this->assertSame(['ids' => ['Value must have between 1 and 2 items']], $this->errors(new LengthListHandler())); + RequestInput::reset(); + $_GET = ['ids' => []]; + $this->assertSame(['ids' => ['Value must have between 1 and 2 items']], $this->errors(new LengthListHandler())); + RequestInput::reset(); + $_GET = ['ids' => ['1', '2'], 'min' => ['x']]; + $this->assertSame(['min[0]' => ['Value must be an integer']], $this->errors(new LengthListHandler())); + RequestInput::reset(); + $_GET = ['ids' => ['1'], 'min' => ['4', '5', '6']]; + $this->assertSame(['ids' => [1], 'min' => [4, 5, 6]], $this->payload(new LengthListHandler())); + } + + public function testDtoBoundaryRejectsSignedZeroGarbage(): void + { + $_GET = ['page' => '--0']; + $this->assertArrayHasKey('page', $this->errors(new OptionalArgumentHandler())); + } + + public function testFieldErrorsStayOnTheirOwnName(): void + { + $params = new PrefixHandler()->params(); + $byName = []; + foreach ($params as $param) { + $result = $param->validate(); + $this->assertFalse($result->isOk()); + $byName[$param->getKey()] = $result->getErrors(); + } + $this->assertSame(['a' => ['Field is required']], $byName['a']); + $this->assertSame(['ab' => ['Field is required']], $byName['ab']); + $this->assertSame('', $params[0]->getDescription()); + $page = new ListUsersHandler()->params()[0]; + $this->assertSame('Page number', $page->getDescription()); + $this->assertFalse($page->isMulti()); + $items = new CreateOrderHandler()->params()[2]; + $this->assertTrue($items->isMulti()); + $this->assertNotSame([], $items->getContentTypes()); + } + + public function testMalformedJsonStillChecksQueryFields(): void + { + $_GET = ['page' => '1a']; + RequestInput::setRawBody('{"email":'); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + $errors = $this->errors(new QueryAfterBodyHandler()); + $this->assertStringStartsWith('Syntax error', $errors['body'][0]); + $this->assertSame(['Value must be an integer'], $errors['page']); + } + + public function testInvalidIntegerKeepsTheDefaultForTheValue(): void + { + $_GET = ['page' => '1a']; + $page = new ListUsersHandler()->params()[0]; + $page->validate(); + $this->assertSame(1, $page->getValue()); + } + + public function testEveryNestedErrorIsReported(): void + { + $this->json([ + 'customerEmail' => 'ada@example.com', + 'address' => ['street' => '', 'postalCode' => 'abc'], + 'items' => [ + ['sku' => 'A', 'quantity' => 0], + ['sku' => 'B', 'quantity' => 0], + ], + ]); + $errors = $this->errors(new CreateOrderHandler()); + $this->assertArrayHasKey('address.street', $errors); + $this->assertArrayHasKey('address.postalCode', $errors); + $this->assertArrayHasKey('items[0].quantity', $errors); + $this->assertArrayHasKey('items[1].quantity', $errors); + + RequestInput::reset(); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + RequestInput::setRawBody('{"customerEmail":"ada@example.com","address":{},"items":[{"sku":"A","quantity":1}]}'); + $emptyObject = $this->errors(new CreateOrderHandler()); + $this->assertSame(['Field is required'], $emptyObject['address.street']); + $this->assertArrayNotHasKey('address', $emptyObject); + + RequestInput::reset(); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + RequestInput::setRawBody('{"customerEmail":"ada@example.com","address":[],"items":[{"sku":"A","quantity":1}]}'); + $this->assertSame(['Value must be an object'], $this->errors(new CreateOrderHandler())['address']); + + RequestInput::reset(); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + RequestInput::setRawBody('{"customerEmail":"ada@example.com","address":{"street":"Main 1","postalCode":"81101"},"items":{}}'); + $this->assertSame(['Value must be a list'], $this->errors(new CreateOrderHandler())['items']); + + RequestInput::reset(); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + RequestInput::setRawBody('[]'); + $this->assertSame(['body' => ['Value must be an object']], $this->errors(new CreateOrderHandler())); + } + + public function testEmptyObjectAndFloat(): void + { + RequestInput::setRawBody('{}'); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + $errors = $this->errors(new CreateOrderHandler()); + $this->assertArrayNotHasKey('body', $errors); + $this->assertSame(['Field is required'], $errors['customerEmail']); + + RequestInput::reset(); + $_GET = ['ratio' => '1.5']; + $this->assertEqualsWithDelta(1.5, $this->payload(new FloatHandler())['ratio'], PHP_FLOAT_EPSILON); + } + + public function testConstraintAndBodyErrorsStayOnTheirFields(): void + { + $_GET = []; + RequestInput::reset(); + $ok = new ListUsersHandler()->params()[0]->validate(); + $this->assertInstanceOf(ValidationResult::class, $ok); + + RequestInput::reset(); + $_GET = ['page' => '1a', 'limit' => '0']; + $errors = $this->errors(new ListUsersHandler()); + $this->assertSame(['Value must be an integer'], $errors['page']); + $this->assertSame(['Value must be between 1 and 100'], $errors['limit']); + + RequestInput::reset(); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + RequestInput::setRawBody('{"customerEmail":'); + $bodyErrors = []; + foreach (new CreateOrderHandler()->params() as $param) { + $result = $param->validate(); + if (!$result->isOk()) { + $bodyErrors[$param->getKey()] = $result->getErrors(); + } + } + $this->assertArrayHasKey('body', $bodyErrors['customerEmail']); + $this->assertArrayNotHasKey('body', $bodyErrors['address'] ?? []); + + RequestInput::reset(); + RequestInput::reset(); + $_GET = ['page' => '1a']; + $both = $this->errors(new QueryThenBodyHandler()); + $this->assertArrayHasKey('page', $both); + $this->assertArrayHasKey('email', $both); + + RequestInput::reset(); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_POST = []; + RequestInput::setRawBody(''); + $emptyBody = $this->errors(new CreateOrderHandler()); + $this->assertArrayHasKey('customerEmail', $emptyBody); + $this->assertArrayNotHasKey('body', $emptyBody); + + RequestInput::reset(); + $_SERVER['REQUEST_METHOD'] = 'GET'; + $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; + $_POST = ['customerEmail' => 'ada@example.com', 'address' => ['street' => 'Main 1', 'postalCode' => '81101'], 'items' => [['sku' => 'A', 'quantity' => 1]]]; + RequestInput::setRawBody(''); + $this->assertSame('ada@example.com', $this->payload(new CreateOrderHandler())['email']); + + $_GET = ['name' => 'ab']; + $_SERVER['REQUEST_METHOD'] = 'GET'; + unset($_SERVER['CONTENT_TYPE']); + $length = $this->errors(new TwoConstraintHandler()); + $this->assertCount(2, $length['name']); + } + + public function testGeneratedParamsExposeDefaultEnumAndExamples(): void + { + $params = new ListUsersHandler()->params(); + $this->assertSame(1, $params[0]->getDefault()); + $values = $params[2]->getAvailableValues(); + $this->assertIsArray($values); + $this->assertContains('active', $values); + $this->assertContains('disabled', $values); + $this->assertTrue($params[0]->validate()->isOk()); + $examples = new TwoExampleParamHandler()->params()[0]->getExamples(); + $this->assertCount(2, $examples); + $this->assertArrayHasKey('one', $examples); + $this->assertArrayHasKey('two', $examples); + } + + public function testListOfEnumsOffersTheItemValues(): void + { + $params = DtoMetadataRegistry::forHandler(PriorityQueryListHandler::class)->inputParams(); + $this->assertSame([1 => 1, 2 => 2], $params[0]->getAvailableValues()); + } +} + +final readonly class DateInput +{ + public function __construct( + #[Body] public \DateTimeImmutable $at, + ) { + } +} + +final class DateHandler extends TypedHandler +{ + public function handleDto(DateInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class LengthListInput +{ + /** + * @param list $ids + * @param list $min + */ + public function __construct( + #[Query] #[Length(min: 1, max: 2)] public array $ids, + #[Query] #[Length(min: 1)] public array $min = [1], + ) { + } +} + +final class LengthListHandler extends TypedHandler +{ + public function handleDto(LengthListInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['ids' => $input->ids, 'min' => $input->min]); + } +} + +final readonly class PrefixInput +{ + public function __construct( + #[Query(description: '')] public string $a, + #[Query] public string $ab, + ) { + } +} + +final class PrefixHandler extends TypedHandler +{ + public function handleDto(PrefixInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class QueryAfterBodyInput +{ + public function __construct( + #[Body] public string $email, + #[Query] public int $page = 1, + ) { + } +} + +final class QueryAfterBodyHandler extends TypedHandler +{ + public function handleDto(QueryAfterBodyInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['page' => $input->page]); + } +} + +final readonly class FloatInput +{ + public function __construct(#[Query] public float $ratio) + { + } +} + +final class FloatHandler extends TypedHandler +{ + public function handleDto(FloatInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['ratio' => $input->ratio]); + } +} + +final readonly class TwoExampleParamInput +{ + public function __construct(#[Query(examples: ['one' => 1, 'two' => 2])] public int $page = 1) + { + } +} + +final class TwoExampleParamHandler extends TypedHandler +{ + public function handleDto(TwoExampleParamInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class TwoConstraintInput +{ + public function __construct( + #[Query] + #[Length(min: 3)] + #[Pattern('/^z+$/')] + public string $name, + ) { + } +} + +final class TwoConstraintHandler extends TypedHandler +{ + public function handleDto(TwoConstraintInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class PriorityQueryListInput +{ + /** @param list $priorities */ + public function __construct(#[Query] public array $priorities = []) + { + } +} + +final class PriorityQueryListHandler extends TypedHandler +{ + public function handleDto(PriorityQueryListInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } } diff --git a/tests/Input/DtoMetadataTest.php b/tests/Input/DtoMetadataTest.php new file mode 100644 index 000000000..25a55efe8 --- /dev/null +++ b/tests/Input/DtoMetadataTest.php @@ -0,0 +1,114 @@ + $metadata, 'files' => $files] = DtoCompiler::compileWithFiles(CreateOrderHandler::class); + $expected = json_decode((string) file_get_contents(__DIR__ . '/Fixtures/create-order-export.json'), true); + $this->assertSame($expected, self::snapshot($metadata)); + $this->assertTrue(array_is_list($files)); + $this->assertContains(realpath(__DIR__ . '/Fixtures/Handlers.php') ?: '', array_map(realpath(...), $files)); + } + + /** + * Compiled metadata as plain data: objects become their class and properties, enum cases their class and value. + */ + private static function snapshot(mixed $value): mixed + { + if ($value instanceof \UnitEnum) { + return ['enum' => $value::class, 'value' => $value instanceof \BackedEnum ? $value->value : $value->name]; + } + if (is_object($value)) { + return ['@class' => $value::class] + array_map(self::snapshot(...), get_object_vars($value)); + } + + return is_array($value) ? array_map(self::snapshot(...), $value) : $value; + } + + public function testSerializedMetadataRoundTrips(): void + { + $compiled = DtoCompiler::compile(CreateOrderHandler::class); + $payload = serialize($compiled); + $this->assertStringNotContainsString('Handlers.php', $payload, 'compile-time file paths stay out of the container'); + $this->assertEquals($compiled, unserialize($payload)); + + $restored = unserialize(serialize(DtoCompiler::compile(TwoExamplesHandler::class))); + $this->assertInstanceOf(DtoMetadata::class, $restored); + $this->assertSame(['one' => 1, 'two' => 2], $restored->fields[0]->examples); + $priority = unserialize(serialize(DtoCompiler::compile(ListUsersHandler::class))); + $this->assertInstanceOf(DtoMetadata::class, $priority); + $this->assertSame([1, 2], $priority->fields[3]->enumValues); + } + + public function testQueryOnlyHandlerDoesNotReadABody(): void + { + $metadata = DtoCompiler::compile(ListUsersHandler::class); + $this->assertFalse($metadata->readsBody); + $this->assertFalse($metadata->bodyRequired); + $this->assertNull($metadata->firstBody); + $this->assertFalse($metadata->fields[0]->enumInt); + $this->assertTrue($metadata->fields[3]->enumInt); + $this->assertSame([1, 2], $metadata->fields[3]->enumValues); + } + + public function testQueryBeforeBodyStillReadsTheBody(): void + { + $metadata = DtoCompiler::compile(QueryThenBodyHandler::class); + $this->assertTrue($metadata->readsBody); + $this->assertTrue($metadata->bodyRequired); + $this->assertSame('email', $metadata->firstBody); + } + + public function testHandlerAndDtoFilesAreBothRecorded(): void + { + $files = array_map(realpath(...), DtoCompiler::compileWithFiles(NoteHandler::class)['files']); + $this->assertContains(realpath(new \ReflectionClass(NoteHandler::class)->getFileName() ?: ''), $files); + $this->assertContains(realpath(new \ReflectionClass(NoteInput::class)->getFileName() ?: ''), $files); + } + + public function testEveryReflectedDependencyRebuildsTheContainer(): void + { + $files = array_map(basename(...), DtoCompiler::compileWithFiles(DependencyHandler::class)['files']); + foreach (['DependencyHandler.php', 'DependencyInput.php', 'DependencyParentInput.php', 'DependencyCaster.php', 'DependencyEnum.php', 'DependencyItemEnum.php', 'DependencyConstraint.php', 'DependencyTrait.php', 'DependencyNestedTrait.php', 'DependencyParentTrait.php'] as $file) { + $this->assertContains($file, $files); + } + $this->assertSame(array_values(array_unique($files)), $files); + } + + public function testSameInstanceIsReusedUntilReset(): void + { + $first = DtoMetadataRegistry::forHandler(ListUsersHandler::class); + $again = DtoMetadataRegistry::forHandler(ListUsersHandler::class); + $this->assertSame($first, $again); + + $installed = new DtoMetadata($first->handler, $first->class, $first->fields, $first->contentTypes, $first->bodyRequired, $first->readsBody, 'from-install'); + DtoMetadataRegistry::reset(); + DtoMetadataRegistry::install([ListUsersHandler::class => serialize($installed)]); + $this->assertTrue(DtoMetadataRegistry::installs(ListUsersHandler::class)); + $this->assertSame('from-install', DtoMetadataRegistry::forHandler(ListUsersHandler::class)->firstBody); + $this->assertFalse(DtoMetadataRegistry::installs(CreateOrderHandler::class)); + $this->assertSame(CreateOrderHandler::class, DtoMetadataRegistry::forHandler(CreateOrderHandler::class)->handler); + } +} diff --git a/tests/Input/DtoPhpDocTest.php b/tests/Input/DtoPhpDocTest.php new file mode 100644 index 000000000..0690b2a44 --- /dev/null +++ b/tests/Input/DtoPhpDocTest.php @@ -0,0 +1,172 @@ +assertSame('int', DtoCompiler::compile(VarFallbackHandler::class)->fields[0]->listItem); + } + + public function testEveryCommonPhpDocSpellingOfAListIsRead(): void + { + $fields = DtoCompiler::compile(DocFormsHandler::class)->fields; + + $this->assertSame( + ['string', 'string', 'string', 'string', 'string', 'string', 'int', 'float'], + array_map(static fn (Field $field): string => (string) $field->listItem, $fields), + ); + } + + /** + * @return \Iterator, string}> + */ + public static function descriptions(): \Iterator + { + yield 'var with a description' => [VarDescriptionHandler::class, 'string']; + yield 'var without a space before the end of the comment' => [VarTightHandler::class, 'int']; + yield 'non-empty-list with a description' => [VarNonEmptyHandler::class, 'string']; + yield 'phpstan var with a nested generic and a description' => [VarGenericHandler::class, 'int']; + } + + /** + * @param class-string $handler + */ + #[DataProvider('descriptions')] + public function testAVarTypeMayBeFollowedByADescription(string $handler, string $item): void + { + $this->assertSame($item, DtoCompiler::compile($handler)->fields[0]->listItem); + } +} + +final readonly class DocFormsInput +{ + /** + * @param list|null $a + * @param ?list $b + * @param null|list $c + * @param string[] $d + * @param non-empty-list $e + * @param list $f + * @phpstan-param list $g + * @psalm-param list $h + */ + public function __construct( + #[Query] public ?array $a = null, + #[Query] public ?array $b = null, + #[Query] public ?array $c = null, + #[Query] public ?array $d = null, + #[Query] public ?array $e = null, + #[Query] public ?array $f = null, + #[Query] public array $g = [], + #[Query] public array $h = [], + ) { + } +} + +final class DocFormsHandler extends TypedHandler +{ + public function handleDto(DocFormsInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class VarFallbackInput +{ + /** @param $a */ + public function __construct( + /** @var list */ + #[Body] public array $a = [], + ) { + } +} + +final class VarFallbackHandler extends TypedHandler +{ + public function handleDto(VarFallbackInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class VarDescriptionInput +{ + public function __construct( + /** @var list Names of the things */ + #[Body] public array $names = [], + ) { + } +} + +final class VarDescriptionHandler extends TypedHandler +{ + public function handleDto(VarDescriptionInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class VarTightInput +{ + public function __construct( + /** @var list*/ + #[Body] public array $ids = [], + ) { + } +} + +final class VarTightHandler extends TypedHandler +{ + public function handleDto(VarTightInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class VarNonEmptyInput +{ + public function __construct( + /** @var non-empty-list Names of the things */ + #[Body] public array $names = ['a'], + ) { + } +} + +final class VarNonEmptyHandler extends TypedHandler +{ + public function handleDto(VarNonEmptyInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class VarGenericInput +{ + public function __construct( + /** @phpstan-var list Numbers: any of them */ + #[Body] public array $numbers = [], + ) { + } +} + +final class VarGenericHandler extends TypedHandler +{ + public function handleDto(VarGenericInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} diff --git a/tests/Input/DtoPropertyTypeTest.php b/tests/Input/DtoPropertyTypeTest.php new file mode 100644 index 000000000..379883f95 --- /dev/null +++ b/tests/Input/DtoPropertyTypeTest.php @@ -0,0 +1,806 @@ + + */ + public static function invalidHandlers(): \Iterator + { + yield 'nested dto in query' => [QueryDtoHandler::class, 'reads #[Query], which carries flat values']; + yield 'list of dto in query' => [QueryListHandler::class, 'cannot be list<']; + yield 'object default (date)' => [DateDefaultHandler::class, 'has a default of type DateTimeImmutable']; + yield 'object default (dto)' => [DtoDefaultHandler::class, 'has a default of type Tomaj\\NetteApi\\Test\\Input\\ListedInner']; + yield 'object default inside a list' => [ListObjectDefaultHandler::class, 'has a default of type']; + yield 'list of nullable items' => [NullableItemsHandler::class, 'one non-nullable type']; + yield 'list of unions' => [UnionItemsHandler::class, 'one non-nullable type']; + yield 'list of lists' => [ListOfListsHandler::class, 'one non-nullable type']; + yield 'associative array' => [AssocHandler::class, 'not a list']; + yield 'unreadable doc type' => [OtherDocHandler::class, 'Found `iterable`']; + yield 'DateTime' => [PlainDateTimeHandler::class, 'Use DateTimeImmutable']; + yield 'DateTimeInterface' => [DateInterfaceHandler::class, 'Use DateTimeImmutable']; + yield 'empty split separator' => [EmptySplitHandler::class, 'Its constructor is __construct(string $separator)']; + yield 'split into ints' => [SplitIntsHandler::class, 'Split gives list']; + yield 'list with a trailing union' => [TrailingUnionHandler::class, 'Found `list|string`']; + yield 'array of arrays' => [ArrayOfArraysHandler::class, 'not a list']; + yield 'brackets with a trailing union' => [BracketUnionHandler::class, 'Found `string[]|int`']; + yield 'array of lists' => [ArrayOfListsHandler::class, 'not a list']; + yield 'union before brackets' => [UnionBracketsHandler::class, 'Found `int|string[]`']; + yield 'generic of array' => [GenericOfArrayHandler::class, 'Found `Collection`']; + yield 'caster constructor with typed and untyped parameters' => [BadCasterHandler::class, 'Its constructor is __construct(string $format, $loose)']; + yield 'caster without a constructor' => [NoCtorCasterHandler::class, 'Its constructor is __construct()']; + yield 'dash in a path name' => [PathDashHandler::class, 'can only have letters, digits and underscores']; + yield 'underscore in a header name' => [HeaderUnderscoreHandler::class, "Use #[Header('X-Foo')]"]; + } + + /** + * @param class-string $handler + */ + #[DataProvider('invalidHandlers')] + public function testCompileTimeMessage(string $handler, string $needle): void + { + $this->expectException(\LogicException::class); + $this->expectExceptionMessage($needle); + DtoCompiler::compile($handler); + } + + public function testPathNameMessageSuggestsTheCorrectedName(): void + { + $this->expectException(\LogicException::class); + $this->expectExceptionMessage("Use for example #[Path('a_b')]."); + DtoCompiler::compile(PathDashHandler::class); + } + + public function testSplitSeparatorMessageHasNoDoublePeriod(): void + { + try { + DtoCompiler::compile(EmptySplitHandler::class); + $this->fail('compiled'); + } catch (\LogicException $exception) { + $this->assertStringNotContainsString('..', $exception->getMessage()); + $this->assertStringContainsString("#[Cast(Split::class, ',')]. Its constructor", $exception->getMessage()); + $this->assertStringNotContainsString('d.m.Y', $exception->getMessage()); + } + } + + /** + * @return \Iterator, string}> + */ + public static function invalid(): \Iterator + { + yield 'associative var with a description' => [VarAssocHandler::class, 'documents `array>`, an array that is not a list']; + yield 'array shape item' => [ShapeItemHandler::class, 'declare an item DTO']; + yield 'positive-int' => [PositiveIntHandler::class, 'PHPStan refinements such as positive-int']; + yield 'non-empty-string' => [NonEmptyStringHandler::class, 'documents list. PHPStan refinements']; + yield 'integer range' => [IntRangeHandler::class, 'documents list>. PHPStan refinements']; + yield 'generic item' => [GenericItemHandler::class, 'documents list>. PHPStan refinements']; + yield 'generic item with a list inside' => [ListInsideGenericHandler::class, 'documents list>. PHPStan refinements']; + yield 'dashed name that is no refinement' => [DashedItemHandler::class, 'documents list, and that type was not found']; + yield 'DateTime of Nette' => [NetteDateHandler::class, 'has type Nette\Utils\DateTime. Use DateTimeImmutable itself']; + yield 'DateTimeImmutable subclass' => [MyDateHandler::class, 'has type Tomaj\NetteApi\Test\Input\CustomDate. Use DateTimeImmutable itself']; + yield 'empty path name' => [EmptyPathHandler::class, "for example #[Path('my_name')]"]; + yield 'empty query name' => [EmptyQueryHandler::class, "for example #[Query('my_name')]"]; + yield 'empty body name' => [EmptyBodyHandler::class, "for example #[Body('my_name')]"]; + yield 'empty header name' => [EmptyHeaderHandler::class, "for example #[Header('X-Request-Id')]"]; + yield 'name that starts with a digit' => [DigitNameHandler::class, 'must start with a letter or an underscore']; + } + + /** + * @param class-string $handler + */ + #[DataProvider('invalid')] + public function testCompileMessages(string $handler, string $needle): void + { + try { + DtoCompiler::compile($handler); + $this->fail('compiled'); + } catch (\LogicException $exception) { + $this->assertStringContainsString($needle, $exception->getMessage()); + } + } + + public function testListOfPureEnumsIsNotABackedEnum(): void + { + $this->expectException(\LogicException::class); + $this->expectExceptionMessage(sprintf('PureEnumListInput::$suits uses %s, which is not a backed enum.', Suit::class)); + DtoCompiler::compile(PureEnumListHandler::class); + } +} + +final readonly class ListedInner +{ + public function __construct(#[Body] public string $q = 'x') + { + } +} + +final readonly class QueryDtoInput +{ + public function __construct( + #[Query] public ListedInner $x, + ) { + } +} + +final class QueryDtoHandler extends TypedHandler +{ + public function handleDto(QueryDtoInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class QueryListInput +{ + /** @param list $many */ + public function __construct( + #[Query] public array $many = [], + ) { + } +} + +final class QueryListHandler extends TypedHandler +{ + public function handleDto(QueryListInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class DateDefaultInput +{ + public function __construct( + #[Query] public \DateTimeImmutable $d = new \DateTimeImmutable('2020-01-01T00:00:00Z'), + ) { + } +} + +final class DateDefaultHandler extends TypedHandler +{ + public function handleDto(DateDefaultInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class DtoDefaultInput +{ + public function __construct( + #[Body] public ListedInner $i = new ListedInner(), + ) { + } +} + +final class DtoDefaultHandler extends TypedHandler +{ + public function handleDto(DtoDefaultInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class ListObjectDefaultInput +{ + /** @param list $items */ + public function __construct( + #[Body] public array $items = [new ListedInner()], + ) { + } +} + +final class ListObjectDefaultHandler extends TypedHandler +{ + public function handleDto(ListObjectDefaultInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class NullableItemsInput +{ + /** @param list $a */ + public function __construct( + #[Body] public array $a = [], + ) { + } +} + +final class NullableItemsHandler extends TypedHandler +{ + public function handleDto(NullableItemsInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class UnionItemsInput +{ + /** @param list $a */ + public function __construct( + #[Body] public array $a = [], + ) { + } +} + +final class UnionItemsHandler extends TypedHandler +{ + public function handleDto(UnionItemsInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class ListOfListsInput +{ + /** @param list> $a */ + public function __construct( + #[Body] public array $a = [], + ) { + } +} + +final class ListOfListsHandler extends TypedHandler +{ + public function handleDto(ListOfListsInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class AssocInput +{ + /** @param array $a */ + public function __construct( + #[Body] public array $a = [], + ) { + } +} + +final class AssocHandler extends TypedHandler +{ + public function handleDto(AssocInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class OtherDocInput +{ + /** @param iterable $a */ + public function __construct( + #[Body] public array $a = [], + ) { + } +} + +final class OtherDocHandler extends TypedHandler +{ + public function handleDto(OtherDocInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class PlainDateTimeInput +{ + public function __construct( + #[Body] public \DateTime $d, + ) { + } +} + +final class PlainDateTimeHandler extends TypedHandler +{ + public function handleDto(PlainDateTimeInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class DateInterfaceInput +{ + public function __construct( + #[Body] public \DateTimeInterface $d, + ) { + } +} + +final class DateInterfaceHandler extends TypedHandler +{ + public function handleDto(DateInterfaceInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class EmptySplitInput +{ + /** @param list $a */ + public function __construct( + #[Query] #[Cast(Split::class, '')] public array $a = [], + ) { + } +} + +final class EmptySplitHandler extends TypedHandler +{ + public function handleDto(EmptySplitInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class SplitIntsInput +{ + /** @param list $a */ + public function __construct( + #[Query] #[Cast(Split::class, ',')] public array $a = [], + ) { + } +} + +final class SplitIntsHandler extends TypedHandler +{ + public function handleDto(SplitIntsInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class PathDashInput +{ + public function __construct( + #[Path('a-b')] public int $x, + ) { + } +} + +final class PathDashHandler extends TypedHandler +{ + public function handleDto(PathDashInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class HeaderUnderscoreInput +{ + public function __construct( + #[Header('X_Foo')] public ?string $x = null, + ) { + } +} + +final class HeaderUnderscoreHandler extends TypedHandler +{ + public function handleDto(HeaderUnderscoreInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class TrailingUnionInput +{ + /** @param list|string $a */ + public function __construct(#[Body] public array $a = []) + { + } +} + +final class TrailingUnionHandler extends TypedHandler +{ + public function handleDto(TrailingUnionInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class ArrayOfArraysInput +{ + /** @param array $a */ + public function __construct(#[Body] public array $a = []) + { + } +} + +final class ArrayOfArraysHandler extends TypedHandler +{ + public function handleDto(ArrayOfArraysInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BracketUnionInput +{ + /** @param string[]|int $a */ + public function __construct(#[Body] public array $a = []) + { + } +} + +final class BracketUnionHandler extends TypedHandler +{ + public function handleDto(BracketUnionInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class ArrayOfListsInput +{ + /** @param array> $a */ + public function __construct(#[Body] public array $a = []) + { + } +} + +final class ArrayOfListsHandler extends TypedHandler +{ + public function handleDto(ArrayOfListsInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class UnionBracketsInput +{ + /** @param int|string[] $a */ + public function __construct(#[Body] public array $a = []) + { + } +} + +final class UnionBracketsHandler extends TypedHandler +{ + public function handleDto(UnionBracketsInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class GenericOfArrayInput +{ + /** @param Collection $a */ + public function __construct(#[Body] public array $a = []) + { + } +} + +final class GenericOfArrayHandler extends TypedHandler +{ + public function handleDto(GenericOfArrayInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BadCaster implements CasterInterface +{ + public function __construct(string $format, $loose = null) + { + throw new \InvalidArgumentException('Bad format'); + } + + public function cast(mixed $value): mixed + { + return $value; + } +} + +final class NoCtorCaster implements CasterInterface +{ + public function cast(mixed $value): mixed + { + return $value; + } +} + +final readonly class BadCasterInput +{ + public function __construct(#[Query] #[Cast(BadCaster::class, 'x')] public ?string $a = null) + { + } +} + +final class BadCasterHandler extends TypedHandler +{ + public function handleDto(BadCasterInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class NoCtorCasterInput +{ + public function __construct(#[Query] #[Cast(NoCtorCaster::class, 'x')] public ?string $a = null) + { + } +} + +final class NoCtorCasterHandler extends TypedHandler +{ + public function handleDto(NoCtorCasterInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class VarAssocInput +{ + public function __construct( + /** @var array> Lists by name */ + #[Body] public array $lists = [], + ) { + } +} + +final class VarAssocHandler extends TypedHandler +{ + public function handleDto(VarAssocInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class ShapeItemInput +{ + /** @param list $shapes */ + public function __construct(#[Body] public array $shapes = []) + { + } +} + +final class ShapeItemHandler extends TypedHandler +{ + public function handleDto(ShapeItemInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class PositiveIntInput +{ + /** @param list $ids */ + public function __construct(#[Body] public array $ids = []) + { + } +} + +final class PositiveIntHandler extends TypedHandler +{ + public function handleDto(PositiveIntInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class NonEmptyStringInput +{ + /** @param list $names */ + public function __construct(#[Body] public array $names = []) + { + } +} + +final class NonEmptyStringHandler extends TypedHandler +{ + public function handleDto(NonEmptyStringInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class IntRangeInput +{ + /** @param list> $ids */ + public function __construct(#[Body] public array $ids = []) + { + } +} + +final class IntRangeHandler extends TypedHandler +{ + public function handleDto(IntRangeInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class GenericItemInput +{ + /** @param list> $items */ + public function __construct(#[Body] public array $items = []) + { + } +} + +final class GenericItemHandler extends TypedHandler +{ + public function handleDto(GenericItemInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class NetteDateInput +{ + public function __construct(#[Body] public ?DateTime $at = null) + { + } +} + +final class NetteDateHandler extends TypedHandler +{ + public function handleDto(NetteDateInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +class CustomDate extends \DateTimeImmutable +{ +} + +final readonly class MyDateInput +{ + public function __construct(#[Body] public ?CustomDate $at = null) + { + } +} + +final class MyDateHandler extends TypedHandler +{ + public function handleDto(MyDateInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class EmptyPathInput +{ + public function __construct(#[Path('')] public int $id) + { + } +} + +final class EmptyPathHandler extends TypedHandler +{ + public function handleDto(EmptyPathInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class EmptyQueryInput +{ + public function __construct(#[Query('')] public ?int $page = null) + { + } +} + +final class EmptyQueryHandler extends TypedHandler +{ + public function handleDto(EmptyQueryInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class EmptyBodyInput +{ + public function __construct(#[Body('')] public ?int $page = null) + { + } +} + +final class EmptyBodyHandler extends TypedHandler +{ + public function handleDto(EmptyBodyInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class EmptyHeaderInput +{ + public function __construct(#[Header('')] public ?string $id = null) + { + } +} + +final class EmptyHeaderHandler extends TypedHandler +{ + public function handleDto(EmptyHeaderInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class DigitNameInput +{ + public function __construct(#[Query('0a')] public ?int $page = null) + { + } +} + +final class DigitNameHandler extends TypedHandler +{ + public function handleDto(DigitNameInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class ListInsideGenericInput +{ + /** @param list> $items */ + public function __construct(#[Body] public array $items = []) + { + } +} + +final class ListInsideGenericHandler extends TypedHandler +{ + public function handleDto(ListInsideGenericInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class DashedItemInput +{ + /** @param list $items */ + public function __construct(#[Body] public array $items = []) + { + } +} + +final class DashedItemHandler extends TypedHandler +{ + public function handleDto(DashedItemInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +enum Suit +{ + case Hearts; + case Spades; +} + +final readonly class PureEnumListInput +{ + /** @param list $suits */ + public function __construct(#[Query] public array $suits = []) + { + } +} + +final class PureEnumListHandler extends TypedHandler +{ + public function handleDto(PureEnumListInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} diff --git a/tests/Input/EndpointTemplateTest.php b/tests/Input/EndpointTemplateTest.php index 56e3196e8..25bec1fc9 100644 --- a/tests/Input/EndpointTemplateTest.php +++ b/tests/Input/EndpointTemplateTest.php @@ -38,6 +38,14 @@ public function testMatchAndNormalize(): void $this->assertNull(EndpointTemplate::normalize('/api/v1extra', '1')); } + public function testAnEncodedSlashStaysInsideItsValue(): void + { + $this->assertSame(['id' => 'a/b'], EndpointTemplate::match('v1/users/{id}', EndpointTemplate::normalize('/api/v1/users/a%2Fb', '1'))); + $this->assertNull(EndpointTemplate::match('v1/users/{id}/detail', EndpointTemplate::normalize('/api/v1/users/a%2Fdetail', '1'))); + $this->assertSame(['id' => 'a b'], EndpointTemplate::match('v1/users/{id}/detail', EndpointTemplate::normalize('/api/v1/users/a%20b/detail', '1'))); + $this->assertSame(['id' => '1'], EndpointTemplate::match('v1/users/{id}', 'v1/us%65rs/1'), 'a static segment is compared decoded'); + } + public function testAssertNamesTheMismatch(): void { EndpointTemplate::assert('v1/users/{id}/detail', ['id'], 'UserDetailHandler'); @@ -72,4 +80,45 @@ public function testOverlap(): void $this->expectException(\LogicException::class); EndpointTemplate::assertDisjoint(['GET' => ['v1/users/{id}', 'v1/users/{slug}']]); } + + public function testEndpointMessagesUseTheRealUrl(): void + { + $this->assertSame('v1/users', EndpointTemplate::normalize('/api/v1/users/', '1')); + foreach (['v1/x{id}', 'v1/{id}x'] as $url) { + try { + EndpointTemplate::assert($url, [], 'Handler'); + $this->fail($url); + } catch (\LogicException $exception) { + $this->assertStringContainsString($url, $exception->getMessage()); + } + } + try { + EndpointTemplate::assert('v1/users/{id}/', [], 'Handler'); + $this->fail('slash'); + } catch (\LogicException $exception) { + $this->assertStringContainsString("endpoint URL 'v1/users/{id}'", $exception->getMessage()); + $this->assertStringNotContainsString("endpoint URL 'v1/users/{id}/'", $exception->getMessage()); + } + try { + EndpointTemplate::assert('v1/{id}/x/{id}/y/{id}/', ['id'], 'Handler'); + $this->fail('duplicate'); + } catch (\LogicException $exception) { + $this->assertStringContainsString('repeats {id}.', $exception->getMessage()); + $this->assertStringContainsString("endpoint URL 'v1/{id}/x/{id}/y/{id}'", $exception->getMessage()); + } + try { + EndpointTemplate::assert('v1/users/{id-1}/', [], 'Handler'); + $this->fail('malformed'); + } catch (\LogicException $exception) { + $this->assertStringContainsString("endpoint URL 'v1/users/{id-1}'", $exception->getMessage()); + $this->assertStringNotContainsString('{id-1}/', $exception->getMessage()); + } + EndpointTemplate::assertDisjoint(['GET' => ['v1/static', 'v1/users/{id}', 'v1/orders/{id}']]); + try { + EndpointTemplate::assertDisjoint(['GET' => ['v1/users/{id}/', 'v1/users/{slug}/']]); + $this->fail('overlap'); + } catch (\LogicException $exception) { + $this->assertStringContainsString("endpoints 'v1/users/{id}' and 'v1/users/{slug}'", $exception->getMessage()); + } + } } diff --git a/tests/Input/ErrorBudgetTest.php b/tests/Input/ErrorBudgetTest.php new file mode 100644 index 000000000..072c4b268 --- /dev/null +++ b/tests/Input/ErrorBudgetTest.php @@ -0,0 +1,372 @@ +json(['ids' => array_fill(0, 5000, 'x')]); + $errors = $this->errors(new ManyIdsHandler()); + + $this->assertCount(DtoMapper::MAX_ERRORS + 1, $errors); + $this->assertSame(['Value must be an integer'], $errors['ids[0]']); + $this->assertSame(['Value must be an integer'], $errors['ids[99]']); + $this->assertArrayNotHasKey('ids[100]', $errors); + $this->assertSame(['Only the first 100 errors are reported, the rest of the request was not checked'], $errors['body']); + $this->assertArrayNotHasKey('ids', $errors); + } + + public function testTheBudgetIsOnePerRequestAcrossNestedLists(): void + { + $leaf = array_fill(0, 100, new \stdClass()); + $middle = array_fill(0, 100, ['cs' => $leaf]); + $outer = array_fill(0, 100, ['bs' => $middle]); + $this->json(['as' => $outer]); + + $errors = $this->errors(new NestedListsHandler()); + $messages = array_merge(...array_values($errors)); + + $this->assertLessThanOrEqual(DtoMapper::MAX_ERRORS + 1, count($messages)); + $this->assertContains('Only the first 100 errors are reported, the rest of the request was not checked', $messages); + $this->assertCount(1, array_filter($messages, static fn (string $message): bool => str_starts_with($message, 'Only the first'))); + } + + public function testTheBudgetAlsoStopsLaterFields(): void + { + $this->json(['ids' => array_fill(0, 150, 'x'), 'other' => 'y']); + $errors = $this->errors(new BudgetHandler()); + + $this->assertArrayNotHasKey('other', $errors); + $this->assertCount(101, $errors); + } + + public function testNothingIsLeftUncheckedUpToTheCapSoThereIsNoNote(): void + { + $this->json(['ids' => array_fill(0, 99, 'x')]); + $errors = $this->errors(new ManyIdsHandler()); + $this->assertCount(99, $errors); + $this->assertArrayNotHasKey('ids', $errors); + + // exactly the budget: nothing was left unchecked, so there is nothing to apologise for + $this->json(['ids' => array_fill(0, 100, 'x')]); + $errors = $this->errors(new ManyIdsHandler()); + $this->assertCount(100, $errors); + $this->assertArrayNotHasKey('body', $errors); + + $this->json(['ids' => array_fill(0, 101, 'x')]); + $errors = $this->errors(new ManyIdsHandler()); + $this->assertCount(101, $errors); + $this->assertArrayHasKey('body', $errors); + $this->assertArrayNotHasKey('ids[100]', $errors); + } + + public function testManyInvalidItemsAreCheckedInLinearTime(): void + { + $this->json(['ids' => array_merge(array_fill(0, 100, 1), array_fill(0, 60000, 'x'))]); + $start = microtime(true); + $this->errors(new ManyIdsHandler()); + $this->assertLessThan(2.0, microtime(true) - $start); + } + + public function testTheBudgetStopsInsideAnObjectToo(): void + { + $this->json(['ids' => array_fill(0, 99, 'x'), 'inner' => new \stdClass()]); + $errors = $this->errors(new BudgetObjectHandler()); + + $this->assertSame(['Field is required'], $errors['inner.a']); + $this->assertSame(['Only the first 100 errors are reported, the rest of the request was not checked'], $errors['body']); + $this->assertArrayNotHasKey('inner', $errors); + $this->assertArrayNotHasKey('inner.b', $errors); + $this->assertArrayNotHasKey('inner.c', $errors); + } + + public function testTheBudgetEndsAtTheTopLevelToo(): void + { + $this->json(['ids' => array_fill(0, 99, 'x'), 'x' => 'a', 'y' => 'b']); + $errors = $this->errors(new BudgetTopHandler()); + + $this->assertSame(['Value must be an integer'], $errors['x']); + $this->assertSame(['Only the first 100 errors are reported, the rest of the request was not checked'], $errors['body']); + $this->assertArrayNotHasKey('y', $errors); + } + + public function testConstraintMessagesCountTowardsTheBudget(): void + { + $this->json(['items' => array_fill(0, 150, ['name' => 'too long'])]); + $errors = $this->errors(new ConstraintBudgetHandler()); + + $this->assertCount(101, $errors); + $this->assertSame(['Only the first 100 errors are reported, the rest of the request was not checked'], $errors['body']); + $this->assertArrayHasKey('items[99].name', $errors); + $this->assertArrayNotHasKey('items[100].name', $errors); + } + + public function testTheNoteAboutAnExhaustedBudgetBelongsToTheFirstFieldWhenNothingReadsABody(): void + { + $_GET = ['ids' => array_fill(0, 150, 'x')]; + $metadata = DtoCompiler::compile(QueryBudgetHandler::class); + $mapper = new DtoMapper($metadata); + + $first = $mapper->errors($metadata->fields[0]); + $this->assertCount(101, $first); + $this->assertSame(['Only the first 100 errors are reported, the rest of the request was not checked'], $first['body']); + $this->assertSame([], $mapper->errors($metadata->fields[1])); + } + + public function testTheNoteBelongsToTheFirstBodyFieldEvenWhenAQueryFieldComesFirst(): void + { + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + RequestInput::setRawBody('{"ids":' . json_encode(array_fill(0, 150, 'x')) . '}'); + $metadata = DtoCompiler::compile(MixedBudgetHandler::class); + $mapper = new DtoMapper($metadata); + + $this->assertSame([], $mapper->errors($metadata->fields[0])); + $this->assertArrayHasKey('body', $mapper->errors($metadata->fields[1])); + } + + public function testAnErrorOfTheBodyAndTheNoteShareTheKey(): void + { + $this->assertNull($this->post('application/json', '{"a":"x"}', new BodyFieldHandler())); + RequestInput::reset(); + $errors = $this->post('application/json', '{"ids":' . json_encode(array_fill(0, 101, 'x')) . '}', new BodyBudgetHandler()); + + $this->assertCount(101, $errors ?? []); + $this->assertSame(['Only the first 100 errors are reported, the rest of the request was not checked'], $errors['body'] ?? []); + } + + /** + * @param array $body + */ + private function json(array $body): void + { + RequestInput::reset(); + RequestInput::setRawBody((string) json_encode($body)); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + } + + /** + * @return array + */ + private function errors(TypedHandler $handler): array + { + $processor = new ParamsProcessor($handler->params()); + $this->assertTrue($processor->isError()); + + return $processor->getErrors(); + } + + /** + * @return array>|null + */ + private function post(string $contentType, string $raw, TypedHandler $handler): ?array + { + $_SERVER['CONTENT_TYPE'] = $contentType; + $_SERVER['REQUEST_METHOD'] = 'POST'; + RequestInput::setRawBody($raw); + $processor = new ParamsProcessor($handler->params()); + + return $processor->isError() ? $processor->getErrors() : null; + } + +} + +final readonly class BudgetLeaf +{ + public function __construct(#[Body] public string $x) + { + } +} + +final readonly class BudgetMiddle +{ + /** @param list $cs */ + public function __construct(#[Body] public array $cs) + { + } +} + +final readonly class BudgetOuter +{ + /** @param list $bs */ + public function __construct(#[Body] public array $bs) + { + } +} + +final readonly class NestedListsInput +{ + /** @param list $as */ + public function __construct(#[Body] public array $as) + { + } +} + +final class NestedListsHandler extends TypedHandler +{ + public function handleDto(NestedListsInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BudgetInput +{ + /** @param list $ids */ + public function __construct(#[Body] public array $ids, #[Body] public int $other) + { + } +} + +final class BudgetHandler extends TypedHandler +{ + public function handleDto(BudgetInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BudgetInner +{ + public function __construct(#[Body] public string $a, #[Body] public string $b, #[Body] public string $c) + { + } +} + +final readonly class BudgetObjectInput +{ + /** @param list $ids */ + public function __construct(#[Body] public array $ids, #[Body] public BudgetInner $inner) + { + } +} + +final class BudgetObjectHandler extends TypedHandler +{ + public function handleDto(BudgetObjectInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class NamedItem +{ + public function __construct(#[Body] #[Length(max: 3)] public string $name) + { + } +} + +final readonly class ConstraintBudgetInput +{ + /** @param list $items */ + public function __construct(#[Body] public array $items) + { + } +} + +final class ConstraintBudgetHandler extends TypedHandler +{ + public function handleDto(ConstraintBudgetInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BudgetTopInput +{ + /** @param list $ids */ + public function __construct(#[Body] public array $ids, #[Body] public int $x, #[Body] public int $y) + { + } +} + +final class BudgetTopHandler extends TypedHandler +{ + public function handleDto(BudgetTopInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class QueryBudgetInput +{ + /** @param list $ids */ + public function __construct(#[Query] public array $ids = [], #[Query] public int $page = 1) + { + } +} + +final class QueryBudgetHandler extends TypedHandler +{ + public function handleDto(QueryBudgetInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BodyBudgetInput +{ + /** @param list $ids */ + public function __construct(#[Body] public array $ids = []) + { + } +} + +final class BodyBudgetHandler extends TypedHandler +{ + public function handleDto(BodyBudgetInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class MixedBudgetInput +{ + /** @param list $ids */ + public function __construct(#[Query] public int $page = 1, #[Body] public array $ids = []) + { + } +} + +final class MixedBudgetHandler extends TypedHandler +{ + public function handleDto(MixedBudgetInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} diff --git a/tests/Input/EscapeTest.php b/tests/Input/EscapeTest.php index aec04ba1e..3cd77921b 100644 --- a/tests/Input/EscapeTest.php +++ b/tests/Input/EscapeTest.php @@ -14,8 +14,6 @@ use Tomaj\NetteApi\Input\Query; use PHPUnit\Framework\TestCase; use Tomaj\NetteApi\Handlers\BaseHandler; -use Tomaj\NetteApi\Input\DtoCompiler; -use Tomaj\NetteApi\Input\Field; use Tomaj\NetteApi\Input\RequestInput; use Tomaj\NetteApi\OpenApi\RequestBodyBuilder; use Tomaj\NetteApi\OpenApi\SchemaRegistry; @@ -24,8 +22,6 @@ use Tomaj\NetteApi\Response\ResponseInterface; use Tomaj\NetteApi\Test\Input\Fixtures\AvatarHandler; use Tomaj\NetteApi\Test\Input\Fixtures\CreateOrderHandler; -use Tomaj\NetteApi\Test\Input\Fixtures\ListUsersHandler; -use Tomaj\NetteApi\Validation\Range; final class EscapeTest extends TestCase { @@ -38,79 +34,6 @@ protected function setUp(): void unset($_SERVER['CONTENT_TYPE'], $_SERVER['HTTP_CONTENT_TYPE'], $_SERVER['REQUEST_METHOD']); } - public function testImportedFieldRejectsCorruptMetadata(): void - { - $export = DtoCompiler::compile(ListUsersHandler::class)->export(); - $field = $export['fields'][0]; - $field['casterArguments'] = [0 => 'd.m.Y', 2 => 'ignored']; - $imported = Field::import($field); - $this->assertSame([0 => 'd.m.Y', 2 => 'ignored'], $imported->casterArguments, 'keys survive so named caster arguments work'); - $this->assertCount(2, $imported->casterArguments); - $this->assertSame('d.m.Y', $imported->casterArguments[0]); - - $field['enumClass'] = \stdClass::class; - $this->expectException(\LogicException::class); - Field::import($field); - } - - public function testImportedFieldRejectsABadCasterAndConstraint(): void - { - $export = DtoCompiler::compile(ListUsersHandler::class)->export(); - $field = $export['fields'][0]; - $field['casterClass'] = \stdClass::class; - try { - Field::import($field); - $this->fail('caster'); - } catch (\LogicException $exception) { - $this->assertStringContainsString('caster', $exception->getMessage()); - } - - $field = $export['fields'][0]; - $field['property'] = ''; - try { - Field::import($field); - $this->fail('property'); - } catch (\LogicException $exception) { - $this->assertStringContainsString('property', $exception->getMessage()); - } - - $field = $export['fields'][0]; - $field['constraintSpecs'] = [new FakeConstraintSpec()]; - try { - Field::import($field); - $this->fail('constraint shape'); - } catch (\LogicException $exception) { - $this->assertStringContainsString('constraint', $exception->getMessage()); - } - - $field = $export['fields'][0]; - $field['constraintSpecs'] = [['class' => Range::class, 'args' => 'nope']]; - try { - Field::import($field); - $this->fail('constraint args'); - } catch (\LogicException $exception) { - $this->assertStringContainsString('constraint', $exception->getMessage()); - } - - $field = $export['fields'][0]; - $field['constraintSpecs'] = [['class' => \stdClass::class, 'args' => []]]; - try { - Field::import($field); - $this->fail('constraint'); - } catch (\LogicException $exception) { - $this->assertStringContainsString('constraint', $exception->getMessage()); - } - - $field = $export['fields'][3]; - $field['enumValues'] = [1, 1.5]; - try { - Field::import($field); - $this->fail('enum'); - } catch (\LogicException $exception) { - $this->assertStringContainsString('enum values', $exception->getMessage()); - } - } - public function testRequiredHeaderAndPathAreMissingRatherThanNull(): void { $_SERVER['CONTENT_TYPE'] = 'application/json'; @@ -163,14 +86,6 @@ public function testPostWithAnEmptySuperglobalDoesNotReadTheRawForm(): void $this->assertArrayHasKey('customerEmail', $this->errors(new CreateOrderHandler())); } - public function testUnknownSourceAttributeIsRejected(): void - { - $compiler = new \ReflectionClass(DtoCompiler::class)->newInstanceWithoutConstructor(); - $method = new \ReflectionMethod(DtoCompiler::class, 'sourceAttribute'); - $this->expectException(\LogicException::class); - $method->invoke($compiler, new \stdClass()); - } - public function testAMissingNestedFieldDoesNotHideTheNextError(): void { RequestInput::setRawBody('{"customerEmail":"ada@example.com","address":{"postalCode":"abc"},"items":[{"sku":"A","quantity":1}]}'); @@ -313,27 +228,6 @@ public function handleDto(SiblingOuter $input): ResponseInterface } } -final class FakeConstraintSpec implements \ArrayAccess -{ - public function offsetExists(mixed $offset): bool - { - return true; - } - - public function offsetGet(mixed $offset): mixed - { - return $offset === 'class' ? Range::class : ['min' => 1]; - } - - public function offsetSet(mixed $offset, mixed $value): void - { - } - - public function offsetUnset(mixed $offset): void - { - } -} - final class LooseBodyHandler extends BaseHandler { public function params(): array diff --git a/tests/Input/FileUploadTest.php b/tests/Input/FileUploadTest.php index 20e8b6c9e..b77273b21 100644 --- a/tests/Input/FileUploadTest.php +++ b/tests/Input/FileUploadTest.php @@ -81,8 +81,8 @@ public function testOpenApiListsFilesOnlyInMultipart(): void public function testOpenApiFileListIsAnArrayOfBinaries(): void { $content = $this->requestBody(new FilesHandler())['content']; - $this->assertSame(['type' => 'array', 'items' => ['type' => 'string', 'format' => 'binary']], $content['multipart/form-data']['schema']['properties']['files']); - $this->assertSame(['files'], $content['multipart/form-data']['schema']['required']); + $this->assertSame(['type' => 'array', 'items' => ['type' => 'string', 'format' => 'binary']], $content['multipart/form-data']['schema']['properties']['files[]']); + $this->assertSame(['files[]'], $content['multipart/form-data']['schema']['required']); $this->assertSame(['multipart/form-data'], array_keys($content)); } @@ -126,7 +126,7 @@ public function testOpenApiOptionalFilesAreNotRequired(): void { $content = $this->requestBody(new DocumentHandler())['content']; $this->assertSame(['issuedOn', 'copies'], $content['multipart/form-data']['schema']['required']); - $this->assertSame(['issuedOn', 'copies', 'scan', 'attachments'], array_keys($content['multipart/form-data']['schema']['properties'])); + $this->assertSame(['issuedOn', 'copies', 'scan', 'attachments[]'], array_keys($content['multipart/form-data']['schema']['properties'])); $this->assertSame(['issuedOn', 'copies'], array_keys($content['application/json']['schema']['properties'])); $this->assertSame(['issuedOn', 'copies'], $content['application/json']['schema']['required']); } @@ -377,4 +377,31 @@ private function processor(BaseHandler $handler): ParamsProcessor { return new ParamsProcessor($handler->params()); } + + public function testFileUploadReplacesNonStrings(): void + { + $file = FileUpload::fromFile(['name' => 1, 'type' => 2, 'tmp_name' => 3, 'size' => '12']); + $this->assertSame('', $file->originalName); + $this->assertSame('', $file->clientContentType); + $this->assertSame('', $file->temporaryPath); + $this->assertSame(0, $file->size); + $this->assertSame(\UPLOAD_ERR_NO_FILE, $file->error); + } + + public function testUploadErrorShapes(): void + { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_SERVER['CONTENT_TYPE'] = 'multipart/form-data'; + $_FILES = ['avatar' => ['name' => '', 'type' => '', 'tmp_name' => '', 'error' => \UPLOAD_ERR_NO_FILE, 'size' => 0]]; + $_POST = ['displayName' => 'Ada']; + $this->assertSame(['avatar' => ['Field is required']], $this->errors(new AvatarHandler())); + + RequestInput::reset(); + $_FILES = ['avatar' => ['name' => 'a.png', 'type' => '', 'tmp_name' => '/tmp/a', 'error' => \UPLOAD_ERR_NO_FILE, 'size' => 4]]; + $this->assertSame('a.png', $this->payload(new AvatarHandler())['file']); + + RequestInput::reset(); + $_FILES = ['avatar' => ['error' => \UPLOAD_ERR_NO_FILE, 'size' => 0]]; + $this->assertSame(['avatar' => ['Field is required']], $this->errors(new AvatarHandler())); + } } diff --git a/tests/Input/Fixtures/Inherited/Base/LevelsCaster.php b/tests/Input/Fixtures/Inherited/Base/LevelsCaster.php new file mode 100644 index 000000000..80f165df6 --- /dev/null +++ b/tests/Input/Fixtures/Inherited/Base/LevelsCaster.php @@ -0,0 +1,23 @@ + + */ + #[\Override] + public function cast(mixed $value): array + { + return array_map(static fn (string $item): Level => Level::from((int) $item), explode(',', is_string($value) ? $value : '')); + } +} diff --git a/tests/Input/Fixtures/Inherited/Base/LevelsInput.php b/tests/Input/Fixtures/Inherited/Base/LevelsInput.php new file mode 100644 index 000000000..f426d0b4e --- /dev/null +++ b/tests/Input/Fixtures/Inherited/Base/LevelsInput.php @@ -0,0 +1,26 @@ + with an import of this file; a subclass in another namespace inherits the constructor. + */ +readonly class LevelsInput +{ + /** + * @param list $levels + * @param list $casted + */ + public function __construct( + #[Query] public array $levels = [], + #[Query] #[Cast(LeafLevelsCaster::class)] public array $casted = [], + ) { + } +} diff --git a/tests/Input/Fixtures/Inherited/LeafLevelsCaster.php b/tests/Input/Fixtures/Inherited/LeafLevelsCaster.php new file mode 100644 index 000000000..76ab6aacd --- /dev/null +++ b/tests/Input/Fixtures/Inherited/LeafLevelsCaster.php @@ -0,0 +1,11 @@ + $input->levels, 'casted' => $input->casted]); + } +} diff --git a/tests/Input/Fixtures/Inherited/LeafLevelsInput.php b/tests/Input/Fixtures/Inherited/LeafLevelsInput.php new file mode 100644 index 000000000..fb8e020e1 --- /dev/null +++ b/tests/Input/Fixtures/Inherited/LeafLevelsInput.php @@ -0,0 +1,14 @@ + only resolves in the file of the parent. + */ +final readonly class LeafLevelsInput extends LevelsInput +{ +} diff --git a/tests/Input/Fixtures/Shared.php b/tests/Input/Fixtures/Shared.php new file mode 100644 index 000000000..62bf9d4dc --- /dev/null +++ b/tests/Input/Fixtures/Shared.php @@ -0,0 +1,197 @@ + $ids */ + public function __construct(#[Body] public array $ids) + { + } +} + +final class ManyIdsHandler extends TypedHandler +{ + public function handleDto(ManyIdsInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['count' => count($input->ids)]); + } +} + +final readonly class SplitInput +{ + /** @param list $tags */ + public function __construct( + #[Query] #[Cast(Split::class, ',')] public array $tags = [], + #[Query] #[Cast(UpperCaster::class)] public string $label = 'plain', + ) { + } +} + +final class SplitHandler extends TypedHandler +{ + public function handleDto(SplitInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['tags' => $input->tags]); + } +} + +final readonly class UpperCaster implements CasterInterface +{ + public function cast(mixed $value): string + { + return strtoupper(is_string($value) ? $value : ''); + } +} + +final readonly class FormInput +{ + public function __construct( + #[Body] public ?string $a = null, + ) { + } +} + +final class FormHandler extends TypedHandler +{ + public function handleDto(FormInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BodyFieldInput +{ + public function __construct(#[Body] public ?string $a = null) + { + } +} + +final class BodyFieldHandler extends TypedHandler +{ + public function handleDto(BodyFieldInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class NamedCaster implements CasterInterface +{ + public function __construct(private string $prefix = 'A', private string $suffix = 'B') + { + } + + public function cast(mixed $value): string + { + return $this->prefix . (is_string($value) ? $value : '') . $this->suffix; + } +} + +final readonly class OptionalArgumentInput +{ + public function __construct(#[Query] public int $page = 1, string $mode = 'fast') + { + unset($mode); + } +} + +final class OptionalArgumentHandler extends TypedHandler +{ + public function handleDto(OptionalArgumentInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['page' => $input->page]); + } +} + +final readonly class TwoExamplesInput +{ + public function __construct(#[Query(examples: ['one' => 1, 'two' => 2])] public int $page = 1) + { + } +} + +final class TwoExamplesHandler extends TypedHandler +{ + public function handleDto(TwoExamplesInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class DescribedInput +{ + public function __construct( + #[Body(description: 'Customer email')] public ?string $email = null, + ) { + } +} + +#[Consumes('application/json')] +final class DescribedHandler extends TypedHandler +{ + public function handleDto(DescribedInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class QueryThenBodyInput +{ + public function __construct( + #[Query] public int $page, + #[Body] public string $email, + ) { + } +} + +final class QueryThenBodyHandler extends TypedHandler +{ + public function handleDto(QueryThenBodyInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class FloatRangeInput +{ + public function __construct(#[Query] #[Range(min: 0.5, max: 2.5)] public float $ratio = 1.0) + { + } +} + +final class FloatRangeHandler extends TypedHandler +{ + public function handleDto(FloatRangeInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class DateHintInput +{ + public function __construct(#[Query] #[Cast(DateFormat::class, 'd.m.Y')] public \DateTimeImmutable $day) + { + } +} + +final class DateHintHandler extends TypedHandler +{ + public function handleDto(DateHintInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} diff --git a/tests/Input/Fixtures/create-order-export.json b/tests/Input/Fixtures/create-order-export.json index 71b9a65f7..c2cc5fcef 100644 --- a/tests/Input/Fixtures/create-order-export.json +++ b/tests/Input/Fixtures/create-order-export.json @@ -1,27 +1,29 @@ { + "@class": "Tomaj\\NetteApi\\Input\\DtoMetadata", "handler": "Tomaj\\NetteApi\\Test\\Input\\Fixtures\\CreateOrderHandler", "class": "Tomaj\\NetteApi\\Test\\Input\\Fixtures\\CreateOrderInput", "fields": [ { + "@class": "Tomaj\\NetteApi\\Input\\Field", "property": "customerEmail", "externalName": "customerEmail", - "source": "body", + "source": { + "enum": "Tomaj\\NetteApi\\Input\\Source", + "value": "body" + }, "typeName": "string", - "builtin": true, "nullable": false, "hasDefault": false, "default": null, "description": null, "examples": [], "listItem": null, - "listItemBuiltin": false, "enumClass": null, "enumInt": false, "enumValues": [], - "constraintSpecs": [ + "constraints": [ { - "class": "Tomaj\\NetteApi\\Validation\\Email", - "args": [] + "@class": "Tomaj\\NetteApi\\Validation\\Email" } ], "casterClass": null, @@ -32,49 +34,51 @@ "dtoClass": "Tomaj\\NetteApi\\Test\\Input\\Fixtures\\CreateOrderInput" }, { + "@class": "Tomaj\\NetteApi\\Input\\Field", "property": "address", "externalName": "address", - "source": "body", + "source": { + "enum": "Tomaj\\NetteApi\\Input\\Source", + "value": "body" + }, "typeName": "Tomaj\\NetteApi\\Test\\Input\\Fixtures\\AddressInput", - "builtin": false, "nullable": false, "hasDefault": false, "default": null, "description": null, "examples": [], "listItem": null, - "listItemBuiltin": false, "enumClass": null, "enumInt": false, "enumValues": [], - "constraintSpecs": [], + "constraints": [], "casterClass": null, "casterArguments": [], "casterSchema": null, "children": [ { + "@class": "Tomaj\\NetteApi\\Input\\Field", "property": "street", "externalName": "street", - "source": "body", + "source": { + "enum": "Tomaj\\NetteApi\\Input\\Source", + "value": "body" + }, "typeName": "string", - "builtin": true, "nullable": false, "hasDefault": false, "default": null, "description": null, "examples": [], "listItem": null, - "listItemBuiltin": false, "enumClass": null, "enumInt": false, "enumValues": [], - "constraintSpecs": [ + "constraints": [ { - "class": "Tomaj\\NetteApi\\Validation\\Length", - "args": { - "min": 1, - "max": 120 - } + "@class": "Tomaj\\NetteApi\\Validation\\Length", + "min": 1, + "max": 120 } ], "casterClass": null, @@ -85,27 +89,27 @@ "dtoClass": "Tomaj\\NetteApi\\Test\\Input\\Fixtures\\AddressInput" }, { + "@class": "Tomaj\\NetteApi\\Input\\Field", "property": "postalCode", "externalName": "postalCode", - "source": "body", + "source": { + "enum": "Tomaj\\NetteApi\\Input\\Source", + "value": "body" + }, "typeName": "string", - "builtin": true, "nullable": false, "hasDefault": false, "default": null, "description": null, "examples": [], "listItem": null, - "listItemBuiltin": false, "enumClass": null, "enumInt": false, "enumValues": [], - "constraintSpecs": [ + "constraints": [ { - "class": "Tomaj\\NetteApi\\Validation\\Pattern", - "args": [ - "/^[0-9]{5}$/" - ] + "@class": "Tomaj\\NetteApi\\Validation\\Pattern", + "pattern": "/^[0-9]{5}$/" } ], "casterClass": null, @@ -120,28 +124,28 @@ "dtoClass": "Tomaj\\NetteApi\\Test\\Input\\Fixtures\\CreateOrderInput" }, { + "@class": "Tomaj\\NetteApi\\Input\\Field", "property": "items", "externalName": "items", - "source": "body", + "source": { + "enum": "Tomaj\\NetteApi\\Input\\Source", + "value": "body" + }, "typeName": "array", - "builtin": true, "nullable": false, "hasDefault": false, "default": null, "description": null, "examples": [], "listItem": "Tomaj\\NetteApi\\Test\\Input\\Fixtures\\ItemInput", - "listItemBuiltin": false, "enumClass": null, "enumInt": false, "enumValues": [], - "constraintSpecs": [ + "constraints": [ { - "class": "Tomaj\\NetteApi\\Validation\\Length", - "args": { - "min": 1, - "max": 50 - } + "@class": "Tomaj\\NetteApi\\Validation\\Length", + "min": 1, + "max": 50 } ], "casterClass": null, @@ -149,43 +153,47 @@ "casterSchema": null, "children": [], "item": { + "@class": "Tomaj\\NetteApi\\Input\\Field", "property": "items", "externalName": "items", - "source": "body", + "source": { + "enum": "Tomaj\\NetteApi\\Input\\Source", + "value": "body" + }, "typeName": "Tomaj\\NetteApi\\Test\\Input\\Fixtures\\ItemInput", - "builtin": false, "nullable": false, "hasDefault": false, "default": null, "description": null, "examples": [], "listItem": null, - "listItemBuiltin": false, "enumClass": null, "enumInt": false, "enumValues": [], - "constraintSpecs": [], + "constraints": [], "casterClass": null, "casterArguments": [], "casterSchema": null, "children": [ { + "@class": "Tomaj\\NetteApi\\Input\\Field", "property": "sku", "externalName": "sku", - "source": "body", + "source": { + "enum": "Tomaj\\NetteApi\\Input\\Source", + "value": "body" + }, "typeName": "string", - "builtin": true, "nullable": false, "hasDefault": false, "default": null, "description": null, "examples": [], "listItem": null, - "listItemBuiltin": false, "enumClass": null, "enumInt": false, "enumValues": [], - "constraintSpecs": [], + "constraints": [], "casterClass": null, "casterArguments": [], "casterSchema": null, @@ -194,27 +202,28 @@ "dtoClass": "Tomaj\\NetteApi\\Test\\Input\\Fixtures\\ItemInput" }, { + "@class": "Tomaj\\NetteApi\\Input\\Field", "property": "quantity", "externalName": "quantity", - "source": "body", + "source": { + "enum": "Tomaj\\NetteApi\\Input\\Source", + "value": "body" + }, "typeName": "int", - "builtin": true, "nullable": false, "hasDefault": false, "default": null, "description": null, "examples": [], "listItem": null, - "listItemBuiltin": false, "enumClass": null, "enumInt": false, "enumValues": [], - "constraintSpecs": [ + "constraints": [ { - "class": "Tomaj\\NetteApi\\Validation\\Range", - "args": { - "min": 1 - } + "@class": "Tomaj\\NetteApi\\Validation\\Range", + "min": 1, + "max": null } ], "casterClass": null, @@ -231,22 +240,24 @@ "dtoClass": "Tomaj\\NetteApi\\Test\\Input\\Fixtures\\CreateOrderInput" }, { + "@class": "Tomaj\\NetteApi\\Input\\Field", "property": "deliveryAt", "externalName": "deliveryAt", - "source": "body", + "source": { + "enum": "Tomaj\\NetteApi\\Input\\Source", + "value": "body" + }, "typeName": "DateTimeImmutable", - "builtin": false, "nullable": true, "hasDefault": true, "default": null, "description": null, "examples": [], "listItem": null, - "listItemBuiltin": false, "enumClass": null, "enumInt": false, "enumValues": [], - "constraintSpecs": [], + "constraints": [], "casterClass": null, "casterArguments": [], "casterSchema": null, diff --git a/tests/Input/RequestInputTest.php b/tests/Input/RequestInputTest.php new file mode 100644 index 000000000..b5c50c7a8 --- /dev/null +++ b/tests/Input/RequestInputTest.php @@ -0,0 +1,73 @@ +server = $_SERVER; + RequestInput::reset(); + $_GET = []; + $_POST = []; + $_FILES = []; + } + + protected function tearDown(): void + { + $_SERVER = $this->server; + RequestInput::reset(); + } + + public function testARejectedMediaTypeIsRejectedAgainOnTheNextRead(): void + { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_SERVER['CONTENT_TYPE'] = 'text/plain'; + RequestInput::setRawBody('hello'); + + for ($attempt = 1; $attempt <= 2; $attempt++) { + try { + RequestInput::boot('Handler', [MediaTypes::JSON], true, true); + $this->fail(sprintf('attempt %d accepted text/plain', $attempt)); + } catch (UnsupportedMediaTypeException) { + $this->assertNull(RequestInput::mediaType()); + } + } + } + + public function testASecondBootOfTheSameHandlerKeepsTheFirstRead(): void + { + $_GET = ['page' => '4']; + $first = $this->payload(new ListUsersHandler()); + $_GET = ['page' => '9']; + $second = $this->payload(new ListUsersHandler()); + $this->assertSame(4, $first['page']); + $this->assertSame(4, $second['page']); + + RequestInput::reset(); + $_GET = ['page' => '9']; + $this->assertSame(9, $this->payload(new ListUsersHandler())['page']); + } + + /** + * @return array + */ + private function payload(object $handler): array + { + $processor = new ParamsProcessor($handler->params()); + $this->assertFalse($processor->isError(), (string) json_encode($processor->getErrors())); + + return $handler->handle($processor->getValues())->getPayload(); + } +} diff --git a/tests/Input/ReviewContractTest.php b/tests/Input/ReviewContractTest.php deleted file mode 100644 index d52ec7b26..000000000 --- a/tests/Input/ReviewContractTest.php +++ /dev/null @@ -1,790 +0,0 @@ -json(['price' => '12.50', 'prices' => ['1.00', '2.25']]); - $handler = new MoneyHandler(); - $processor = new ParamsProcessor($handler->params()); - $this->assertFalse($processor->isError(), (string) json_encode($processor->getErrors())); - $this->assertSame(['price' => 1250, 'prices' => [100, 225]], $handler->handle($processor->getValues())->getPayload()); - - $fields = DtoCompiler::compile(MoneyHandler::class)->fields; - $this->assertSame([], $fields[0]->children); - $this->assertSame(['type' => 'string', 'example' => '12.50'], SchemaBuilder::build($fields[0], true)); - $this->assertNull($fields[1]->item); - - $this->json(['price' => 'abc', 'prices' => []]); - $this->assertSame(['price' => ['Use a decimal amount, for example 12.50']], $this->errors(new MoneyHandler())); - } - - public function testNamedCasterArgumentsSurviveTheCompiledContainer(): void - { - $_GET = ['value' => 'X', 'other' => 'Y']; - $this->assertSame(['value' => 'STARTXEND', 'other' => 'AYB'], $this->payload(new NamedCasterHandler())); - $compiled = DtoCompiler::compile(WireSchemaHandler::class); - $imported = DtoMetadata::import($compiled->export()); - $this->assertSame($compiled->fields[0]->casterSchema, $imported->fields[0]->casterSchema); - $this->assertSame('integer', $imported->fields[0]->casterSchema['type'] ?? null); - - $export = $compiled->fields[0]->export(); - $export['casterSchema'] = [0 => 'stray', 'type' => 'integer']; - $this->assertSame(['type' => 'integer'], Field::import($export)->casterSchema); - - DtoMetadataRegistry::install([NamedCasterHandler::class => DtoCompiler::compile(NamedCasterHandler::class)->export()]); - $this->assertTrue(DtoMetadataRegistry::installs(NamedCasterHandler::class)); - $this->assertSame(['value' => 'STARTXEND', 'other' => 'AYB'], $this->payload(new NamedCasterHandler())); - } - - public function testNulByteIsAFieldError(): void - { - try { - new DateFormat('d.m.Y')->cast("24.12.2026\0"); - $this->fail('NUL byte was accepted'); - } catch (CastException $exception) { - $this->assertSame('Date must match d.m.Y, for example 24.12.2026', $exception->getMessage()); - } - - $this->json(['day' => "24.12.2026\u{0}"]); - $this->assertSame(['day' => ['Date must match d.m.Y, for example 24.12.2026']], $this->errors(new NulDateHandler())); - } - - public function testCompiledCasterSchemaUsesTheWireType(): void - { - $fields = DtoCompiler::compile(WireSchemaHandler::class)->fields; - $this->assertSame('integer', SchemaBuilder::build($fields[0], true)['type']); - $this->assertSame(new UnixTimestamp()->openApiSchema()['example'], SchemaBuilder::build($fields[0], true)['example']); - $this->assertSame(['type' => 'string'], SchemaBuilder::build($fields[1], true)); - } - - public function testSiblingDefaultsAreVisibleToConstraints(): void - { - $this->assertCount(2, DtoCompiler::compile(SiblingDefaultsHandler::class)->fields); - $this->assertCompileFails(BadSiblingDefaultsHandler::class, 'BadSiblingDefaultsInput::$right default does not satisfy #[SameAs]: Must equal left'); - } - - public function testDefaultsAfterARequiredFieldAreChecked(): void - { - $this->assertCompileFails(RequiredThenBadDefaultHandler::class, 'RequiredThenBadDefaultInput::$right default does not satisfy #[SameAs]'); - } - - public function testValidListDefaultsOfEveryItemType(): void - { - $fields = DtoCompiler::compile(ListDefaultsHandler::class)->fields; - $this->assertSame([[1, 2.5], [true], ['a'], [UserStatus::Active], ['x']], array_map(static fn (Field $field): mixed => $field->default, $fields)); - $this->assertCompileFails(BadFloatListDefaultHandler::class, 'default item 1 is string, but the property is list'); - $this->assertCompileFails(BadBoolListDefaultHandler::class, 'default item 0 is int, but the property is list'); - $this->assertCompileFails(BadStringListDefaultHandler::class, 'default item 0 is int, but the property is list'); - $this->assertCompileFails(BadEnumListDefaultHandler::class, 'default item 0 is string, but the property is list<' . UserStatus::class . '>'); - $this->assertCompileFails(BadCastListDefaultHandler::class, 'default item 0 is int, but the property is list'); - } - - public function testLengthOnAListIsCheckedBeforeItsItems(): void - { - $_GET = ['ids' => ['x', 'y', 'z']]; - $this->assertSame(['ids' => ['Value must have between 1 and 2 items']], $this->errors(new LengthListHandler())); - RequestInput::reset(); - $_GET = ['ids' => []]; - $this->assertSame(['ids' => ['Value must have between 1 and 2 items']], $this->errors(new LengthListHandler())); - RequestInput::reset(); - $_GET = ['ids' => ['1', '2'], 'min' => ['x']]; - $this->assertSame(['min[0]' => ['Value must be an integer']], $this->errors(new LengthListHandler())); - RequestInput::reset(); - $_GET = ['ids' => ['1'], 'min' => ['4', '5', '6']]; - $this->assertSame(['ids' => [1], 'min' => [4, 5, 6]], $this->payload(new LengthListHandler())); - } - - public function testDefaultsInTheSchema(): void - { - $fields = DtoCompiler::compile(SchemaDefaultsHandler::class)->fields; - $this->assertSame('active', SchemaBuilder::build($fields[0], true)['default']); - $this->assertSame('a,b', SchemaBuilder::build($fields[1], true)['default']); - $this->assertArrayNotHasKey('default', SchemaBuilder::build($fields[2], true)); - $this->assertSame(2, SchemaBuilder::build($fields[3], true)['default']); - } - - public function testListDefaultItemsAreChecked(): void - { - $this->assertCompileFails(BadListDefaultHandler::class, "BadListDefaultInput::\$items default item 1 is string, but the property is list"); - $this->assertCompileFails(MapDefaultHandler::class, 'MapDefaultInput::$items default must be a list'); - } - - public function testConstructorParametersThatTheMapperCannotPass(): void - { - $this->assertCompileFails(SecretArgumentHandler::class, 'SecretArgumentInput::__construct() has the required parameter $secret that is not a promoted property'); - $this->assertCompileFails(VariadicArgumentHandler::class, 'VariadicArgumentInput::__construct() parameter $rest is variadic'); - $this->assertCompileFails(ReferenceArgumentHandler::class, 'ReferenceArgumentInput::__construct() parameter $page is passed by reference'); - $this->assertCount(1, DtoCompiler::compile(OptionalArgumentHandler::class)->fields); - } - - /** - * @return iterable - */ - public static function malformedIntegers(): iterable - { - foreach (['++0', '--0', '+-0', '-+000', "1\n", ' 1', '1 ', '+', '-', ''] as $value) { - yield json_encode($value, JSON_THROW_ON_ERROR) => [$value]; - } - } - - #[DataProvider('malformedIntegers')] - public function testMalformedIntegersAreRejected(string $value): void - { - $this->expectException(ConversionFailed::class); - ScalarCoercer::toInt($value); - } - - public function testSingleSignedIntegersAndAnchoredPatterns(): void - { - $this->assertSame([5, -5, 0, 7], [ScalarCoercer::toInt('+5'), ScalarCoercer::toInt('-5'), ScalarCoercer::toInt('-0'), ScalarCoercer::toInt('007')]); - foreach (["1\n", "1.5\n"] as $value) { - try { - ScalarCoercer::toFloat($value); - $this->fail('float with a newline was accepted'); - } catch (ConversionFailed) { - $this->addToAssertionCount(1); - } - } - $this->expectException(ConversionFailed::class); - ScalarCoercer::toDateTime("2026-11-06T14:30:00Z\n"); - } - - public function testEnumBackingTypeComesFromItsCases(): void - { - $this->assertSame(DependencyItemEnum::First, ScalarCoercer::toEnum('1', DependencyItemEnum::class)); - $this->expectException(ConversionFailed::class); - ScalarCoercer::toEnum('x', EmptyStringEnum::class); - } - - public function testDtoBoundaryRejectsSignedZeroGarbage(): void - { - $_GET = ['page' => '--0']; - $this->assertArrayHasKey('page', $this->errors(new OptionalArgumentHandler())); - } - - public function testPatternsAreExportedOnlyWhenPortable(): void - { - $this->assertSame('^[a-z]+$', new Pattern('{^[a-z]+$}')->expression()); - $this->assertSame('^[a-z]+$', new Pattern('(^[a-z]+$)')->expression()); - $this->assertSame('^[a-z]+$', new Pattern('[^[a-z]+$]')->expression()); - $this->assertSame('^[a-z]+$', new Pattern('<^[a-z]+$>')->expression()); - $this->assertSame('^[a-z]+$', new Pattern('#^[a-z]+$#uD')->expression()); - $this->assertNull(new Pattern('{^[a-z]+$}i')->expression()); - $this->assertNull(new Pattern('/^[a-z]+$/i')->expression()); - $this->assertNull(new Pattern('/^[a-z]+$/x')->expression()); - } - - public function testEveryReflectedDependencyRebuildsTheContainer(): void - { - $files = array_map(basename(...), DtoCompiler::compile(DependencyHandler::class)->files); - foreach (['DependencyHandler.php', 'DependencyInput.php', 'DependencyParentInput.php', 'DependencyCaster.php', 'DependencyEnum.php', 'DependencyItemEnum.php', 'DependencyConstraint.php', 'DependencyTrait.php', 'DependencyNestedTrait.php', 'DependencyParentTrait.php'] as $file) { - $this->assertContains($file, $files); - } - $this->assertSame(array_values(array_unique($files)), $files); - } - - public function testNativeListsAndObjectsCannotComeFromAPathOrHeader(): void - { - $this->assertCompileFails(HeaderListHandler::class, "HeaderListInput::\$tags reads #[Header], which is one string, so it cannot be list. Use a scalar type or split the string, for example #[Cast(Split::class, ',')]."); - } - - public function testQueryListIsAdvertisedInTheFormPhpReads(): void - { - $parameters = new ParameterBuilder()->build(new QueryListHandler()); - $this->assertSame(['ids[]', 'csv'], array_column($parameters, 'name')); - $this->assertSame(['type' => 'array', 'items' => ['type' => 'integer']], $parameters[0]['schema']); - - $name = rawurlencode((string) $parameters[0]['name']); - $query = sprintf('%s=3&%s=4&csv=a,b', $name, $name); - parse_str($query, $_GET); - $this->assertSame(['ids' => [3, 4], 'csv' => ['a', 'b']], $this->payload(new QueryListHandler())); - } - - /** - * @param array $body - */ - private function json(array $body): void - { - RequestInput::reset(); - RequestInput::setRawBody((string) json_encode($body)); - $_SERVER['CONTENT_TYPE'] = 'application/json'; - $_SERVER['REQUEST_METHOD'] = 'POST'; - } - - /** - * @return array - */ - private function payload(TypedHandler $handler): array - { - $processor = new ParamsProcessor($handler->params()); - $this->assertFalse($processor->isError(), (string) json_encode($processor->getErrors())); - - return $handler->handle($processor->getValues())->getPayload(); - } - - /** - * @return array - */ - private function errors(TypedHandler $handler): array - { - $processor = new ParamsProcessor($handler->params()); - $this->assertTrue($processor->isError()); - - return $processor->getErrors(); - } - - private function assertCompileFails(string $handler, string $needle): void - { - try { - DtoCompiler::compile($handler); - $this->fail($handler); - } catch (\LogicException $exception) { - $this->assertStringContainsString($needle, $exception->getMessage(), $handler); - } - } -} - -final readonly class Money -{ - private function __construct(public int $cents) - { - } - - public static function fromCents(int $cents): self - { - return new self($cents); - } -} - -final readonly class MoneyCaster implements CasterInterface, OpenApiCasterInterface -{ - public function cast(mixed $value): Money - { - if (!is_string($value) || preg_match('/^\d+\.\d{2}\z/', $value) !== 1) { - throw new CastException('Use a decimal amount, for example 12.50'); - } - - return Money::fromCents((int) str_replace('.', '', $value)); - } - - /** - * @return array{type: string, example: string} - */ - public function openApiSchema(): array - { - return ['type' => 'string', 'example' => '12.50']; - } -} - -final readonly class MoneyListCaster implements CasterInterface -{ - /** - * @return list - */ - public function cast(mixed $value): array - { - if (!is_array($value)) { - throw new CastException('Use a list of amounts'); - } - - return array_values(array_map(static fn (mixed $item): Money => new MoneyCaster()->cast($item), $value)); - } -} - -final readonly class MoneyInput -{ - /** @param list $prices */ - public function __construct( - #[Body] #[Cast(MoneyCaster::class)] public Money $price, - #[Body] #[Cast(MoneyListCaster::class)] public array $prices, - ) { - } -} - -final class MoneyHandler extends TypedHandler -{ - public function handleDto(MoneyInput $input): ResponseInterface - { - return new JsonApiResponse(200, ['price' => $input->price->cents, 'prices' => array_map(static fn (Money $money): int => $money->cents, $input->prices)]); - } -} - -final readonly class NamedCaster implements CasterInterface -{ - public function __construct(private string $prefix = 'A', private string $suffix = 'B') - { - } - - public function cast(mixed $value): string - { - return $this->prefix . (is_string($value) ? $value : '') . $this->suffix; - } -} - -final readonly class NamedCasterInput -{ - public function __construct( - #[Query] #[Cast(NamedCaster::class, suffix: 'END', prefix: 'START')] public string $value, - #[Query] #[Cast(NamedCaster::class)] public string $other, - ) { - } -} - -final class NamedCasterHandler extends TypedHandler -{ - public function handleDto(NamedCasterInput $input): ResponseInterface - { - return new JsonApiResponse(200, ['value' => $input->value, 'other' => $input->other]); - } -} - -final readonly class NulDateInput -{ - public function __construct(#[Body] #[Cast(DateFormat::class, 'd.m.Y')] public \DateTimeImmutable $day) - { - } -} - -final class NulDateHandler extends TypedHandler -{ - public function handleDto(NulDateInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class TextToIntCaster implements CasterInterface -{ - public function cast(mixed $value): int - { - return $value === 'one' ? 1 : 0; - } -} - -final readonly class WireSchemaInput -{ - public function __construct( - #[Query] #[Cast(UnixTimestamp::class)] public \DateTimeImmutable $at, - #[Query] #[Cast(TextToIntCaster::class)] public int $count, - ) { - } -} - -final class WireSchemaHandler extends TypedHandler -{ - public function handleDto(WireSchemaInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_PARAMETER)] -final readonly class SameAs implements ConstraintInterface -{ - public function __construct(private string $other) - { - } - - public function validate(mixed $value, ConstraintContext $context): ?string - { - return $value === $context->value($this->other) ? null : 'Must equal ' . $this->other; - } -} - -final readonly class SiblingDefaultsInput -{ - public function __construct( - #[Query] public string $left = 'same', - #[Query] #[SameAs('left')] public string $right = 'same', - ) { - } -} - -final class SiblingDefaultsHandler extends TypedHandler -{ - public function handleDto(SiblingDefaultsInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class BadSiblingDefaultsInput -{ - public function __construct( - #[Query] #[SameAs('left')] public string $right = 'other', - #[Query] public string $left = 'same', - ) { - } -} - -final class BadSiblingDefaultsHandler extends TypedHandler -{ - public function handleDto(BadSiblingDefaultsInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class BadListDefaultInput -{ - /** @param list $items */ - public function __construct(#[Query] public array $items = [1, 'not-an-int']) - { - } -} - -final class BadListDefaultHandler extends TypedHandler -{ - public function handleDto(BadListDefaultInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class MapDefaultInput -{ - /** @param list $items */ - public function __construct(#[Query] public array $items = ['a' => 1]) - { - } -} - -final class MapDefaultHandler extends TypedHandler -{ - public function handleDto(MapDefaultInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class SecretArgumentInput -{ - public function __construct(#[Query] public int $page, string $secret) - { - unset($secret); - } -} - -final class SecretArgumentHandler extends TypedHandler -{ - public function handleDto(SecretArgumentInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class VariadicArgumentInput -{ - public function __construct(#[Query] public int $page, string ...$rest) - { - unset($rest); - } -} - -final class VariadicArgumentHandler extends TypedHandler -{ - public function handleDto(VariadicArgumentInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final class ReferenceArgumentInput -{ - public function __construct(#[Query] public int &$page) - { - } -} - -final class ReferenceArgumentHandler extends TypedHandler -{ - public function handleDto(ReferenceArgumentInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class OptionalArgumentInput -{ - public function __construct(#[Query] public int $page = 1, string $mode = 'fast') - { - unset($mode); - } -} - -final class OptionalArgumentHandler extends TypedHandler -{ - public function handleDto(OptionalArgumentInput $input): ResponseInterface - { - return new JsonApiResponse(200, ['page' => $input->page]); - } -} - -final readonly class HeaderListInput -{ - /** @param list $tags */ - public function __construct(#[Header('X-Tags')] public array $tags = []) - { - } -} - -final class HeaderListHandler extends TypedHandler -{ - public function handleDto(HeaderListInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class QueryListInput -{ - /** - * @param list $ids - * @param list $csv - */ - public function __construct( - #[Query] public array $ids, - #[Query] #[Cast(Split::class, ',')] public array $csv, - ) { - } -} - -final class QueryListHandler extends TypedHandler -{ - public function handleDto(QueryListInput $input): ResponseInterface - { - return new JsonApiResponse(200, ['ids' => $input->ids, 'csv' => $input->csv]); - } -} - -final readonly class RequiredThenBadDefaultInput -{ - public function __construct( - #[Query] public string $left, - #[Query] #[SameAs('left')] public string $right = 'x', - ) { - } -} - -final class RequiredThenBadDefaultHandler extends TypedHandler -{ - public function handleDto(RequiredThenBadDefaultInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class ListDefaultsInput -{ - /** - * @param list $floats - * @param list $flags - * @param list $names - * @param list $statuses - * @param list $split - */ - public function __construct( - #[Query] public array $floats = [1, 2.5], - #[Query] public array $flags = [true], - #[Query] public array $names = ['a'], - #[Query] public array $statuses = [UserStatus::Active], - #[Query] #[Cast(Split::class, ',')] public array $split = ['x'], - ) { - } -} - -final class ListDefaultsHandler extends TypedHandler -{ - public function handleDto(ListDefaultsInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class BadFloatListDefaultInput -{ - /** @param list $items */ - public function __construct(#[Query] public array $items = [1.5, 'x']) - { - } -} - -final class BadFloatListDefaultHandler extends TypedHandler -{ - public function handleDto(BadFloatListDefaultInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class BadBoolListDefaultInput -{ - /** @param list $items */ - public function __construct(#[Query] public array $items = [1]) - { - } -} - -final class BadBoolListDefaultHandler extends TypedHandler -{ - public function handleDto(BadBoolListDefaultInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class BadStringListDefaultInput -{ - /** @param list $items */ - public function __construct(#[Query] public array $items = [1]) - { - } -} - -final class BadStringListDefaultHandler extends TypedHandler -{ - public function handleDto(BadStringListDefaultInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class BadEnumListDefaultInput -{ - /** @param list $items */ - public function __construct(#[Query] public array $items = ['active']) - { - } -} - -final class BadEnumListDefaultHandler extends TypedHandler -{ - public function handleDto(BadEnumListDefaultInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class BadCastListDefaultInput -{ - /** @param list $items */ - public function __construct(#[Query] #[Cast(Split::class, ',')] public array $items = [1]) - { - } -} - -final class BadCastListDefaultHandler extends TypedHandler -{ - public function handleDto(BadCastListDefaultInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class LengthListInput -{ - /** - * @param list $ids - * @param list $min - */ - public function __construct( - #[Query] #[Length(min: 1, max: 2)] public array $ids, - #[Query] #[Length(min: 1)] public array $min = [1], - ) { - } -} - -final class LengthListHandler extends TypedHandler -{ - public function handleDto(LengthListInput $input): ResponseInterface - { - return new JsonApiResponse(200, ['ids' => $input->ids, 'min' => $input->min]); - } -} - -final readonly class StatusCaster implements CasterInterface -{ - public function cast(mixed $value): UserStatus - { - return UserStatus::from(is_string($value) ? $value : 'active'); - } -} - -final readonly class SchemaDefaultsInput -{ - public function __construct( - #[Query] public UserStatus $status = UserStatus::Active, - #[Query] #[Cast(NamedCaster::class)] public string $text = 'a,b', - #[Query] #[Cast(StatusCaster::class)] public UserStatus $casted = UserStatus::Active, - #[Query] public Priority $priority = Priority::High, - ) { - } -} - -final class SchemaDefaultsHandler extends TypedHandler -{ - public function handleDto(SchemaDefaultsInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -enum EmptyStringEnum: string -{ -} diff --git a/tests/Input/Round10Test.php b/tests/Input/Round10Test.php deleted file mode 100644 index 2f6367f1a..000000000 --- a/tests/Input/Round10Test.php +++ /dev/null @@ -1,319 +0,0 @@ -json(['ids' => array_fill(0, 5000, 'x')]); - $errors = $this->errors(new ManyIdsHandler()); - - $this->assertCount(DtoMapper::MAX_ERRORS + 1, $errors); - $this->assertSame(['Value must be an integer'], $errors['ids[0]']); - $this->assertSame(['Value must be an integer'], $errors['ids[99]']); - $this->assertArrayNotHasKey('ids[100]', $errors); - $this->assertSame(['Only the first 100 errors are reported, the rest of the request was not checked'], $errors['body']); - $this->assertArrayNotHasKey('ids', $errors); - } - - public function testTheBudgetIsOnePerRequestAcrossNestedLists(): void - { - $leaf = array_fill(0, 100, new \stdClass()); - $middle = array_fill(0, 100, ['cs' => $leaf]); - $outer = array_fill(0, 100, ['bs' => $middle]); - $this->json(['as' => $outer]); - - $errors = $this->errors(new NestedListsHandler()); - $messages = array_merge(...array_values($errors)); - - $this->assertLessThanOrEqual(DtoMapper::MAX_ERRORS + 1, count($messages)); - $this->assertContains('Only the first 100 errors are reported, the rest of the request was not checked', $messages); - $this->assertCount(1, array_filter($messages, static fn (string $message): bool => str_starts_with($message, 'Only the first'))); - } - - public function testTheBudgetAlsoStopsLaterFields(): void - { - $this->json(['ids' => array_fill(0, 150, 'x'), 'other' => 'y']); - $errors = $this->errors(new BudgetHandler()); - - $this->assertArrayNotHasKey('other', $errors); - $this->assertCount(101, $errors); - } - - public function testNothingIsLeftUncheckedUpToTheCapSoThereIsNoNote(): void - { - $this->json(['ids' => array_fill(0, 99, 'x')]); - $errors = $this->errors(new ManyIdsHandler()); - $this->assertCount(99, $errors); - $this->assertArrayNotHasKey('ids', $errors); - - // exactly the budget: nothing was left unchecked, so there is nothing to apologise for - $this->json(['ids' => array_fill(0, 100, 'x')]); - $errors = $this->errors(new ManyIdsHandler()); - $this->assertCount(100, $errors); - $this->assertArrayNotHasKey('body', $errors); - - $this->json(['ids' => array_fill(0, 101, 'x')]); - $errors = $this->errors(new ManyIdsHandler()); - $this->assertCount(101, $errors); - $this->assertArrayHasKey('body', $errors); - $this->assertArrayNotHasKey('ids[100]', $errors); - } - - public function testManyInvalidItemsAreCheckedInLinearTime(): void - { - $this->json(['ids' => array_merge(array_fill(0, 100, 1), array_fill(0, 60000, 'x'))]); - $start = microtime(true); - $this->errors(new ManyIdsHandler()); - $this->assertLessThan(2.0, microtime(true) - $start); - } - - public function testSplitPropertyIsOneStringInputWithoutAnArrayDefault(): void - { - $param = new SplitHandler()->params()[0]; - $this->assertFalse($param->isMulti()); - $this->assertNull($param->getDefault()); - $this->assertSame(['type' => 'string', 'example' => 'red,green,blue'], $param->getOpenApiSchema()); - - $parameters = new ParameterBuilder()->build(new SplitHandler()); - $this->assertSame(['tags', 'label'], array_column($parameters, 'name')); - $this->assertSame('plain', $parameters[1]['schema']['default']); - $this->assertSame('plain', new SplitHandler()->params()[1]->getDefault()); - - $_GET = ['tags' => 'a,b']; - $this->assertSame(['tags' => ['a', 'b']], $this->payload(new SplitHandler())); - RequestInput::reset(); - $_GET = []; - $this->assertSame(['tags' => []], $this->payload(new SplitHandler())); - } - - public function testOpenApiListsTheUnsupportedMediaTypeResponseOfATypedBody(): void - { - foreach ([false, true] as $problemDetails) { - $builder = new ResponseBuilder($problemDetails); - $withBody = $builder->build(new ManyIdsHandler(), new NoAuthorization(), true, new SchemaRegistry()); - $this->assertSame([400, 415, 500], array_keys($withBody)); - $this->assertSame('Unsupported media type', $withBody[415]['description']); - $this->assertArrayHasKey($problemDetails ? 'application/problem+json; charset=utf-8' : 'application/json; charset=utf-8', $withBody[415]['content']); - - $queryOnly = $builder->build(new SplitHandler(), new NoAuthorization(), true, new SchemaRegistry()); - $this->assertSame([400, 500], array_keys($queryOnly)); - } - - $classic = new ResponseBuilder()->build(new EchoHandler(), new NoAuthorization(), true, new SchemaRegistry()); - $this->assertArrayNotHasKey(415, $classic); - } - - public function testANullableEnumListsNullInTheBodyAndNothingNullableOnTheWire(): void - { - $params = DtoCompiler::compile(LevelHandler::class)->inputParams(); - - $this->assertSame(['type' => 'string', 'enum' => ['low', 'high', null], 'nullable' => true], $params[1]->getOpenApiSchema()); - $this->assertSame(['type' => 'string', 'enum' => ['low', 'high']], $params[2]->getOpenApiSchema()); - $this->assertSame([ - 'type' => 'object', - 'properties' => ['text' => ['type' => 'string'], 'author' => ['type' => 'string', 'nullable' => true]], - 'required' => ['text'], - 'nullable' => true, - ], $params[0]->getOpenApiSchema()); - } - - /** - * @param array $body - */ - private function json(array $body): void - { - RequestInput::reset(); - RequestInput::setRawBody((string) json_encode($body)); - $_SERVER['CONTENT_TYPE'] = 'application/json'; - $_SERVER['REQUEST_METHOD'] = 'POST'; - } - - /** - * @return array - */ - private function errors(TypedHandler $handler): array - { - $processor = new ParamsProcessor($handler->params()); - $this->assertTrue($processor->isError()); - - return $processor->getErrors(); - } - - /** - * @return array - */ - private function payload(TypedHandler $handler): array - { - $processor = new ParamsProcessor($handler->params()); - $this->assertFalse($processor->isError(), (string) json_encode($processor->getErrors())); - - return $handler->handle($processor->getValues())->getPayload(); - } -} - -final readonly class Round10Note -{ - public function __construct(#[Body] public string $text, #[Body] public ?string $author = null) - { - } -} - -enum Round10Level: string -{ - case Low = 'low'; - case High = 'high'; -} - -final readonly class LevelInput -{ - public function __construct( - #[Body] public ?Round10Note $note = null, - #[Body] public ?Round10Level $level = null, - #[Query] public ?Round10Level $filter = null, - ) { - } -} - -final class LevelHandler extends TypedHandler -{ - public function handleDto(LevelInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class ManyIdsInput -{ - /** @param list $ids */ - public function __construct(#[Body] public array $ids) - { - } -} - -final class ManyIdsHandler extends TypedHandler -{ - public function handleDto(ManyIdsInput $input): ResponseInterface - { - return new JsonApiResponse(200, ['count' => count($input->ids)]); - } -} - -final readonly class SplitInput -{ - /** @param list $tags */ - public function __construct( - #[Query] #[Cast(Split::class, ',')] public array $tags = [], - #[Query] #[Cast(UpperCaster::class)] public string $label = 'plain', - ) { - } -} - -final class SplitHandler extends TypedHandler -{ - public function handleDto(SplitInput $input): ResponseInterface - { - return new JsonApiResponse(200, ['tags' => $input->tags]); - } -} - -final readonly class UpperCaster implements CasterInterface -{ - public function cast(mixed $value): string - { - return strtoupper(is_string($value) ? $value : ''); - } -} - -final readonly class BudgetLeaf -{ - public function __construct(#[Body] public string $x) - { - } -} - -final readonly class BudgetMiddle -{ - /** @param list $cs */ - public function __construct(#[Body] public array $cs) - { - } -} - -final readonly class BudgetOuter -{ - /** @param list $bs */ - public function __construct(#[Body] public array $bs) - { - } -} - -final readonly class NestedListsInput -{ - /** @param list $as */ - public function __construct(#[Body] public array $as) - { - } -} - -final class NestedListsHandler extends TypedHandler -{ - public function handleDto(NestedListsInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class BudgetInput -{ - /** @param list $ids */ - public function __construct(#[Body] public array $ids, #[Body] public int $other) - { - } -} - -final class BudgetHandler extends TypedHandler -{ - public function handleDto(BudgetInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} diff --git a/tests/Input/Round11Test.php b/tests/Input/Round11Test.php deleted file mode 100644 index 05dba477d..000000000 --- a/tests/Input/Round11Test.php +++ /dev/null @@ -1,1042 +0,0 @@ - - */ - public static function invalidHandlers(): \Iterator - { - yield 'nested dto in query' => [R11QueryDtoHandler::class, 'reads #[Query], which carries flat values']; - yield 'list of dto in query' => [R11QueryListHandler::class, 'cannot be list<']; - yield 'object default (date)' => [R11DateDefaultHandler::class, 'has a default of type DateTimeImmutable']; - yield 'object default (dto)' => [R11DtoDefaultHandler::class, 'has a default of type Tomaj\\NetteApi\\Test\\Input\\R11Inner']; - yield 'object default inside a list' => [R11ListObjectDefaultHandler::class, 'has a default of type']; - yield 'list of nullable items' => [R11NullableItemsHandler::class, 'one non-nullable type']; - yield 'list of unions' => [R11UnionItemsHandler::class, 'one non-nullable type']; - yield 'list of lists' => [R11NestedListsHandler::class, 'one non-nullable type']; - yield 'associative array' => [R11AssocHandler::class, 'not a list']; - yield 'unreadable doc type' => [R11OtherDocHandler::class, 'Found `iterable`']; - yield 'DateTime' => [R11PlainDateTimeHandler::class, 'Use DateTimeImmutable']; - yield 'DateTimeInterface' => [R11DateInterfaceHandler::class, 'Use DateTimeImmutable']; - yield 'empty split separator' => [R11EmptySplitHandler::class, 'Its constructor is __construct(string $separator)']; - yield 'split into ints' => [R11SplitIntsHandler::class, 'Split gives list']; - yield 'list with a trailing union' => [R11TrailingUnionHandler::class, 'Found `list|string`']; - yield 'array of arrays' => [R11ArrayOfArraysHandler::class, 'not a list']; - yield 'brackets with a trailing union' => [R11BracketUnionHandler::class, 'Found `string[]|int`']; - yield 'array of lists' => [R11ArrayOfListsHandler::class, 'not a list']; - yield 'union before brackets' => [R11UnionBracketsHandler::class, 'Found `int|string[]`']; - yield 'generic of array' => [R11GenericOfArrayHandler::class, 'Found `Collection`']; - yield 'caster constructor with typed and untyped parameters' => [R11BadCasterHandler::class, 'Its constructor is __construct(string $format, $loose)']; - yield 'caster without a constructor' => [R11NoCtorCasterHandler::class, 'Its constructor is __construct()']; - yield 'dash in a path name' => [R11PathDashHandler::class, 'can only have letters, digits and underscores']; - yield 'underscore in a header name' => [R11HeaderUnderscoreHandler::class, "Use #[Header('X-Foo')]"]; - } - - /** - * @param class-string $handler - */ - #[DataProvider('invalidHandlers')] - public function testCompileTimeMessage(string $handler, string $needle): void - { - $this->expectException(\LogicException::class); - $this->expectExceptionMessage($needle); - DtoCompiler::compile($handler); - } - - /** - * @param array $body - */ - private function json(array $body): void - { - RequestInput::reset(); - RequestInput::setRawBody((string) json_encode($body)); - $_SERVER['CONTENT_TYPE'] = 'application/json'; - $_SERVER['REQUEST_METHOD'] = 'POST'; - } - - /** - * @return array> - */ - private function errors(TypedHandler $handler): array - { - $processor = new ParamsProcessor($handler->params()); - $this->assertTrue($processor->isError()); - - return $processor->getErrors(); - } - - public function testPathNameMessageSuggestsTheCorrectedName(): void - { - $this->expectException(\LogicException::class); - $this->expectExceptionMessage("Use for example #[Path('a_b')]."); - DtoCompiler::compile(R11PathDashHandler::class); - } - - public function testSplitSeparatorMessageHasNoDoublePeriod(): void - { - try { - DtoCompiler::compile(R11EmptySplitHandler::class); - $this->fail('compiled'); - } catch (\LogicException $exception) { - $this->assertStringNotContainsString('..', $exception->getMessage()); - $this->assertStringContainsString("#[Cast(Split::class, ',')]. Its constructor", $exception->getMessage()); - $this->assertStringNotContainsString('d.m.Y', $exception->getMessage()); - } - } - - public function testAnUntypedParamTagFallsBackToTheVarOfTheProperty(): void - { - $this->assertSame('int', DtoCompiler::compile(R11VarFallbackHandler::class)->fields[0]->listItem); - } - - public function testEveryCommonPhpDocSpellingOfAListIsRead(): void - { - $fields = DtoCompiler::compile(R11DocFormsHandler::class)->fields; - - $this->assertSame( - ['string', 'string', 'string', 'string', 'string', 'string', 'int', 'float'], - array_map(static fn (Field $field): string => (string) $field->listItem, $fields), - ); - } - - public function testABodyWithoutAContentTypeIsNotIgnoredWhenAllFieldsAreOptional(): void - { - unset($_SERVER['CONTENT_TYPE']); - $_SERVER['REQUEST_METHOD'] = 'POST'; - RequestInput::setRawBody('{"a":"x"}'); - - $this->expectException(UnsupportedMediaTypeException::class); - $this->expectExceptionMessage('Content-Type is missing'); - new ParamsProcessor(new R11OptionalHandler()->params())->isError(); - } - - public function testAnEmptyRequestWithoutAContentTypeStillSucceedsWhenAllFieldsAreOptional(): void - { - unset($_SERVER['CONTENT_TYPE']); - $_SERVER['REQUEST_METHOD'] = 'POST'; - RequestInput::setRawBody(''); - - $this->assertFalse(new ParamsProcessor(new R11OptionalHandler()->params())->isError()); - } - - public function testMultipartWithPutAnswersWithTheReasonInsteadOfMissingFields(): void - { - $_SERVER['CONTENT_TYPE'] = 'multipart/form-data; boundary=x'; - $_SERVER['REQUEST_METHOD'] = 'PUT'; - RequestInput::setRawBody("--x\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\nv\r\n--x--\r\n"); - - $processor = new ParamsProcessor(new R11MultipartHandler()->params()); - $this->assertTrue($processor->isError()); - $this->assertSame( - ['body' => ['multipart/form-data is only parsed by PHP for POST requests, but this one is PUT. Send it with POST, or use application/json']], - $processor->getErrors(), - ); - } - - public function testAnEmptyMultipartPutIsNotAnError(): void - { - $_SERVER['CONTENT_TYPE'] = 'multipart/form-data; boundary=x'; - $_SERVER['REQUEST_METHOD'] = 'PUT'; - RequestInput::setRawBody(''); - - $this->assertFalse(new ParamsProcessor(new R11MultipartHandler()->params())->isError()); - } - - public function testTooManyFormFieldsDoNotReachTheErrorHandlerOfTheApplication(): void - { - $limit = (int) ini_get('max_input_vars'); - $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; - $_SERVER['REQUEST_METHOD'] = 'PUT'; - RequestInput::setRawBody(implode('&', array_map(static fn (int $i): string => 'f' . $i . '=1', range(1, $limit + 1)))); - - $seen = []; - set_error_handler(static function (int $level, string $message) use (&$seen): bool { - $seen[] = $message; - - return true; - }); - error_clear_last(); - try { - $this->assertTrue(new ParamsProcessor(new R11FormHandler()->params())->isError()); - $afterwards = $seen; - // the handler of the application is back in place: it receives the next warning - hex2bin('abc'); - } finally { - restore_error_handler(); - } - - // PHP's own handler runs only when ours declines the warning, and it would leave it in error_get_last() - $this->assertNull(error_get_last()); - $this->assertSame([], $afterwards); - $this->assertCount(1, $seen); - } - - public function testTooManyFormFieldsAreAnErrorInsteadOfAWarning(): void - { - $limit = (int) ini_get('max_input_vars'); - $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; - $_SERVER['REQUEST_METHOD'] = 'PUT'; - RequestInput::setRawBody(implode('&', array_map(static fn (int $i): string => 'f' . $i . '=1', range(1, $limit + 1)))); - - $processor = new ParamsProcessor(new R11FormHandler()->params()); - $this->assertTrue($processor->isError()); - $this->assertSame(['body' => ['Too many form fields']], $processor->getErrors()); - } - - public function testExactlyTheLimitOfFormFieldsIsAccepted(): void - { - $limit = (int) ini_get('max_input_vars'); - $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; - $_SERVER['REQUEST_METHOD'] = 'PUT'; - RequestInput::setRawBody(implode('&', array_map(static fn (int $i): string => 'f' . $i . '=1', range(1, $limit)))); - - $this->assertFalse(new ParamsProcessor(new R11FormHandler()->params())->isError()); - } - - public function testAJsonCharsetOtherThanUtf8IsRejected(): void - { - foreach (['application/json; charset=ISO-8859-1' => 'iso-8859-1', 'application/json;charset="latin1"' => 'latin1', 'application/json; CHARSET=latin1' => 'latin1'] as $contentType => $charset) { - RequestInput::reset(); - $_SERVER['CONTENT_TYPE'] = $contentType; - $_SERVER['REQUEST_METHOD'] = 'POST'; - RequestInput::setRawBody('{"a":"x"}'); - - $processor = new ParamsProcessor(new R11FormHandler()->params()); - $this->assertTrue($processor->isError(), $contentType); - $this->assertSame(['JSON must be UTF-8; the request says charset=' . $charset], $processor->getErrors()['body']); - } - - foreach (['application/json; charset=UTF-8', 'application/json; Charset="utf-8"', 'application/json'] as $contentType) { - RequestInput::reset(); - $_SERVER['CONTENT_TYPE'] = $contentType; - RequestInput::setRawBody('{"a":"x"}'); - $this->assertFalse(new ParamsProcessor(new R11FormHandler()->params())->isError(), $contentType); - } - } - - public function testTheBudgetStopsInsideAnObjectToo(): void - { - $this->json(['ids' => array_fill(0, 99, 'x'), 'inner' => new \stdClass()]); - $errors = $this->errors(new R11BudgetObjectHandler()); - - $this->assertSame(['Field is required'], $errors['inner.a']); - $this->assertSame(['Only the first 100 errors are reported, the rest of the request was not checked'], $errors['body']); - $this->assertArrayNotHasKey('inner', $errors); - $this->assertArrayNotHasKey('inner.b', $errors); - $this->assertArrayNotHasKey('inner.c', $errors); - } - - public function testTheBudgetEndsAtTheTopLevelToo(): void - { - $this->json(['ids' => array_fill(0, 99, 'x'), 'x' => 'a', 'y' => 'b']); - $errors = $this->errors(new R11BudgetTopHandler()); - - $this->assertSame(['Value must be an integer'], $errors['x']); - $this->assertSame(['Only the first 100 errors are reported, the rest of the request was not checked'], $errors['body']); - $this->assertArrayNotHasKey('y', $errors); - } - - public function testConstraintMessagesCountTowardsTheBudget(): void - { - $this->json(['items' => array_fill(0, 150, ['name' => 'too long'])]); - $errors = $this->errors(new R11ConstraintBudgetHandler()); - - $this->assertCount(101, $errors); - $this->assertSame(['Only the first 100 errors are reported, the rest of the request was not checked'], $errors['body']); - $this->assertArrayHasKey('items[99].name', $errors); - $this->assertArrayNotHasKey('items[100].name', $errors); - } - - public function testLengthCountsUtf8CharactersWhateverTheInternalEncoding(): void - { - $encoding = mb_internal_encoding(); - mb_internal_encoding('ISO-8859-1'); - try { - $this->assertNull(new Length(max: 3)->validate('čšž', new ConstraintContext('x', self::class, [], []))); - } finally { - mb_internal_encoding($encoding); - } - } - - public function testASmallRangeBoundIsNotPrintedAsZero(): void - { - $context = new ConstraintContext('x', self::class, [], []); - $this->assertSame('Value must be at most 1.0E-12', new Range(max: 1.0E-12)->validate(1.0, $context)); - $this->assertSame('Value must be at least -2.0E-11', new Range(min: -2.0E-11)->validate(-1.0, $context)); - $this->assertSame('Value must be at most 0.5', new Range(max: 0.5)->validate(1.0, $context)); - $this->assertSame('Value must be at least 0', new Range(min: 0)->validate(-1, $context)); - $this->assertSame('Value must be at most 0', new Range(max: 0.0)->validate(1, $context)); - $this->assertSame('Value must be at most 100', new Range(max: 100.0)->validate(101, $context)); - $this->assertSame('Value must be at most 9223372036854775806', new Range(max: PHP_INT_MAX - 1)->validate(PHP_INT_MAX, $context)); - } - - public function testRfc3339AcceptsLowercaseSeparators(): void - { - $_SERVER['CONTENT_TYPE'] = 'application/json'; - $_SERVER['REQUEST_METHOD'] = 'POST'; - foreach (['2024-05-01t10:00:00z' => '2024-05-01T10:00:00+00:00', '2024-05-01t10:00:00.5+02:00' => '2024-05-01T10:00:00+02:00'] as $input => $expected) { - RequestInput::reset(); - RequestInput::setRawBody((string) json_encode(['at' => $input])); - $processor = new ParamsProcessor(new R11DateHandler()->params()); - $this->assertFalse($processor->isError(), $input); - $at = $processor->getValues()['at']; - $this->assertInstanceOf(\DateTimeImmutable::class, $at); - $this->assertSame($expected, $at->format('c')); - } - - RequestInput::reset(); - RequestInput::setRawBody('{"at":"2016-12-31T23:59:60Z"}'); - $this->assertTrue(new ParamsProcessor(new R11DateHandler()->params())->isError()); - } - - /** - * @return \Iterator - */ - public static function patterns(): \Iterator - { - yield 'plain' => ['/^[a-z]+$/', '^[a-z]+$']; - yield 'escaped plus' => ['/^a\+\+$/', '^a\+\+$']; - yield 'lookahead and a group' => ['/^(?=a)(?:a|b)+x$/u', '^(?=a)(?:a|b)+x$']; - yield 'lookahead and named group' => ['/^(?=a)(?a|b)+x$/u', null]; - yield 'start anchor' => ['/\Aab\z/', null]; - yield 'end anchor Z' => ['/ab\Z/', null]; - yield 'possessive' => ['/^a++$/', null]; - yield 'possessive braces' => ['/^a{2}+$/', null]; - yield 'possessive question' => ['/^a?+$/', null]; - yield 'atomic group' => ['/^(?>a+)b$/', null]; - yield 'python group' => ['/(?Pa)/', null]; - yield 'inline flag' => ['/(?i)a/', null]; - yield 'scoped flag' => ['/(?i:a)b/', null]; - yield 'horizontal space' => ['/a\hb/', null]; - } - - #[DataProvider('patterns')] - public function testOnlyEcmaCompatiblePatternsReachOpenApi(string $pattern, ?string $expected): void - { - $this->assertSame($expected, new Pattern($pattern)->expression()); - } - - public function testAuthorizationFromAnApacheRewriteIsRead(): void - { - $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] = 'Bearer abc'; - $this->assertSame('Bearer abc', HeaderBag::get('Authorization')); - - $_SERVER['HTTP_AUTHORIZATION'] = 'Bearer direct'; - $this->assertSame('Bearer direct', HeaderBag::get('authorization')); - - unset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'], $_SERVER['HTTP_AUTHORIZATION']); - $this->assertFalse(HeaderBag::has('Authorization')); - } - - public function testTheUnsupportedMediaTypeResponseDescribesItsDetail(): void - { - $legacy = new ResponseBuilder()->build(new R11FormHandler(), new NoAuthorization(), true, new SchemaRegistry()); - $schema = $legacy[415]['content']['application/json; charset=utf-8']['schema']; - $this->assertSame([ - 'type' => 'object', - 'properties' => [ - 'status' => ['type' => 'string', 'enum' => ['error']], - 'message' => ['type' => 'string'], - 'detail' => ['type' => 'string', 'description' => 'Which media types the endpoint reads. Sent only when error details are on.'], - ], - 'required' => ['status', 'message'], - ], $schema); - $this->assertSame('Unsupported media type', $legacy[415]['description']); - - $problem = new ResponseBuilder(true)->build(new R11FormHandler(), new NoAuthorization(), true, new SchemaRegistry()); - $this->assertSame(['$ref' => '#/components/schemas/ProblemDetails'], $problem[415]['content']['application/problem+json; charset=utf-8']['schema']); - } -} - -final readonly class R11Inner -{ - public function __construct(#[Body] public string $q = 'x') - { - } -} - -final readonly class R11QueryDtoInput -{ - public function __construct( - #[Query] public R11Inner $x, - ) { - } -} - -final class R11QueryDtoHandler extends TypedHandler -{ - public function handleDto(R11QueryDtoInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11QueryListInput -{ - /** @param list $many */ - public function __construct( - #[Query] public array $many = [], - ) { - } -} - -final class R11QueryListHandler extends TypedHandler -{ - public function handleDto(R11QueryListInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11DateDefaultInput -{ - public function __construct( - #[Query] public \DateTimeImmutable $d = new \DateTimeImmutable('2020-01-01T00:00:00Z'), - ) { - } -} - -final class R11DateDefaultHandler extends TypedHandler -{ - public function handleDto(R11DateDefaultInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11DtoDefaultInput -{ - public function __construct( - #[Body] public R11Inner $i = new R11Inner(), - ) { - } -} - -final class R11DtoDefaultHandler extends TypedHandler -{ - public function handleDto(R11DtoDefaultInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11ListObjectDefaultInput -{ - /** @param list $items */ - public function __construct( - #[Body] public array $items = [new R11Inner()], - ) { - } -} - -final class R11ListObjectDefaultHandler extends TypedHandler -{ - public function handleDto(R11ListObjectDefaultInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11NullableItemsInput -{ - /** @param list $a */ - public function __construct( - #[Body] public array $a = [], - ) { - } -} - -final class R11NullableItemsHandler extends TypedHandler -{ - public function handleDto(R11NullableItemsInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11UnionItemsInput -{ - /** @param list $a */ - public function __construct( - #[Body] public array $a = [], - ) { - } -} - -final class R11UnionItemsHandler extends TypedHandler -{ - public function handleDto(R11UnionItemsInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11NestedListsInput -{ - /** @param list> $a */ - public function __construct( - #[Body] public array $a = [], - ) { - } -} - -final class R11NestedListsHandler extends TypedHandler -{ - public function handleDto(R11NestedListsInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11AssocInput -{ - /** @param array $a */ - public function __construct( - #[Body] public array $a = [], - ) { - } -} - -final class R11AssocHandler extends TypedHandler -{ - public function handleDto(R11AssocInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11OtherDocInput -{ - /** @param iterable $a */ - public function __construct( - #[Body] public array $a = [], - ) { - } -} - -final class R11OtherDocHandler extends TypedHandler -{ - public function handleDto(R11OtherDocInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11PlainDateTimeInput -{ - public function __construct( - #[Body] public \DateTime $d, - ) { - } -} - -final class R11PlainDateTimeHandler extends TypedHandler -{ - public function handleDto(R11PlainDateTimeInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11DateInterfaceInput -{ - public function __construct( - #[Body] public \DateTimeInterface $d, - ) { - } -} - -final class R11DateInterfaceHandler extends TypedHandler -{ - public function handleDto(R11DateInterfaceInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11EmptySplitInput -{ - /** @param list $a */ - public function __construct( - #[Query] #[Cast(Split::class, '')] public array $a = [], - ) { - } -} - -final class R11EmptySplitHandler extends TypedHandler -{ - public function handleDto(R11EmptySplitInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11SplitIntsInput -{ - /** @param list $a */ - public function __construct( - #[Query] #[Cast(Split::class, ',')] public array $a = [], - ) { - } -} - -final class R11SplitIntsHandler extends TypedHandler -{ - public function handleDto(R11SplitIntsInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11PathDashInput -{ - public function __construct( - #[Path('a-b')] public int $x, - ) { - } -} - -final class R11PathDashHandler extends TypedHandler -{ - public function handleDto(R11PathDashInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11HeaderUnderscoreInput -{ - public function __construct( - #[Header('X_Foo')] public ?string $x = null, - ) { - } -} - -final class R11HeaderUnderscoreHandler extends TypedHandler -{ - public function handleDto(R11HeaderUnderscoreInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11DocFormsInput -{ - /** - * @param list|null $a - * @param ?list $b - * @param null|list $c - * @param string[] $d - * @param non-empty-list $e - * @param list $f - * @phpstan-param list $g - * @psalm-param list $h - */ - public function __construct( - #[Query] public ?array $a = null, - #[Query] public ?array $b = null, - #[Query] public ?array $c = null, - #[Query] public ?array $d = null, - #[Query] public ?array $e = null, - #[Query] public ?array $f = null, - #[Query] public array $g = [], - #[Query] public array $h = [], - ) { - } -} - -final class R11DocFormsHandler extends TypedHandler -{ - public function handleDto(R11DocFormsInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11OptionalInput -{ - public function __construct( - #[Body] public ?string $a = null, - #[Body] public ?R11Color $c = null, - ) { - } -} - -final class R11OptionalHandler extends TypedHandler -{ - public function handleDto(R11OptionalInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11FormInput -{ - public function __construct( - #[Body] public ?string $a = null, - ) { - } -} - -#[Consumes(MediaTypes::MULTIPART)] -final class R11MultipartHandler extends TypedHandler -{ - public function handleDto(R11FormInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final class R11FormHandler extends TypedHandler -{ - public function handleDto(R11FormInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11TextInput -{ - public function __construct( - #[Body] #[Length(max: 3)] public string $text, - ) { - } -} - -final class R11TextHandler extends TypedHandler -{ - public function handleDto(R11TextInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11RangeInput -{ - public function __construct( - #[Query] #[Range(max: 1.0E-12)] public float $x = 0.0, - ) { - } -} - -final class R11RangeHandler extends TypedHandler -{ - public function handleDto(R11RangeInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11DateInput -{ - public function __construct( - #[Body] public \DateTimeImmutable $at, - ) { - } -} - -final class R11DateHandler extends TypedHandler -{ - public function handleDto(R11DateInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11HeaderInput -{ - public function __construct( - #[Header('Authorization')] public ?string $auth = null, - ) { - } -} - -final class R11HeaderHandler extends TypedHandler -{ - public function handleDto(R11HeaderInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -enum R11Color: string -{ - case Red = 'red'; -} - -final readonly class R11TrailingUnionInput -{ - /** @param list|string $a */ - public function __construct(#[Body] public array $a = []) - { - } -} - -final class R11TrailingUnionHandler extends TypedHandler -{ - public function handleDto(R11TrailingUnionInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11ArrayOfArraysInput -{ - /** @param array $a */ - public function __construct(#[Body] public array $a = []) - { - } -} - -final class R11ArrayOfArraysHandler extends TypedHandler -{ - public function handleDto(R11ArrayOfArraysInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11BracketUnionInput -{ - /** @param string[]|int $a */ - public function __construct(#[Body] public array $a = []) - { - } -} - -final class R11BracketUnionHandler extends TypedHandler -{ - public function handleDto(R11BracketUnionInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11ArrayOfListsInput -{ - /** @param array> $a */ - public function __construct(#[Body] public array $a = []) - { - } -} - -final class R11ArrayOfListsHandler extends TypedHandler -{ - public function handleDto(R11ArrayOfListsInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11UnionBracketsInput -{ - /** @param int|string[] $a */ - public function __construct(#[Body] public array $a = []) - { - } -} - -final class R11UnionBracketsHandler extends TypedHandler -{ - public function handleDto(R11UnionBracketsInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11GenericOfArrayInput -{ - /** @param Collection $a */ - public function __construct(#[Body] public array $a = []) - { - } -} - -final class R11GenericOfArrayHandler extends TypedHandler -{ - public function handleDto(R11GenericOfArrayInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11VarFallbackInput -{ - /** @param $a */ - public function __construct( - /** @var list */ - #[Body] public array $a = [], - ) { - } -} - -final class R11VarFallbackHandler extends TypedHandler -{ - public function handleDto(R11VarFallbackInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11BadCaster implements CasterInterface -{ - public function __construct(string $format, $loose = null) - { - throw new \InvalidArgumentException('Bad format'); - } - - public function cast(mixed $value): mixed - { - return $value; - } -} - -final class R11NoCtorCaster implements CasterInterface -{ - public function cast(mixed $value): mixed - { - return $value; - } -} - -final readonly class R11BadCasterInput -{ - public function __construct(#[Query] #[Cast(R11BadCaster::class, 'x')] public ?string $a = null) - { - } -} - -final class R11BadCasterHandler extends TypedHandler -{ - public function handleDto(R11BadCasterInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11NoCtorCasterInput -{ - public function __construct(#[Query] #[Cast(R11NoCtorCaster::class, 'x')] public ?string $a = null) - { - } -} - -final class R11NoCtorCasterHandler extends TypedHandler -{ - public function handleDto(R11NoCtorCasterInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11BudgetInner -{ - public function __construct(#[Body] public string $a, #[Body] public string $b, #[Body] public string $c) - { - } -} - -final readonly class R11BudgetObjectInput -{ - /** @param list $ids */ - public function __construct(#[Body] public array $ids, #[Body] public R11BudgetInner $inner) - { - } -} - -final class R11BudgetObjectHandler extends TypedHandler -{ - public function handleDto(R11BudgetObjectInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11NamedItem -{ - public function __construct(#[Body] #[Length(max: 3)] public string $name) - { - } -} - -final readonly class R11ConstraintBudgetInput -{ - /** @param list $items */ - public function __construct(#[Body] public array $items) - { - } -} - -final class R11ConstraintBudgetHandler extends TypedHandler -{ - public function handleDto(R11ConstraintBudgetInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R11BudgetTopInput -{ - /** @param list $ids */ - public function __construct(#[Body] public array $ids, #[Body] public int $x, #[Body] public int $y) - { - } -} - -final class R11BudgetTopHandler extends TypedHandler -{ - public function handleDto(R11BudgetTopInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} diff --git a/tests/Input/Round12Test.php b/tests/Input/Round12Test.php deleted file mode 100644 index c66711f6b..000000000 --- a/tests/Input/Round12Test.php +++ /dev/null @@ -1,656 +0,0 @@ - $name . $i . '=1', range(1, $count))); - } - - /** - * @return array>|null - */ - private function post(string $contentType, string $raw, TypedHandler $handler): ?array - { - $_SERVER['CONTENT_TYPE'] = $contentType; - $_SERVER['REQUEST_METHOD'] = 'POST'; - RequestInput::setRawBody($raw); - $processor = new ParamsProcessor($handler->params()); - - return $processor->isError() ? $processor->getErrors() : null; - } - - public function testAPostFormWithMoreFieldsThanMaxInputVarsIsRejected(): void - { - $limit = (int) ini_get('max_input_vars'); - // PHP keeps the first `limit` variables and drops the rest without a word - $_POST = array_fill_keys(array_map(static fn (int $i): string => 'f' . $i, range(1, $limit)), '1'); - - $errors = $this->post('application/x-www-form-urlencoded', self::pairs('f', $limit + 1), new R12FormHandler()); - - $this->assertSame(['body' => ['Too many form fields']], $errors); - } - - public function testAPostFormWithExactlyTheLimitIsAccepted(): void - { - $limit = (int) ini_get('max_input_vars'); - $_POST = array_fill_keys(array_map(static fn (int $i): string => 'f' . $i, range(1, $limit)), '1'); - - $this->assertNull($this->post('application/x-www-form-urlencoded', self::pairs('f', $limit), new R12FormHandler())); - } - - public function testAPostFormIsCountedWithItsNestedValues(): void - { - $limit = (int) ini_get('max_input_vars'); - $_POST = ['a' => array_fill(0, $limit, '1')]; - $raw = implode('&', array_map(static fn (int $i): string => 'a[]=' . $i, range(1, $limit + 1))); - - $this->assertSame(['body' => ['Too many form fields']], $this->post('application/x-www-form-urlencoded', $raw, new R12FormHandler())); - } - - public function testASmallPostFormIsNotParsedAgain(): void - { - $limit = (int) ini_get('max_input_vars'); - $_POST = ['a' => 'x']; - - // the body is not even looked at: PHP cannot have cut a form that fits - $this->assertNull($this->post('application/x-www-form-urlencoded', self::pairs('f', $limit + 1), new R12FormHandler())); - } - - public function testAMultipartPostIsLeftToPhp(): void - { - $limit = (int) ini_get('max_input_vars'); - $_POST = array_fill_keys(array_map(static fn (int $i): string => 'f' . $i, range(1, $limit)), '1'); - - // PHP does not give a multipart body back, so a form that was cut cannot be told from a complete one - $this->assertNull($this->post('multipart/form-data; boundary=x', self::pairs('f', $limit + 1), new R12MultipartHandler())); - } - - #[DataProvider('charsets')] - public function testJsonCharsets(string $contentType, ?string $rejected): void - { - $errors = $this->post($contentType, '{"a":"x"}', new R12FormHandler()); - - if ($rejected === null) { - $this->assertNull($errors, $contentType); - } else { - $this->assertSame(['body' => ['JSON must be UTF-8; the request says charset=' . $rejected]], $errors, $contentType); - } - } - - /** - * @return \Iterator - */ - public static function charsets(): \Iterator - { - yield 'utf-8' => ['application/json; charset=utf-8', null]; - yield 'utf8 spelling' => ['application/json; charset=utf8', null]; - yield 'UTF8 upper case' => ['application/json; charset=UTF8', null]; - yield 'us-ascii' => ['application/json; charset=US-ASCII', null]; - yield 'quoted' => ['application/json; charset="utf-8"', null]; - yield 'spaces around the equals sign' => ['application/json; charset = utf-8', null]; - yield 'trailing space' => ['application/json; charset="UTF-8" ', null]; - yield 'quoted value that only looks like a charset' => ['application/json; foo="a;charset=latin1"', null]; - yield 'the first charset wins' => ['application/json; charset=utf-8; charset=latin1', null]; - yield 'another parameter first' => ['application/json; foo=1; charset=latin1', 'latin1']; - yield 'latin1' => ['application/json; charset=ISO-8859-1', 'iso-8859-1']; - yield 'quoted latin1' => ['application/json;charset="latin1"', 'latin1']; - yield 'long value is cut' => ['application/json; charset=' . str_repeat('X', 100), str_repeat('x', 30)]; - yield 'value of exactly the shown length' => ['application/json; charset=' . str_repeat('y', 30), str_repeat('y', 30)]; - } - - /** - * @return \Iterator, string}> - */ - public static function descriptions(): \Iterator - { - yield 'var with a description' => [R12VarDescriptionHandler::class, 'string']; - yield 'var without a space before the end of the comment' => [R12VarTightHandler::class, 'int']; - yield 'non-empty-list with a description' => [R12VarNonEmptyHandler::class, 'string']; - yield 'phpstan var with a nested generic and a description' => [R12VarGenericHandler::class, 'int']; - } - - /** - * @param class-string $handler - */ - #[DataProvider('descriptions')] - public function testAVarTypeMayBeFollowedByADescription(string $handler, string $item): void - { - $this->assertSame($item, DtoCompiler::compile($handler)->fields[0]->listItem); - } - - /** - * @return \Iterator, string}> - */ - public static function invalid(): \Iterator - { - yield 'associative var with a description' => [R12VarAssocHandler::class, 'documents `array>`, an array that is not a list']; - yield 'array shape item' => [R12ShapeItemHandler::class, 'declare an item DTO']; - yield 'positive-int' => [R12PositiveIntHandler::class, 'PHPStan refinements such as positive-int']; - yield 'non-empty-string' => [R12NonEmptyStringHandler::class, 'documents list. PHPStan refinements']; - yield 'integer range' => [R12IntRangeHandler::class, 'documents list>. PHPStan refinements']; - yield 'generic item' => [R12GenericItemHandler::class, 'documents list>. PHPStan refinements']; - yield 'generic item with a list inside' => [R12ListInsideGenericHandler::class, 'documents list>. PHPStan refinements']; - yield 'dashed name that is no refinement' => [R12DashedItemHandler::class, 'documents list, and that type was not found']; - yield 'DateTime of Nette' => [R12NetteDateHandler::class, 'has type Nette\Utils\DateTime. Use DateTimeImmutable itself']; - yield 'DateTimeImmutable subclass' => [R12MyDateHandler::class, 'has type Tomaj\NetteApi\Test\Input\R12MyDate. Use DateTimeImmutable itself']; - yield 'empty path name' => [R12EmptyPathHandler::class, "for example #[Path('my_name')]"]; - yield 'empty query name' => [R12EmptyQueryHandler::class, "for example #[Query('my_name')]"]; - yield 'empty body name' => [R12EmptyBodyHandler::class, "for example #[Body('my_name')]"]; - yield 'empty header name' => [R12EmptyHeaderHandler::class, "for example #[Header('X-Request-Id')]"]; - yield 'name that starts with a digit' => [R12DigitNameHandler::class, 'must start with a letter or an underscore']; - } - - /** - * @param class-string $handler - */ - #[DataProvider('invalid')] - public function testCompileMessages(string $handler, string $needle): void - { - try { - DtoCompiler::compile($handler); - $this->fail('compiled'); - } catch (\LogicException $exception) { - $this->assertStringContainsString($needle, $exception->getMessage()); - } - } - - /** - * @return \Iterator - */ - public static function patterns(): \Iterator - { - yield 'unicode property with a quantifier' => ['/^\p{L}+$/u', null]; - yield 'braces after an escaped brace' => ['/\{3}+/', null]; - yield 'escaped backslash and A' => ['/\\\\A/', '\\\\A']; - yield 'escaped backslash and a letter that is only PCRE after one more backslash' => ['/a\\\\\\\\A/', 'a\\\\\\\\A']; - yield 'escaped plus then a quantifier' => ['/a\++/', 'a\++']; - yield 'lazy quantifier' => ['/[0-9]+?/', '[0-9]+?']; - yield 'lookbehind' => ['/(?<=a)b/', null]; - yield 'named group' => ['/(?a)/', null]; - yield 'hex code point' => ['/^\x{41}+$/u', null]; - yield 'hex byte' => ['/^\x41+$/', null]; - yield 'posix class' => ['/[[:alpha:]]/', null]; - yield 'comment' => ['/a(?#note)b/', null]; - yield 'branch reset' => ['/(?|a|b)/', null]; - yield 'escape character' => ['/a\e/', null]; - yield 'back reference g' => ['/(a)\g{1}/', null]; - yield 'escaped backslash then possessive' => ['/\\\\++/', null]; - yield 'three backslashes then A' => ['/\\\\\A/', null]; - yield 'possessive after a number of repetitions' => ['/a{2}+/', null]; - yield 'possessive after a range' => ['/[a-z]{2,}+/', null]; - yield 'relative recursion' => ['/(a)(?-1)/', null]; - yield 'numbered recursion' => ['/(a)(?1)/', null]; - yield 'named recursion' => ['/(?a)(?&n)/', null]; - yield 'single quoted group name' => ["/(?'n'a)/", null]; - yield 'non newline escape' => ['/a\N/', null]; - yield 'possessive question' => ['/a?+/', null]; - yield 'possessive star' => ['/a*+/', null]; - } - - #[DataProvider('patterns')] - public function testPatternOmissionFromOpenApi(string $pattern, ?string $expression): void - { - $this->assertSame($expression, new Pattern($pattern)->expression()); - } - - public function testTheNoteAboutAnExhaustedBudgetBelongsToTheFirstFieldWhenNothingReadsABody(): void - { - $_GET = ['ids' => array_fill(0, 150, 'x')]; - $metadata = DtoCompiler::compile(R12QueryBudgetHandler::class); - $mapper = new DtoMapper($metadata); - - $first = $mapper->errors($metadata->fields[0]); - $this->assertCount(101, $first); - $this->assertSame(['Only the first 100 errors are reported, the rest of the request was not checked'], $first['body']); - $this->assertSame([], $mapper->errors($metadata->fields[1])); - } - - public function testTheNoteBelongsToTheFirstBodyFieldEvenWhenAQueryFieldComesFirst(): void - { - $_SERVER['CONTENT_TYPE'] = 'application/json'; - $_SERVER['REQUEST_METHOD'] = 'POST'; - RequestInput::setRawBody('{"ids":' . json_encode(array_fill(0, 150, 'x')) . '}'); - $metadata = DtoCompiler::compile(R12MixedBudgetHandler::class); - $mapper = new DtoMapper($metadata); - - $this->assertSame([], $mapper->errors($metadata->fields[0])); - $this->assertArrayHasKey('body', $mapper->errors($metadata->fields[1])); - } - - public function testAnErrorOfTheBodyAndTheNoteShareTheKey(): void - { - $this->assertNull($this->post('application/json', '{"a":"x"}', new R12FormHandler())); - RequestInput::reset(); - $errors = $this->post('application/json', '{"ids":' . json_encode(array_fill(0, 101, 'x')) . '}', new R12BodyBudgetHandler()); - - $this->assertCount(101, $errors ?? []); - $this->assertSame(['Only the first 100 errors are reported, the rest of the request was not checked'], $errors['body'] ?? []); - } - - public function testRangePrintsMinusZeroAsZero(): void - { - $context = new ConstraintContext('x', self::class, [], []); - - $this->assertSame('Value must be at most 0', new Range(max: -0.0)->validate(1, $context)); - } -} - -final readonly class R12FormInput -{ - public function __construct(#[Body] public ?string $a = null) - { - } -} - -final class R12FormHandler extends TypedHandler -{ - public function handleDto(R12FormInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -#[Consumes(MediaTypes::MULTIPART)] -final class R12MultipartHandler extends TypedHandler -{ - public function handleDto(R12FormInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R12VarDescriptionInput -{ - public function __construct( - /** @var list Names of the things */ - #[Body] public array $names = [], - ) { - } -} - -final class R12VarDescriptionHandler extends TypedHandler -{ - public function handleDto(R12VarDescriptionInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R12VarTightInput -{ - public function __construct( - /** @var list*/ - #[Body] public array $ids = [], - ) { - } -} - -final class R12VarTightHandler extends TypedHandler -{ - public function handleDto(R12VarTightInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R12VarNonEmptyInput -{ - public function __construct( - /** @var non-empty-list Names of the things */ - #[Body] public array $names = ['a'], - ) { - } -} - -final class R12VarNonEmptyHandler extends TypedHandler -{ - public function handleDto(R12VarNonEmptyInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R12VarGenericInput -{ - public function __construct( - /** @phpstan-var list Numbers: any of them */ - #[Body] public array $numbers = [], - ) { - } -} - -final class R12VarGenericHandler extends TypedHandler -{ - public function handleDto(R12VarGenericInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R12VarAssocInput -{ - public function __construct( - /** @var array> Lists by name */ - #[Body] public array $lists = [], - ) { - } -} - -final class R12VarAssocHandler extends TypedHandler -{ - public function handleDto(R12VarAssocInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R12ShapeItemInput -{ - /** @param list $shapes */ - public function __construct(#[Body] public array $shapes = []) - { - } -} - -final class R12ShapeItemHandler extends TypedHandler -{ - public function handleDto(R12ShapeItemInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R12PositiveIntInput -{ - /** @param list $ids */ - public function __construct(#[Body] public array $ids = []) - { - } -} - -final class R12PositiveIntHandler extends TypedHandler -{ - public function handleDto(R12PositiveIntInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R12NonEmptyStringInput -{ - /** @param list $names */ - public function __construct(#[Body] public array $names = []) - { - } -} - -final class R12NonEmptyStringHandler extends TypedHandler -{ - public function handleDto(R12NonEmptyStringInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R12IntRangeInput -{ - /** @param list> $ids */ - public function __construct(#[Body] public array $ids = []) - { - } -} - -final class R12IntRangeHandler extends TypedHandler -{ - public function handleDto(R12IntRangeInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R12GenericItemInput -{ - /** @param list> $items */ - public function __construct(#[Body] public array $items = []) - { - } -} - -final class R12GenericItemHandler extends TypedHandler -{ - public function handleDto(R12GenericItemInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R12NetteDateInput -{ - public function __construct(#[Body] public ?DateTime $at = null) - { - } -} - -final class R12NetteDateHandler extends TypedHandler -{ - public function handleDto(R12NetteDateInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -class R12MyDate extends \DateTimeImmutable -{ -} - -final readonly class R12MyDateInput -{ - public function __construct(#[Body] public ?R12MyDate $at = null) - { - } -} - -final class R12MyDateHandler extends TypedHandler -{ - public function handleDto(R12MyDateInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R12EmptyPathInput -{ - public function __construct(#[Path('')] public int $id) - { - } -} - -final class R12EmptyPathHandler extends TypedHandler -{ - public function handleDto(R12EmptyPathInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R12EmptyQueryInput -{ - public function __construct(#[Query('')] public ?int $page = null) - { - } -} - -final class R12EmptyQueryHandler extends TypedHandler -{ - public function handleDto(R12EmptyQueryInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R12EmptyBodyInput -{ - public function __construct(#[Body('')] public ?int $page = null) - { - } -} - -final class R12EmptyBodyHandler extends TypedHandler -{ - public function handleDto(R12EmptyBodyInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R12EmptyHeaderInput -{ - public function __construct(#[Header('')] public ?string $id = null) - { - } -} - -final class R12EmptyHeaderHandler extends TypedHandler -{ - public function handleDto(R12EmptyHeaderInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R12DigitNameInput -{ - public function __construct(#[Query('0a')] public ?int $page = null) - { - } -} - -final class R12DigitNameHandler extends TypedHandler -{ - public function handleDto(R12DigitNameInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R12QueryBudgetInput -{ - /** @param list $ids */ - public function __construct(#[Query] public array $ids = [], #[Query] public int $page = 1) - { - } -} - -final class R12QueryBudgetHandler extends TypedHandler -{ - public function handleDto(R12QueryBudgetInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R12BodyBudgetInput -{ - /** @param list $ids */ - public function __construct(#[Body] public array $ids = []) - { - } -} - -final class R12BodyBudgetHandler extends TypedHandler -{ - public function handleDto(R12BodyBudgetInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R12ListInsideGenericInput -{ - /** @param list> $items */ - public function __construct(#[Body] public array $items = []) - { - } -} - -final class R12ListInsideGenericHandler extends TypedHandler -{ - public function handleDto(R12ListInsideGenericInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R12DashedItemInput -{ - /** @param list $items */ - public function __construct(#[Body] public array $items = []) - { - } -} - -final class R12DashedItemHandler extends TypedHandler -{ - public function handleDto(R12DashedItemInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R12MixedBudgetInput -{ - /** @param list $ids */ - public function __construct(#[Query] public int $page = 1, #[Body] public array $ids = []) - { - } -} - -final class R12MixedBudgetHandler extends TypedHandler -{ - public function handleDto(R12MixedBudgetInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} diff --git a/tests/Input/ScalarCoercerTest.php b/tests/Input/ScalarCoercerTest.php index 80ad79c66..8c899ce5b 100644 --- a/tests/Input/ScalarCoercerTest.php +++ b/tests/Input/ScalarCoercerTest.php @@ -9,6 +9,10 @@ use Tomaj\NetteApi\Input\ScalarCoercer; use Tomaj\NetteApi\Test\Input\Fixtures\Priority; use Tomaj\NetteApi\Test\Input\Fixtures\UserStatus; +use PHPUnit\Framework\Attributes\DataProvider; +use Tomaj\NetteApi\Input\DateFormat; +use Tomaj\NetteApi\Input\MediaTypes; +use Tomaj\NetteApi\Test\Input\Fixtures\Dependency\DependencyItemEnum; final class ScalarCoercerTest extends TestCase { @@ -132,4 +136,66 @@ public function testEnums(): void $this->assertSame('Value must be one of: 1, 2', $exception->getMessage()); } } + + /** + * @return iterable + */ + public static function malformedIntegers(): iterable + { + foreach (['++0', '--0', '+-0', '-+000', "1\n", ' 1', '1 ', '+', '-', ''] as $value) { + yield json_encode($value, JSON_THROW_ON_ERROR) => [$value]; + } + } + + #[DataProvider('malformedIntegers')] + public function testMalformedIntegersAreRejected(string $value): void + { + $this->expectException(ConversionFailed::class); + ScalarCoercer::toInt($value); + } + + public function testSingleSignedIntegersAndAnchoredPatterns(): void + { + $this->assertSame([5, -5, 0, 7], [ScalarCoercer::toInt('+5'), ScalarCoercer::toInt('-5'), ScalarCoercer::toInt('-0'), ScalarCoercer::toInt('007')]); + foreach (["1\n", "1.5\n"] as $value) { + try { + ScalarCoercer::toFloat($value); + $this->fail('float with a newline was accepted'); + } catch (ConversionFailed) { + $this->addToAssertionCount(1); + } + } + $this->expectException(ConversionFailed::class); + ScalarCoercer::toDateTime("2026-11-06T14:30:00Z\n"); + } + + public function testEnumBackingTypeComesFromItsCases(): void + { + $this->assertSame(DependencyItemEnum::First, ScalarCoercer::toEnum('1', DependencyItemEnum::class)); + $this->expectException(ConversionFailed::class); + ScalarCoercer::toEnum('x', EmptyStringEnum::class); + } + + public function testDateAndEnumMessages(): void + { + $date = new DateFormat('d.m.Y')->cast('24.12.2026'); + $this->assertSame('2026-12-24T00:00:00+00:00', $date->format('c')); + $parsed = ScalarCoercer::toDateTime('2026-12-24T00:00:00.1Z'); + $this->assertSame('100000', $parsed->format('u')); + $longer = ScalarCoercer::toDateTime('2026-12-24T00:00:00.1234567Z'); + $this->assertSame('123456', $longer->format('u')); + $this->assertSame('Value must be one of: 1, 2', ScalarCoercer::enumMessage(Priority::class)); + $this->assertSame('application/json', MediaTypes::normalize(' Application/JSON ; charset=utf-8')); + } + + public function testNegativeZeroOffsetIsUtc(): void + { + $date = ScalarCoercer::toDateTime('2026-05-01T10:00:00-00:00'); + $this->assertSame('2026-05-01T10:00:00+00:00', $date->format('c')); + $this->assertSame('2026-05-01T10:00:00.500000+00:00', ScalarCoercer::toDateTime('2026-05-01T10:00:00.5-00:00')->format('Y-m-d\TH:i:s.uP')); + } +} + +enum EmptyStringEnum: string +{ } diff --git a/tests/Input/TypeNameTest.php b/tests/Input/TypeNameTest.php index 3c6fecbbc..921ef5ef7 100644 --- a/tests/Input/TypeNameTest.php +++ b/tests/Input/TypeNameTest.php @@ -9,14 +9,27 @@ use Tomaj\NetteApi\Input\Body; use Tomaj\NetteApi\Input\File; use Tomaj\NetteApi\Input\Query; +use Tomaj\NetteApi\Input\DtoMetadataRegistry; +use Tomaj\NetteApi\Input\RequestInput; use Tomaj\NetteApi\Input\TypeName; use Tomaj\NetteApi\Test\Input\Fixtures\ImportScope; use Tomaj\NetteApi\Test\Input\Fixtures\SecondScope; use Tomaj\NetteApi\Validation\Email; use Tomaj\NetteApi\Validation\Range; +use Tomaj\NetteApi\Input\DtoCompiler; +use Tomaj\NetteApi\Params\ParamsProcessor; +use Tomaj\NetteApi\Test\Input\Fixtures\Inherited\LeafLevelsHandler; +use Tomaj\NetteApi\Test\Input\Fixtures\Priority; final class TypeNameTest extends TestCase { + protected function setUp(): void + { + RequestInput::reset(); + DtoMetadataRegistry::reset(); + $_GET = []; + } + public function testResolvesLikePhp(): void { $scope = new \ReflectionClass(ImportScope::class); @@ -121,5 +134,20 @@ public function testDollarBraceInterpolationKeepsTheDepth(): void $code = 'assertSame(['import' => 'Late\Import'], TypeName::importsOf($code, 'N')); } -} + public function testInheritedListDocblockResolvesInTheDeclaringClass(): void + { + $fields = DtoCompiler::compile(LeafLevelsHandler::class)->fields; + $this->assertSame(Priority::class, $fields[0]->listItem); + $this->assertSame(Priority::class, $fields[1]->listItem, 'the @return of an inherited cast() resolves in the parent caster'); + + $_GET = ['levels' => ['2', '1'], 'casted' => '1,2']; + $handler = new LeafLevelsHandler(); + $processor = new ParamsProcessor($handler->params()); + $this->assertFalse($processor->isError()); + $payload = $handler->handle($processor->getValues())->getPayload(); + $this->assertIsArray($payload); + $this->assertSame([Priority::High, Priority::Low], $payload['levels']); + $this->assertSame([Priority::Low, Priority::High], $payload['casted']); + } +} diff --git a/tests/Input/Utf8Test.php b/tests/Input/Utf8Test.php new file mode 100644 index 000000000..889dd3dd4 --- /dev/null +++ b/tests/Input/Utf8Test.php @@ -0,0 +1,265 @@ +clean(); + } + + protected function tearDown(): void + { + $this->clean(); + } + + /** + * @return \Iterator + */ + public static function invalidUtf8(): \Iterator + { + yield 'latin 1 letter' => ["\xE9"]; + yield 'lone continuation byte' => ["a\x80b"]; + yield 'truncated sequence' => ["abc\xE2\x82"]; + yield 'overlong slash' => ["\xC0\xAF"]; + yield 'surrogate' => ["\xED\xA0\x80"]; + yield 'beyond the last code point' => ["\xF4\x90\x80\x80"]; + } + + #[DataProvider('invalidUtf8')] + public function testInvalidUtf8InAQueryStringIsRejected(string $value): void + { + $_GET = ['q' => $value]; + + $this->assertSame(['q' => ['Value must be valid UTF-8']], $this->errors(new Utf8Handler())); + } + + public function testInvalidUtf8InAHeaderIsRejected(): void + { + $_SERVER['HTTP_X_T'] = "\xE9"; + + $this->assertSame(['X-T' => ['Value must be valid UTF-8']], $this->errors(new Utf8Handler())); + } + + public function testInvalidUtf8InAPathValueIsRejected(): void + { + PathValues::set(['id' => "\xE9"]); + + $this->assertSame(['id' => ['Value must be valid UTF-8']], $this->errors(new Utf8PathHandler())); + } + + public function testInvalidUtf8InAFormValueIsRejected(): void + { + $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_POST = ['name' => "\xE9"]; + RequestInput::setRawBody('name=%E9'); + + $this->assertSame(['name' => ['Value must be valid UTF-8']], $this->errors(new Utf8FormHandler())); + } + + public function testInvalidUtf8InAnItemOfAListIsRejectedWithItsPosition(): void + { + $_GET = ['tags' => ['ok', "\xE9"]]; + + $this->assertSame(['tags[1]' => ['Value must be valid UTF-8']], $this->errors(new Utf8ListHandler())); + } + + public function testInvalidUtf8IsReportedInsteadOfAMisleadingLengthOrPatternMessage(): void + { + $_GET = ['short' => "\xE9\xE9\xE9", 'u' => "\xE9"]; + + $this->assertSame([ + 'short' => ['Value must be valid UTF-8'], + 'u' => ['Value must be valid UTF-8'], + ], $this->errors(new Utf8LengthHandler())); + } + + public function testInvalidUtf8ForAStringBackedEnumIsAnUnknownCase(): void + { + $_GET = ['kind' => "\xE9"]; + + $this->assertSame(['kind' => ['Value must be one of: a, b']], $this->errors(new Utf8EnumHandler())); + } + + public function testValidUtf8IsAccepted(): void + { + $_GET = ['q' => 'žluťoučký kůň 😀', 'short' => '', 'u' => 'é']; + $_SERVER['HTTP_X_T'] = 'ž'; + PathValues::set(['id' => 'é']); + + $this->assertFalse(new ParamsProcessor(new Utf8Handler()->params())->isError()); + $this->assertFalse(new ParamsProcessor(new Utf8PathHandler()->params())->isError()); + $this->assertFalse(new ParamsProcessor(new Utf8LengthHandler()->params())->isError()); + } + + public function testAJsonStringWithSomethingThatLooksLikeInvalidUtf8EscapesIsFine(): void + { + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + RequestInput::setRawBody('{"name":"\u00e9"}'); + + $this->assertFalse(new ParamsProcessor(new Utf8FormHandler()->params())->isError()); + } + + public function testAHandlerWithParamsKeepsAcceptingAnyBytes(): void + { + $_GET = ['q' => "\xE9"]; + $handler = new class extends BaseHandler { + public function params(): array + { + return [new GetInputParam('q')]; + } + + public function handle(array $params): ResponseInterface + { + return new JsonApiResponse(200, []); + } + }; + + $this->assertFalse(new ParamsProcessor($handler->params())->isError()); + } + + private function clean(): void + { + RequestInput::reset(); + PathValues::reset(); + $_GET = []; + $_POST = []; + unset($_SERVER['HTTP_X_T'], $_SERVER['CONTENT_TYPE'], $_SERVER['REQUEST_METHOD']); + } + + /** + * @return array> + */ + private function errors(TypedHandler $handler): array + { + $processor = new ParamsProcessor($handler->params()); + $this->assertTrue($processor->isError()); + + return $processor->getErrors(); + } +} + +final readonly class Utf8Input +{ + public function __construct( + #[Query] public string $q = 'd', + #[Header('X-T')] public string $h = 'd', + ) { + } +} + +final class Utf8Handler extends TypedHandler +{ + public function handleDto(Utf8Input $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class Utf8PathInput +{ + public function __construct(#[Path] public string $id) + { + } +} + +final class Utf8PathHandler extends TypedHandler +{ + public function handleDto(Utf8PathInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class Utf8FormInput +{ + public function __construct(#[Body] public string $name) + { + } +} + +final class Utf8FormHandler extends TypedHandler +{ + public function handleDto(Utf8FormInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class Utf8ListInput +{ + /** + * @param list $tags + */ + public function __construct(#[Query] public array $tags = []) + { + } +} + +final class Utf8ListHandler extends TypedHandler +{ + public function handleDto(Utf8ListInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class Utf8LengthInput +{ + public function __construct( + #[Query] #[Length(max: 2)] public string $short = 'x', + #[Query] #[Pattern('/^.+$/u')] public string $u = 'a', + ) { + } +} + +final class Utf8LengthHandler extends TypedHandler +{ + public function handleDto(Utf8LengthInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +enum Utf8Kind: string +{ + case A = 'a'; + case B = 'b'; +} + +final readonly class Utf8EnumInput +{ + public function __construct(#[Query] public Utf8Kind $kind) + { + } +} + +final class Utf8EnumHandler extends TypedHandler +{ + public function handleDto(Utf8EnumInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} diff --git a/tests/Link/ApiLinkTest.php b/tests/Link/ApiLinkTest.php new file mode 100644 index 000000000..5247f427b --- /dev/null +++ b/tests/Link/ApiLinkTest.php @@ -0,0 +1,39 @@ +link(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), ['id' => 'a/b c', 'q' => 1]); + + $this->assertSame('https://example.com/api/v1/users/a%2Fb%20c/detail?q=1', $link); + } + + public function testATemplateWithoutAValueStaysLiteral(): void + { + $link = ApiFixtures::apiLink()->link(new EndpointIdentifier('GET', 1, 'users', '{id}/detail')); + + $this->assertSame('https://example.com/api/v1/users/{id}/detail', $link); + } + + public function testATemplatedPackageWithoutAnActionHasNoTrailingSlash(): void + { + $link = ApiFixtures::apiLink()->link(new EndpointIdentifier('GET', 1, 'users/{id}', null), ['id' => 5]); + + $this->assertSame('https://example.com/api/v1/users/5', $link); + } + + public function testLinkKeepsASlashInThePackage(): void + { + $link = ApiFixtures::apiLink()->link(new EndpointIdentifier('GET', 1, 'acme/widgets', 'show'), ['q' => 'a b']); + $this->assertSame('https://example.com/api/v1/acme/widgets/show?q=a+b', $link); + } +} diff --git a/tests/OpenApi/Fixtures/TypedProfileHandler.php b/tests/OpenApi/Fixtures/TypedProfileHandler.php new file mode 100644 index 000000000..e55c6bf76 --- /dev/null +++ b/tests/OpenApi/Fixtures/TypedProfileHandler.php @@ -0,0 +1,20 @@ + $input->id]); + } +} diff --git a/tests/OpenApi/Fixtures/TypedProfileInput.php b/tests/OpenApi/Fixtures/TypedProfileInput.php new file mode 100644 index 000000000..94379287e --- /dev/null +++ b/tests/OpenApi/Fixtures/TypedProfileInput.php @@ -0,0 +1,43 @@ + $fields + * @param list $tags + */ + public function __construct( + #[Path] + #[Range(min: 1)] + public int $id, + #[Header('X-Request-Id')] + public string $requestId, + #[Query] + public array $fields, + #[Body] + public string $name, + #[Body] + public ?UserStatus $status, + #[Body] + public array $tags, + #[Body] + public AddressInput $address, + #[File] + public ?FileUpload $avatar = null, + ) { + } +} diff --git a/tests/OpenApi/ParameterBuilderTest.php b/tests/OpenApi/ParameterBuilderTest.php index 9e87efb95..b5e9a9b15 100644 --- a/tests/OpenApi/ParameterBuilderTest.php +++ b/tests/OpenApi/ParameterBuilderTest.php @@ -5,6 +5,7 @@ namespace Tomaj\NetteApi\Test\OpenApi; use PHPUnit\Framework\TestCase; +use Tomaj\NetteApi\Input\RequestInput; use Tomaj\NetteApi\OpenApi\ParameterBuilder; use Tomaj\NetteApi\Params\CookieInputParam; use Tomaj\NetteApi\Params\FileInputParam; @@ -12,9 +13,22 @@ use Tomaj\NetteApi\Params\JsonInputParam; use Tomaj\NetteApi\Params\PostInputParam; use Tomaj\NetteApi\Test\OpenApi\Fixtures\ConfigurableHandler; +use Tomaj\NetteApi\Handlers\TypedHandler; +use Tomaj\NetteApi\Input\Cast; +use Tomaj\NetteApi\Input\Query; +use Tomaj\NetteApi\Input\Split; +use Tomaj\NetteApi\Params\ParamsProcessor; +use Tomaj\NetteApi\Response\JsonApiResponse; +use Tomaj\NetteApi\Response\ResponseInterface; final class ParameterBuilderTest extends TestCase { + protected function setUp(): void + { + RequestInput::reset(); + $_GET = []; + } + public function testOnlyQueryAndCookieParamsAreParameters(): void { $parameters = new ParameterBuilder()->build(new ConfigurableHandler([ @@ -77,4 +91,48 @@ public function testHandlerWithoutParams(): void { $this->assertSame([], new ParameterBuilder()->build(new ConfigurableHandler())); } + + public function testQueryListIsAdvertisedInTheFormPhpReads(): void + { + $parameters = new ParameterBuilder()->build(new QueryListHandler()); + $this->assertSame(['ids[]', 'csv'], array_column($parameters, 'name')); + $this->assertSame(['type' => 'array', 'items' => ['type' => 'integer']], $parameters[0]['schema']); + + $name = rawurlencode((string) $parameters[0]['name']); + $query = sprintf('%s=3&%s=4&csv=a,b', $name, $name); + parse_str($query, $_GET); + $this->assertSame(['ids' => [3, 4], 'csv' => ['a', 'b']], $this->payload(new QueryListHandler())); + } + + /** + * @return array + */ + private function payload(TypedHandler $handler): array + { + $processor = new ParamsProcessor($handler->params()); + $this->assertFalse($processor->isError(), (string) json_encode($processor->getErrors())); + + return $handler->handle($processor->getValues())->getPayload(); + } +} + +final readonly class QueryListInput +{ + /** + * @param list $ids + * @param list $csv + */ + public function __construct( + #[Query] public array $ids, + #[Query] #[Cast(Split::class, ',')] public array $csv, + ) { + } +} + +final class QueryListHandler extends TypedHandler +{ + public function handleDto(QueryListInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['ids' => $input->ids, 'csv' => $input->csv]); + } } diff --git a/tests/OpenApi/RequestBodyBuilderTest.php b/tests/OpenApi/RequestBodyBuilderTest.php index f80aebe9e..0df23e322 100644 --- a/tests/OpenApi/RequestBodyBuilderTest.php +++ b/tests/OpenApi/RequestBodyBuilderTest.php @@ -7,6 +7,7 @@ use PHPUnit\Framework\TestCase; use Tomaj\NetteApi\OpenApi\RequestBodyBuilder; use Tomaj\NetteApi\OpenApi\SchemaRegistry; +use Tomaj\NetteApi\Params\BodyInputParam; use Tomaj\NetteApi\Params\FileInputParam; use Tomaj\NetteApi\Params\GetInputParam; use Tomaj\NetteApi\Params\JsonInputParam; @@ -14,6 +15,7 @@ use Tomaj\NetteApi\Params\PutInputParam; use Tomaj\NetteApi\Params\RawInputParam; use Tomaj\NetteApi\Test\OpenApi\Fixtures\ConfigurableHandler; +use Tomaj\NetteApi\Test\Input\Fixtures\DescribedHandler; final class RequestBodyBuilderTest extends TestCase { @@ -143,4 +145,126 @@ public function testRawBodyKeepsDescriptionAndRequiredOfEarlierParam(): void $this->assertSame('Json', $body['description']); $this->assertTrue($body['required']); } + + public function testBodyParamWithoutSchemaIsDocumentedAsString(): void + { + $body = new RequestBodyBuilder()->build(new ConfigurableHandler([ + new BodyInputParam('name')->setRequired()->setDescription('Name'), + new BodyInputParam('tags')->setMulti(), + ]), new SchemaRegistry()); + + $this->assertIsArray($body); + $this->assertTrue($body['required']); + $this->assertSame(['application/json', 'application/x-www-form-urlencoded'], array_keys($body['content'])); + $this->assertSame([ + 'type' => 'object', + 'properties' => [ + 'name' => ['type' => 'string', 'description' => 'Name'], + 'tags' => ['type' => 'array', 'items' => ['type' => 'string']], + ], + 'required' => ['name'], + ], $body['content']['application/json']['schema']); + $this->assertSame([ + 'type' => 'object', + 'properties' => [ + 'name' => ['type' => 'string', 'description' => 'Name'], + 'tags[]' => ['type' => 'array', 'items' => ['type' => 'string']], + ], + 'required' => ['name'], + ], $body['content']['application/x-www-form-urlencoded']['schema']); + } + + public function testBodyWithOptionalFileFallsBackToJsonAndMultipart(): void + { + $file = ['type' => 'string', 'format' => 'binary']; + $body = new RequestBodyBuilder()->build(new ConfigurableHandler([ + new BodyInputParam('name')->setRequired(), + new FileInputParam('photo')->setOpenApiSchema($file), + ]), new SchemaRegistry()); + + $this->assertIsArray($body); + $this->assertSame(['application/json', 'multipart/form-data'], array_keys($body['content'])); + $this->assertArrayNotHasKey('photo', $body['content']['application/json']['schema']['properties']); + $this->assertSame($file, $body['content']['multipart/form-data']['schema']['properties']['photo']); + } + + public function testBodyParamsShareTheFormWithSchemalessFileParams(): void + { + $body = new RequestBodyBuilder()->build(new ConfigurableHandler([ + new FileInputParam('photo')->setRequired(), + new BodyInputParam('name')->setRequired(), + ]), new SchemaRegistry()); + + $this->assertIsArray($body); + $this->assertSame(['multipart/form-data', 'application/json'], array_keys($body['content'])); + $this->assertSame(['photo', 'name'], array_keys($body['content']['multipart/form-data']['schema']['properties'])); + $this->assertSame(['photo', 'name'], $body['content']['multipart/form-data']['schema']['required']); + } + + public function testFormSchemaNamesListsEncodesObjectsAndDropsNull(): void + { + $address = [ + 'type' => 'object', + 'properties' => ['street' => ['type' => 'string', 'nullable' => true]], + 'required' => ['street'], + ]; + $types = ['application/json', 'application/x-www-form-urlencoded', 'multipart/form-data']; + $body = new RequestBodyBuilder()->build(new ConfigurableHandler([ + new BodyInputParam('tags')->setRequired()->setOpenApiSchema(['type' => 'array', 'items' => ['type' => 'string']])->setContentTypes($types), + new BodyInputParam('address')->setOpenApiSchema($address)->setContentTypes($types), + new BodyInputParam('status')->setOpenApiSchema(['type' => 'string', 'enum' => ['a', null], 'nullable' => true])->setContentTypes($types), + ]), new SchemaRegistry()); + + $this->assertIsArray($body); + $this->assertSame($types, array_keys($body['content'])); + $this->assertSame(['tags', 'address', 'status'], array_keys($body['content']['application/json']['schema']['properties'])); + $this->assertTrue($body['content']['application/json']['schema']['properties']['status']['nullable']); + $this->assertArrayNotHasKey('encoding', $body['content']['application/json']); + foreach (['application/x-www-form-urlencoded', 'multipart/form-data'] as $form) { + $this->assertSame([ + 'schema' => [ + 'type' => 'object', + 'properties' => [ + 'tags[]' => ['type' => 'array', 'items' => ['type' => 'string']], + 'address' => ['type' => 'object', 'properties' => ['street' => ['type' => 'string']], 'required' => ['street']], + 'status' => ['type' => 'string', 'enum' => ['a']], + ], + 'required' => ['tags[]'], + ], + 'encoding' => ['address' => ['style' => 'deepObject', 'explode' => true]], + ], $body['content'][$form], $form); + } + } + + public function testListOfObjectsIsDocumentedOnlyAsJson(): void + { + $items = ['type' => 'array', 'items' => ['type' => 'object', 'properties' => ['sku' => ['type' => 'string']]]]; + $nested = ['type' => 'object', 'properties' => ['geo' => ['type' => 'object', 'properties' => []]]]; + $types = ['application/json', 'application/x-www-form-urlencoded']; + foreach ([$items, $nested] as $schema) { + $body = new RequestBodyBuilder()->build(new ConfigurableHandler([ + new BodyInputParam('value')->setOpenApiSchema($schema)->setContentTypes($types), + ]), new SchemaRegistry()); + $this->assertIsArray($body); + $this->assertSame(['application/json'], array_keys($body['content'])); + } + + // when only form media types are accepted, they are still documented (best effort) instead of an empty body + $body = new RequestBodyBuilder()->build(new ConfigurableHandler([ + new BodyInputParam('items')->setOpenApiSchema($items)->setContentTypes(['application/x-www-form-urlencoded']), + ]), new SchemaRegistry()); + $this->assertIsArray($body); + $this->assertSame(['application/x-www-form-urlencoded'], array_keys($body['content'])); + $this->assertArrayHasKey('items[]', $body['content']['application/x-www-form-urlencoded']['schema']['properties']); + } + + public function testOpenApiUsesTheDeclaredBodyMediaTypeAndDescription(): void + { + $builder = new RequestBodyBuilder(); + $body = $builder->build(new DescribedHandler(), new SchemaRegistry()); + $this->assertIsArray($body); + $this->assertSame(['application/json'], array_keys($body['content'])); + $this->assertSame('Customer email', $body['content']['application/json']['schema']['properties']['email']['description']); + $this->assertFalse($body['required']); + } } diff --git a/tests/OpenApi/ResponseBuilderTest.php b/tests/OpenApi/ResponseBuilderTest.php index 11d62f5e2..284220cd4 100644 --- a/tests/OpenApi/ResponseBuilderTest.php +++ b/tests/OpenApi/ResponseBuilderTest.php @@ -14,6 +14,10 @@ use Tomaj\NetteApi\Output\JsonOutput; use Tomaj\NetteApi\Output\RedirectOutput; use Tomaj\NetteApi\Test\OpenApi\Fixtures\ConfigurableHandler; +use Tomaj\NetteApi\Handlers\EchoHandler; +use Tomaj\NetteApi\Test\Input\Fixtures\ManyIdsHandler; +use Tomaj\NetteApi\Test\Input\Fixtures\FormHandler; +use Tomaj\NetteApi\Test\Input\Fixtures\SplitHandler; final class ResponseBuilderTest extends TestCase { @@ -148,4 +152,40 @@ public function testRedirectOutput(): void ], ], $responses[301]); } + + public function testOpenApiListsTheUnsupportedMediaTypeResponseOfATypedBody(): void + { + foreach ([false, true] as $problemDetails) { + $builder = new ResponseBuilder($problemDetails); + $withBody = $builder->build(new ManyIdsHandler(), new NoAuthorization(), true, new SchemaRegistry()); + $this->assertSame([400, 415, 500], array_keys($withBody)); + $this->assertSame('Unsupported media type', $withBody[415]['description']); + $this->assertArrayHasKey($problemDetails ? 'application/problem+json; charset=utf-8' : 'application/json; charset=utf-8', $withBody[415]['content']); + + $queryOnly = $builder->build(new SplitHandler(), new NoAuthorization(), true, new SchemaRegistry()); + $this->assertSame([400, 500], array_keys($queryOnly)); + } + + $classic = new ResponseBuilder()->build(new EchoHandler(), new NoAuthorization(), true, new SchemaRegistry()); + $this->assertArrayNotHasKey(415, $classic); + } + + public function testTheUnsupportedMediaTypeResponseDescribesItsDetail(): void + { + $legacy = new ResponseBuilder()->build(new FormHandler(), new NoAuthorization(), true, new SchemaRegistry()); + $schema = $legacy[415]['content']['application/json; charset=utf-8']['schema']; + $this->assertSame([ + 'type' => 'object', + 'properties' => [ + 'status' => ['type' => 'string', 'enum' => ['error']], + 'message' => ['type' => 'string'], + 'detail' => ['type' => 'string', 'description' => 'Which media types the endpoint reads. Sent only when error details are on.'], + ], + 'required' => ['status', 'message'], + ], $schema); + $this->assertSame('Unsupported media type', $legacy[415]['description']); + + $problem = new ResponseBuilder(true)->build(new FormHandler(), new NoAuthorization(), true, new SchemaRegistry()); + $this->assertSame(['$ref' => '#/components/schemas/ProblemDetails'], $problem[415]['content']['application/problem+json; charset=utf-8']['schema']); + } } diff --git a/tests/OpenApi/TypedInputOpenApiTest.php b/tests/OpenApi/TypedInputOpenApiTest.php index 6b14e28a4..e3759af90 100644 --- a/tests/OpenApi/TypedInputOpenApiTest.php +++ b/tests/OpenApi/TypedInputOpenApiTest.php @@ -4,6 +4,7 @@ namespace Tomaj\NetteApi\Test\OpenApi; +use JsonSchema\Validator; use PHPUnit\Framework\TestCase; use Tomaj\NetteApi\Api; use Tomaj\NetteApi\Authorization\NoAuthorization; @@ -12,13 +13,32 @@ use Tomaj\NetteApi\OpenApi\ParameterBuilder; use Tomaj\NetteApi\OpenApi\PathBuilder; use Tomaj\NetteApi\OpenApi\SchemaRegistry; +use Tomaj\NetteApi\OpenApi\SpecBuilder; use Tomaj\NetteApi\Params\BodyInputParam; use Tomaj\NetteApi\Params\GetInputParam; use Tomaj\NetteApi\Params\HeaderInputParam; use Tomaj\NetteApi\Params\PathInputParam; use Tomaj\NetteApi\Test\Input\Fixtures\CreateOrderHandler; +use Tomaj\NetteApi\Test\Input\Fixtures\DocumentHandler; use Tomaj\NetteApi\Test\Input\Fixtures\UserDetailHandler; +use Tomaj\NetteApi\Test\OpenApi\Fixtures\ApiFixtures; use Tomaj\NetteApi\Test\OpenApi\Fixtures\ConfigurableHandler; +use Tomaj\NetteApi\Test\OpenApi\Fixtures\TypedProfileHandler; +use Tomaj\NetteApi\Handlers\TypedHandler; +use Tomaj\NetteApi\Input\Body; +use Tomaj\NetteApi\Input\Cast; +use Tomaj\NetteApi\Input\CasterInterface; +use Tomaj\NetteApi\Input\DtoCompiler; +use Tomaj\NetteApi\Input\Query; +use Tomaj\NetteApi\Input\SchemaBuilder; +use Tomaj\NetteApi\Response\JsonApiResponse; +use Tomaj\NetteApi\Response\ResponseInterface; +use Tomaj\NetteApi\Test\Input\Fixtures\DateHintHandler; +use Tomaj\NetteApi\Test\Input\Fixtures\FloatRangeHandler; +use Tomaj\NetteApi\Test\Input\Fixtures\ListUsersHandler; +use Tomaj\NetteApi\Test\Input\Fixtures\NamedCaster; +use Tomaj\NetteApi\Test\Input\Fixtures\Priority; +use Tomaj\NetteApi\Test\Input\Fixtures\UserStatus; final class TypedInputOpenApiTest extends TestCase { @@ -36,7 +56,7 @@ public function testDtoOperationEqualsTheEquivalentParamsHandler(): void $this->assertMatchesSnapshot('typed-user-detail.json', $dto['parameters']); } - public function testNestedBodyListsJsonAndForm(): void + public function testNestedBodyWithListOfObjectsIsDocumentedOnlyAsJson(): void { $dto = $this->operation(new CreateOrderHandler()); $schema = $dto['requestBody']['content']['application/json']['schema']; @@ -51,10 +71,99 @@ public function testNestedBodyListsJsonAndForm(): void $this->assertSame(['customerEmail', 'address', 'items'], $schema['required']); $this->assertSame('email', $schema['properties']['customerEmail']['format']); $this->assertSame(1, $schema['properties']['items']['minItems']); - $this->assertArrayHasKey('application/x-www-form-urlencoded', $dto['requestBody']['content']); + // `items[0][sku]=...` has no serialization in OpenAPI 3.0, so the form is not documented + $this->assertSame(['application/json'], array_keys($dto['requestBody']['content'])); $this->assertMatchesSnapshot('typed-create-order.json', $dto['requestBody']); } + public function testFormBodyUsesTheWireShapePhpParses(): void + { + $dto = $this->operation(new TypedProfileHandler()); + $multipart = $dto['requestBody']['content']['multipart/form-data']; + + $this->assertSame(['application/json', 'multipart/form-data'], array_keys($dto['requestBody']['content'])); + $this->assertSame(['name', 'status', 'tags[]', 'address', 'avatar'], array_keys($multipart['schema']['properties'])); + $this->assertSame(['name', 'tags[]', 'address'], $multipart['schema']['required']); + $this->assertSame(['address' => ['style' => 'deepObject', 'explode' => true]], $multipart['encoding']); + $this->assertSame(['active', 'disabled'], $multipart['schema']['properties']['status']['enum']); + $this->assertArrayNotHasKey('nullable', $multipart['schema']['properties']['status']); + $this->assertMatchesSnapshot('typed-profile.json', ['parameters' => $dto['parameters'], 'requestBody' => $dto['requestBody']]); + } + + /** + * No OpenAPI 3.0 meta schema is available offline, so the document is checked for the rules the typed input relies on. + */ + public function testGeneratedDocumentWithTypedEndpointsIsWellFormed(): void + { + $apis = [ + new Api(new EndpointIdentifier('POST', '1', 'profile/{id}'), new TypedProfileHandler(), new NoAuthorization()), + new Api(new EndpointIdentifier('GET', '1', 'users/{id}/detail'), new UserDetailHandler(), new NoAuthorization()), + new Api(new EndpointIdentifier('POST', '1', 'orders'), new CreateOrderHandler(), new NoAuthorization()), + new Api(new EndpointIdentifier('POST', '1', 'documents'), new DocumentHandler(), new NoAuthorization()), + ]; + $spec = new SpecBuilder(new PathBuilder())->build($apis, '1', ApiFixtures::HOST_URL, ApiFixtures::apiLink()); + $json = json_encode($spec, JSON_THROW_ON_ERROR); + $document = json_decode($json, true, flags: JSON_THROW_ON_ERROR); + $this->assertIsArray($document); + $this->assertIsString($document['openapi']); + $this->assertStringStartsWith('3.0.', $document['openapi']); + + $forms = 0; + foreach ($document['paths'] as $path => $operations) { + foreach ($operations as $operation) { + foreach ($operation['parameters'] ?? [] as $parameter) { + $this->assertContains($parameter['in'], ['path', 'query', 'header', 'cookie']); + if ($parameter['in'] === 'path') { + $this->assertTrue($parameter['required']); + $this->assertStringContainsString('{' . $parameter['name'] . '}', (string) $path); + } + if ($parameter['in'] === 'query' && $parameter['schema']['type'] === 'array') { + $this->assertStringEndsWith('[]', $parameter['name']); + } + } + foreach ($operation['requestBody']['content'] ?? [] as $mediaType => $content) { + $schema = $content['schema']; + $this->assertSame('object', $schema['type']); + foreach ($schema['required'] ?? [] as $required) { + $this->assertArrayHasKey($required, $schema['properties']); + } + if ($mediaType === 'application/json') { + $this->assertArrayNotHasKey('encoding', $content); + continue; + } + $forms++; + $this->assertStringNotContainsString('"nullable"', json_encode($schema, JSON_THROW_ON_ERROR)); + foreach ($schema['properties'] as $name => $property) { + if ($property['type'] === 'array') { + $this->assertStringEndsWith('[]', $name); + $this->assertNotContains($property['items']['type'], ['array', 'object'], 'no form serialization of nested lists'); + } + if ($property['type'] === 'object') { + $this->assertSame(['style' => 'deepObject', 'explode' => true], $content['encoding'][$name]); + } + } + foreach (array_keys($content['encoding'] ?? []) as $encoded) { + $this->assertArrayHasKey($encoded, $schema['properties']); + } + } + } + } + $this->assertSame(2, $forms); + + // the JSON body schema is a JSON schema a validator accepts and applies (`nullable` is OpenAPI only, so null is not sent here) + $profilePaths = array_values(array_filter(array_keys($document['paths']), static fn (string $path): bool => str_ends_with($path, '/profile/{id}'))); + $this->assertCount(1, $profilePaths); + $schema = json_decode(json_encode($document['paths'][$profilePaths[0]]['post']['requestBody']['content']['application/json']['schema'], JSON_THROW_ON_ERROR)); + $valid = json_decode('{"name": "Ada", "status": "active", "tags": ["a"], "address": {"street": "Main", "postalCode": "81101"}}'); + $invalid = json_decode('{"name": "Ada", "tags": "a", "address": {"street": "", "postalCode": "811"}}'); + $validator = new Validator(); + $validator->validate($valid, $schema); + $this->assertTrue($validator->isValid(), json_encode($validator->getErrors(), JSON_THROW_ON_ERROR)); + $validator = new Validator(); + $validator->validate($invalid, $schema); + $this->assertCount(3, $validator->getErrors()); + } + public function testDirectPathAndHeaderParamsUseThoseLocations(): void { $parameters = new ParameterBuilder()->build(new ConfigurableHandler([ @@ -96,4 +205,124 @@ private function assertMatchesSnapshot(string $name, array $value): void $this->assertFileExists($file); $this->assertSame(file_get_contents($file), $actual); } + + public function testANullableEnumListsNullInTheBodyAndNothingNullableOnTheWire(): void + { + $params = DtoCompiler::compile(LevelHandler::class)->inputParams(); + + $this->assertSame(['type' => 'string', 'enum' => ['low', 'high', null], 'nullable' => true], $params[1]->getOpenApiSchema()); + $this->assertSame(['type' => 'string', 'enum' => ['low', 'high']], $params[2]->getOpenApiSchema()); + $this->assertSame([ + 'type' => 'object', + 'properties' => ['text' => ['type' => 'string'], 'author' => ['type' => 'string', 'nullable' => true]], + 'required' => ['text'], + 'nullable' => true, + ], $params[0]->getOpenApiSchema()); + } + + public function testDefaultsInTheSchema(): void + { + $fields = DtoCompiler::compile(SchemaDefaultsHandler::class)->fields; + $this->assertSame('active', SchemaBuilder::build($fields[0], true)['default']); + $this->assertSame('a,b', SchemaBuilder::build($fields[1], true)['default']); + $this->assertArrayNotHasKey('default', SchemaBuilder::build($fields[2], true)); + $this->assertSame(2, SchemaBuilder::build($fields[3], true)['default']); + } + + public function testSchemaObjectCopiesDescription(): void + { + $field = DtoCompiler::compile(ListUsersHandler::class)->fields[0]; + $schema = SchemaBuilder::object([$field]); + $this->assertSame('Page number', $schema['properties']['page']['description']); + $this->assertSame('integer', $schema['properties']['page']['type']); + $this->assertArrayNotHasKey('required', $schema); + $id = DtoCompiler::compile(UserDetailHandler::class)->fields[0]; + $required = SchemaBuilder::object([$id]); + $this->assertSame(['id'], $required['required']); + $this->assertSame('integer', $required['properties']['id']['type']); + } + + public function testSchemaTypes(): void + { + $float = SchemaBuilder::build(DtoCompiler::compile(FloatRangeHandler::class)->fields[0], true); + $this->assertSame('number', $float['type']); + $bool = SchemaBuilder::build(DtoCompiler::compile(BoolHandler::class)->fields[0], true); + $this->assertSame('boolean', $bool['type']); + $date = SchemaBuilder::build(DtoCompiler::compile(DateHintHandler::class)->fields[0], true); + $this->assertSame('string', $date['type']); + $this->assertArrayNotHasKey('format', $date); + } +} + +final readonly class LevelNote +{ + public function __construct(#[Body] public string $text, #[Body] public ?string $author = null) + { + } +} + +enum Level: string +{ + case Low = 'low'; + case High = 'high'; +} + +final readonly class LevelInput +{ + public function __construct( + #[Body] public ?LevelNote $note = null, + #[Body] public ?Level $level = null, + #[Query] public ?Level $filter = null, + ) { + } +} + +final class LevelHandler extends TypedHandler +{ + public function handleDto(LevelInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class StatusCaster implements CasterInterface +{ + public function cast(mixed $value): UserStatus + { + return UserStatus::from(is_string($value) ? $value : 'active'); + } +} + +final readonly class SchemaDefaultsInput +{ + public function __construct( + #[Query] public UserStatus $status = UserStatus::Active, + #[Query] #[Cast(NamedCaster::class)] public string $text = 'a,b', + #[Query] #[Cast(StatusCaster::class)] public UserStatus $casted = UserStatus::Active, + #[Query] public Priority $priority = Priority::High, + ) { + } +} + +final class SchemaDefaultsHandler extends TypedHandler +{ + public function handleDto(SchemaDefaultsInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class BoolPinInput +{ + public function __construct(#[Query] public bool $flag = false) + { + } +} + +final class BoolHandler extends TypedHandler +{ + public function handleDto(BoolPinInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } } diff --git a/tests/OpenApi/snapshots/typed-create-order.json b/tests/OpenApi/snapshots/typed-create-order.json index 75e3b9b17..807cb1226 100644 --- a/tests/OpenApi/snapshots/typed-create-order.json +++ b/tests/OpenApi/snapshots/typed-create-order.json @@ -60,66 +60,6 @@ "items" ] } - }, - "application/x-www-form-urlencoded": { - "schema": { - "type": "object", - "properties": { - "customerEmail": { - "type": "string", - "format": "email" - }, - "address": { - "type": "object", - "properties": { - "street": { - "type": "string", - "minLength": 1, - "maxLength": 120 - }, - "postalCode": { - "type": "string", - "pattern": "^[0-9]{5}$" - } - }, - "required": [ - "street", - "postalCode" - ] - }, - "items": { - "type": "array", - "items": { - "type": "object", - "properties": { - "sku": { - "type": "string" - }, - "quantity": { - "type": "integer", - "minimum": 1 - } - }, - "required": [ - "sku", - "quantity" - ] - }, - "minItems": 1, - "maxItems": 50 - }, - "deliveryAt": { - "type": "string", - "format": "date-time", - "nullable": true - } - }, - "required": [ - "customerEmail", - "address", - "items" - ] - } } } } diff --git a/tests/OpenApi/snapshots/typed-profile.json b/tests/OpenApi/snapshots/typed-profile.json new file mode 100644 index 000000000..5d1bc9285 --- /dev/null +++ b/tests/OpenApi/snapshots/typed-profile.json @@ -0,0 +1,141 @@ +{ + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + } + }, + { + "name": "X-Request-Id", + "in": "header", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "fields[]", + "in": "query", + "required": true, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "status": { + "type": "string", + "enum": [ + "active", + "disabled", + null + ], + "nullable": true + }, + "tags": { + "type": "array", + "items": { + "type": "string" + } + }, + "address": { + "type": "object", + "properties": { + "street": { + "type": "string", + "minLength": 1, + "maxLength": 120 + }, + "postalCode": { + "type": "string", + "pattern": "^[0-9]{5}$" + } + }, + "required": [ + "street", + "postalCode" + ] + } + }, + "required": [ + "name", + "tags", + "address" + ] + } + }, + "multipart/form-data": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "status": { + "type": "string", + "enum": [ + "active", + "disabled" + ] + }, + "tags[]": { + "type": "array", + "items": { + "type": "string" + } + }, + "address": { + "type": "object", + "properties": { + "street": { + "type": "string", + "minLength": 1, + "maxLength": 120 + }, + "postalCode": { + "type": "string", + "pattern": "^[0-9]{5}$" + } + }, + "required": [ + "street", + "postalCode" + ] + }, + "avatar": { + "type": "string", + "format": "binary" + } + }, + "required": [ + "name", + "tags[]", + "address" + ] + }, + "encoding": { + "address": { + "style": "deepObject", + "explode": true + } + } + } + } + } +} diff --git a/tests/Params/PathHeaderBodyParamTest.php b/tests/Params/PathHeaderBodyParamTest.php index 722b22046..d05c69ffd 100644 --- a/tests/Params/PathHeaderBodyParamTest.php +++ b/tests/Params/PathHeaderBodyParamTest.php @@ -11,6 +11,7 @@ use Tomaj\NetteApi\Params\PathInputParam; use Tomaj\NetteApi\Params\PathValues; use Tomaj\NetteApi\Validation\InputType; +use Tomaj\NetteApi\Params\HeaderBag; final class PathHeaderBodyParamTest extends TestCase { @@ -19,7 +20,7 @@ protected function setUp(): void $_GET = []; $_POST = []; $_FILES = []; - unset($_SERVER['CONTENT_TYPE'], $_SERVER['HTTP_X_REQUEST_ID'], $_SERVER['CONTENT_LENGTH']); + unset($_SERVER['CONTENT_TYPE'], $_SERVER['HTTP_CONTENT_TYPE'], $_SERVER['HTTP_X_REQUEST_ID'], $_SERVER['CONTENT_LENGTH'], $_SERVER['REQUEST_METHOD']); PathValues::reset(); RequestInput::reset(); } @@ -72,6 +73,19 @@ public function testBodyReadsPostAndJson(): void $this->assertSame('none', new BodyInputParam('name')->setDefault('none')->getValue()); } + public function testBodyReadsAPutFormAndTheContentTypeHeaderLikeTypedHandlers(): void + { + $_SERVER['REQUEST_METHOD'] = 'PUT'; + $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; + RequestInput::setRawBody('name=Linus'); + $this->assertSame('Linus', new BodyInputParam('name')->getValue()); + + unset($_SERVER['CONTENT_TYPE']); + $_SERVER['HTTP_CONTENT_TYPE'] = 'application/json'; + RequestInput::setRawBody('{"name":"Ken"}'); + $this->assertSame('Ken', new BodyInputParam('name')->getValue()); + } + public function testSchemaAndContentTypesRoundTrip(): void { $param = new BodyInputParam('name') @@ -82,4 +96,47 @@ public function testSchemaAndContentTypesRoundTrip(): void $this->assertNull(new BodyInputParam('other')->getOpenApiSchema()); $this->assertSame([], new BodyInputParam('other')->getContentTypes()); } + + public function testAuthorizationFromAnApacheRewriteIsRead(): void + { + $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] = 'Bearer abc'; + $this->assertSame('Bearer abc', HeaderBag::get('Authorization')); + + $_SERVER['HTTP_AUTHORIZATION'] = 'Bearer direct'; + $this->assertSame('Bearer direct', HeaderBag::get('authorization')); + + unset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'], $_SERVER['HTTP_AUTHORIZATION']); + $this->assertFalse(HeaderBag::has('Authorization')); + } + + public function testHeadersIgnoreServerInternals(): void + { + $_SERVER['HTTP_X_REQUEST_ID'] = 'abc'; + $_SERVER['HTTP_X_TRACE'] = 'xyz'; + $_SERVER['SCRIPT_NAME'] = '/index.php'; + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $this->assertSame('abc', HeaderBag::get('x-request-id')); + $this->assertSame('xyz', HeaderBag::get('X-Trace')); + $this->assertFalse(HeaderBag::has('t-name')); + $this->assertSame('application/json', HeaderBag::get('Content-Type')); + } + + public function testBodyParamReadsJsonObjectsOnly(): void + { + RequestInput::setRawBody('{"note":"hi","1":"n"}'); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $param = new BodyInputParam('note'); + $this->assertSame('hi', $param->getValue()); + $numeric = new BodyInputParam('1'); + $this->assertSame('n', $numeric->getValue()); + + RequestInput::reset(); + RequestInput::setRawBody('[1, 2]'); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $this->assertNull(new BodyInputParam('note')->getValue()); + + RequestInput::reset(); + RequestInput::setRawBody(''); + $this->assertNull(new BodyInputParam('note')->getValue()); + } } diff --git a/tests/Presenters/ApiPresenterUnsupportedMediaTypeTest.php b/tests/Presenters/ApiPresenterUnsupportedMediaTypeTest.php index 1ba42cb01..79f105af3 100644 --- a/tests/Presenters/ApiPresenterUnsupportedMediaTypeTest.php +++ b/tests/Presenters/ApiPresenterUnsupportedMediaTypeTest.php @@ -171,4 +171,21 @@ public function getByType(string $type, bool $throw = true): ?object return $presenter; } + + public function testPresenterDropsAStaleBody(): void + { + RequestInput::setRawBody('{"customerEmail":"ada@example.com","address":{"street":"Main","postalCode":"81101"},"items":[{"sku":"A","quantity":1}]}'); + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + $decider = new ApiDecider(new Container()); + $decider->addApi(new EndpointIdentifier('POST', 1, 'orders'), new CreateOrderHandler(), new NoAuthorization()); + $presenter = new ApiPresenter(); + $presenter->apiDecider = $decider; + $presenter->response = new HttpResponse(); + $presenter->context = new Container(); + $presenter->outputConfigurator = new DebuggerConfigurator(); + $presenter->errorHandler = new DefaultErrorHandler($presenter->outputConfigurator); + $result = $presenter->run(new Request('Api:Api:default', 'POST', ['version' => '1', 'package' => 'orders'])); + $this->assertSame(400, $result->getCode()); + } } diff --git a/tests/TypedEndpointMatchTest.php b/tests/TypedEndpointMatchTest.php index ff387e8a2..fe5aa5b22 100644 --- a/tests/TypedEndpointMatchTest.php +++ b/tests/TypedEndpointMatchTest.php @@ -120,4 +120,41 @@ private static function resolve(ApiDecider $decider, string $method, string $ver return $api->getHandler() instanceof DefaultHandler ? ($decider->matchPath($method, $version, $package, $apiAction, $path) ?? $api) : $api; } + + public function testPathCaptureDoesNotLeakIntoTheNextEndpoint(): void + { + $decider = new ApiDecider(new Container()); + $decider->enableGlobalPreflight(); + $decider->addApi(new EndpointIdentifier('GET', 1, 'users', 'list'), new AlwaysOkHandler(), new NoAuthorization()); + $decider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), new UserDetailHandler(), new NoAuthorization()); + $decider->addApi(new EndpointIdentifier('GET', 2, 'users', '{id}/detail'), new UserDetailHandler(), new NoAuthorization()); + + $matched = self::resolve($decider, 'GET', '1', 'users', '42', '/api/v1/users/42/detail'); + $id = null; + foreach ($matched->getHandler()->params() as $param) { + if ($param->getKey() === 'id') { + $id = $param->getValue(); + } + } + $this->assertSame(42, $id); + + $static = self::resolve($decider, 'GET', '1', 'users', 'list', '/api/v1/users/list'); + $this->assertInstanceOf(AlwaysOkHandler::class, $static->getHandler()); + foreach (new UserDetailHandler()->params() as $param) { + if ($param->getKey() === 'id') { + $this->assertNull($param->getValue()); + } + } + + $post = self::resolve($decider, 'POST', '1', 'users', '42', '/api/v1/users/42/detail'); + $this->assertInstanceOf(DefaultHandler::class, $post->getHandler()); + $withPreflight = self::resolve($decider, 'GET', '1', 'users', '7', '/api/v1/users/7/detail'); + $this->assertInstanceOf(UserDetailHandler::class, $withPreflight->getHandler()); + $otherVersion = self::resolve($decider, 'GET', '1', 'users', '7', '/api/v2/users/7/detail'); + $this->assertInstanceOf(DefaultHandler::class, $otherVersion->getHandler()); + + $decider->addApi(new EndpointIdentifier('GET', 1, 'users', 'detail'), new UserDetailHandler(), new NoAuthorization()); + $this->expectException(\LogicException::class); + $decider->getApi('GET', '1', 'users', 'detail'); + } } diff --git a/tests/Input/Round13Test.php b/tests/Validation/PatternTest.php similarity index 53% rename from tests/Input/Round13Test.php rename to tests/Validation/PatternTest.php index 26575093a..ebca714ff 100644 --- a/tests/Input/Round13Test.php +++ b/tests/Validation/PatternTest.php @@ -2,17 +2,12 @@ declare(strict_types=1); -namespace Tomaj\NetteApi\Test\Input; +namespace Tomaj\NetteApi\Test\Validation; -use Tomaj\NetteApi\Handlers\BaseHandler; -use Tomaj\NetteApi\Params\GetInputParam; -use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; use Tomaj\NetteApi\Handlers\TypedHandler; -use Tomaj\NetteApi\Input\Body; use Tomaj\NetteApi\Input\DtoCompiler; -use Tomaj\NetteApi\Input\Header; -use Tomaj\NetteApi\Input\Path; use Tomaj\NetteApi\Input\Query; use Tomaj\NetteApi\Input\RequestInput; use Tomaj\NetteApi\Input\SchemaBuilder; @@ -23,7 +18,7 @@ use Tomaj\NetteApi\Validation\Length; use Tomaj\NetteApi\Validation\Pattern; -final class Round13Test extends TestCase +final class PatternTest extends TestCase { protected function setUp(): void { @@ -35,30 +30,88 @@ protected function tearDown(): void $this->clean(); } - private function clean(): void + public function testPatternsAreExportedOnlyWhenPortable(): void { - RequestInput::reset(); - PathValues::reset(); - $_GET = []; - $_POST = []; - unset($_SERVER['HTTP_X_T'], $_SERVER['CONTENT_TYPE'], $_SERVER['REQUEST_METHOD']); + $this->assertSame('^[a-z]+$', new Pattern('{^[a-z]+$}')->expression()); + $this->assertSame('^[a-z]+$', new Pattern('(^[a-z]+$)')->expression()); + $this->assertSame('^[a-z]+$', new Pattern('[^[a-z]+$]')->expression()); + $this->assertSame('^[a-z]+$', new Pattern('<^[a-z]+$>')->expression()); + $this->assertSame('^[a-z]+$', new Pattern('#^[a-z]+$#uD')->expression()); + $this->assertNull(new Pattern('{^[a-z]+$}i')->expression()); + $this->assertNull(new Pattern('/^[a-z]+$/i')->expression()); + $this->assertNull(new Pattern('/^[a-z]+$/x')->expression()); } /** - * @return array> + * @return \Iterator */ - private function errors(TypedHandler $handler): array + public static function ecmaCompatiblePatterns(): \Iterator { - $processor = new ParamsProcessor($handler->params()); - $this->assertTrue($processor->isError()); + yield 'plain' => ['/^[a-z]+$/', '^[a-z]+$']; + yield 'escaped plus' => ['/^a\+\+$/', '^a\+\+$']; + yield 'lookahead and a group' => ['/^(?=a)(?:a|b)+x$/u', '^(?=a)(?:a|b)+x$']; + yield 'lookahead and named group' => ['/^(?=a)(?a|b)+x$/u', null]; + yield 'start anchor' => ['/\Aab\z/', null]; + yield 'end anchor Z' => ['/ab\Z/', null]; + yield 'possessive' => ['/^a++$/', null]; + yield 'possessive braces' => ['/^a{2}+$/', null]; + yield 'possessive question' => ['/^a?+$/', null]; + yield 'atomic group' => ['/^(?>a+)b$/', null]; + yield 'python group' => ['/(?Pa)/', null]; + yield 'inline flag' => ['/(?i)a/', null]; + yield 'scoped flag' => ['/(?i:a)b/', null]; + yield 'horizontal space' => ['/a\hb/', null]; + } - return $processor->getErrors(); + #[DataProvider('ecmaCompatiblePatterns')] + public function testOnlyEcmaCompatiblePatternsReachOpenApi(string $pattern, ?string $expected): void + { + $this->assertSame($expected, new Pattern($pattern)->expression()); + } + + /** + * @return \Iterator + */ + public static function pcreOnlyConstructs(): \Iterator + { + yield 'unicode property with a quantifier' => ['/^\p{L}+$/u', null]; + yield 'braces after an escaped brace' => ['/\{3}+/', null]; + yield 'escaped backslash and A' => ['/\\\\A/', '\\\\A']; + yield 'escaped backslash and a letter that is only PCRE after one more backslash' => ['/a\\\\\\\\A/', 'a\\\\\\\\A']; + yield 'escaped plus then a quantifier' => ['/a\++/', 'a\++']; + yield 'lazy quantifier' => ['/[0-9]+?/', '[0-9]+?']; + yield 'lookbehind' => ['/(?<=a)b/', null]; + yield 'named group' => ['/(?a)/', null]; + yield 'hex code point' => ['/^\x{41}+$/u', null]; + yield 'hex byte' => ['/^\x41+$/', null]; + yield 'posix class' => ['/[[:alpha:]]/', null]; + yield 'comment' => ['/a(?#note)b/', null]; + yield 'branch reset' => ['/(?|a|b)/', null]; + yield 'escape character' => ['/a\e/', null]; + yield 'back reference g' => ['/(a)\g{1}/', null]; + yield 'escaped backslash then possessive' => ['/\\\\++/', null]; + yield 'three backslashes then A' => ['/\\\\\A/', null]; + yield 'possessive after a number of repetitions' => ['/a{2}+/', null]; + yield 'possessive after a range' => ['/[a-z]{2,}+/', null]; + yield 'relative recursion' => ['/(a)(?-1)/', null]; + yield 'numbered recursion' => ['/(a)(?1)/', null]; + yield 'named recursion' => ['/(?a)(?&n)/', null]; + yield 'single quoted group name' => ["/(?'n'a)/", null]; + yield 'non newline escape' => ['/a\N/', null]; + yield 'possessive question' => ['/a?+/', null]; + yield 'possessive star' => ['/a*+/', null]; + } + + #[DataProvider('pcreOnlyConstructs')] + public function testPatternOmissionFromOpenApi(string $pattern, ?string $expression): void + { + $this->assertSame($expression, new Pattern($pattern)->expression()); } /** * @return \Iterator */ - public static function patterns(): \Iterator + public static function portability(): \Iterator { yield 'zip code' => ['/^[0-9]{5}$/', true]; yield 'with the flags u and D' => ['/^[a-z]+$/uD', true]; @@ -131,7 +184,7 @@ public static function patterns(): \Iterator yield 'start of subject anchor' => ['/\Aa\z/', false]; } - #[DataProvider('patterns')] + #[DataProvider('portability')] public function testOnlyAPatternThatMeansTheSameInEcma262IsExported(string $pattern, bool $portable): void { $expression = null; @@ -148,7 +201,7 @@ public function testOnlyAPatternThatMeansTheSameInEcma262IsExported(string $patt public function testAPortablePatternIsDocumentedAsPatternAndTheOthersAsXPattern(): void { - $fields = DtoCompiler::compile(R13PatternHandler::class)->fields; + $fields = DtoCompiler::compile(PatternHandler::class)->fields; $this->assertSame(['type' => 'string', 'pattern' => '^[0-9]{5}$'], SchemaBuilder::build($fields[0], true)); $this->assertSame(['type' => 'string', 'x-pattern' => '/^\p{Lu}[a-z]+$/u'], SchemaBuilder::build($fields[1], true)); @@ -160,118 +213,31 @@ public function testThePatternIsStillCheckedWhateverIsExported(): void { $_GET = ['name' => 'ada']; - $this->assertSame(['name' => ['Value must match the pattern /^\p{Lu}[a-z]+$/u']], $this->errors(new R13NameHandler())); - } - - /** - * @return \Iterator - */ - public static function invalidUtf8(): \Iterator - { - yield 'latin 1 letter' => ["\xE9"]; - yield 'lone continuation byte' => ["a\x80b"]; - yield 'truncated sequence' => ["abc\xE2\x82"]; - yield 'overlong slash' => ["\xC0\xAF"]; - yield 'surrogate' => ["\xED\xA0\x80"]; - yield 'beyond the last code point' => ["\xF4\x90\x80\x80"]; - } - - #[DataProvider('invalidUtf8')] - public function testInvalidUtf8InAQueryStringIsRejected(string $value): void - { - $_GET = ['q' => $value]; - - $this->assertSame(['q' => ['Value must be valid UTF-8']], $this->errors(new R13Handler())); - } - - public function testInvalidUtf8InAHeaderIsRejected(): void - { - $_SERVER['HTTP_X_T'] = "\xE9"; - - $this->assertSame(['X-T' => ['Value must be valid UTF-8']], $this->errors(new R13Handler())); - } - - public function testInvalidUtf8InAPathValueIsRejected(): void - { - PathValues::set(['id' => "\xE9"]); - - $this->assertSame(['id' => ['Value must be valid UTF-8']], $this->errors(new R13PathHandler())); + $this->assertSame(['name' => ['Value must match the pattern /^\p{Lu}[a-z]+$/u']], $this->errors(new NameHandler())); } - public function testInvalidUtf8InAFormValueIsRejected(): void - { - $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; - $_SERVER['REQUEST_METHOD'] = 'POST'; - $_POST = ['name' => "\xE9"]; - RequestInput::setRawBody('name=%E9'); - - $this->assertSame(['name' => ['Value must be valid UTF-8']], $this->errors(new R13FormHandler())); - } - - public function testInvalidUtf8InAnItemOfAListIsRejectedWithItsPosition(): void - { - $_GET = ['tags' => ['ok', "\xE9"]]; - - $this->assertSame(['tags[1]' => ['Value must be valid UTF-8']], $this->errors(new R13ListHandler())); - } - - public function testInvalidUtf8IsReportedInsteadOfAMisleadingLengthOrPatternMessage(): void - { - $_GET = ['short' => "\xE9\xE9\xE9", 'u' => "\xE9"]; - - $this->assertSame([ - 'short' => ['Value must be valid UTF-8'], - 'u' => ['Value must be valid UTF-8'], - ], $this->errors(new R13LengthHandler())); - } - - public function testInvalidUtf8ForAStringBackedEnumIsAnUnknownCase(): void - { - $_GET = ['kind' => "\xE9"]; - - $this->assertSame(['kind' => ['Value must be one of: a, b']], $this->errors(new R13EnumHandler())); - } - - public function testValidUtf8IsAccepted(): void - { - $_GET = ['q' => 'žluťoučký kůň 😀', 'short' => '', 'u' => 'é']; - $_SERVER['HTTP_X_T'] = 'ž'; - PathValues::set(['id' => 'é']); - - $this->assertFalse(new ParamsProcessor(new R13Handler()->params())->isError()); - $this->assertFalse(new ParamsProcessor(new R13PathHandler()->params())->isError()); - $this->assertFalse(new ParamsProcessor(new R13LengthHandler()->params())->isError()); - } - - public function testAJsonStringWithSomethingThatLooksLikeInvalidUtf8EscapesIsFine(): void + private function clean(): void { - $_SERVER['CONTENT_TYPE'] = 'application/json'; - $_SERVER['REQUEST_METHOD'] = 'POST'; - RequestInput::setRawBody('{"name":"\u00e9"}'); - - $this->assertFalse(new ParamsProcessor(new R13FormHandler()->params())->isError()); + RequestInput::reset(); + PathValues::reset(); + $_GET = []; + $_POST = []; + unset($_SERVER['HTTP_X_T'], $_SERVER['CONTENT_TYPE'], $_SERVER['REQUEST_METHOD']); } - public function testAHandlerWithParamsKeepsAcceptingAnyBytes(): void + /** + * @return array> + */ + private function errors(TypedHandler $handler): array { - $_GET = ['q' => "\xE9"]; - $handler = new class extends BaseHandler { - public function params(): array - { - return [new GetInputParam('q')]; - } - - public function handle(array $params): ResponseInterface - { - return new JsonApiResponse(200, []); - } - }; + $processor = new ParamsProcessor($handler->params()); + $this->assertTrue($processor->isError()); - $this->assertFalse(new ParamsProcessor($handler->params())->isError()); + return $processor->getErrors(); } } -final readonly class R13PatternInput +final readonly class PatternInput { public function __construct( #[Query] #[Pattern('/^[0-9]{5}$/')] public string $zip, @@ -282,127 +248,24 @@ public function __construct( } } -final class R13PatternHandler extends TypedHandler +final class PatternHandler extends TypedHandler { - public function handleDto(R13PatternInput $input): ResponseInterface + public function handleDto(PatternInput $input): ResponseInterface { return new JsonApiResponse(200, []); } } -final readonly class R13NameInput +final readonly class NameInput { public function __construct(#[Query] #[Pattern('/^\p{Lu}[a-z]+$/u')] public string $name) { } } -final class R13NameHandler extends TypedHandler -{ - public function handleDto(R13NameInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R13Input -{ - public function __construct( - #[Query] public string $q = 'd', - #[Header('X-T')] public string $h = 'd', - ) { - } -} - -final class R13Handler extends TypedHandler -{ - public function handleDto(R13Input $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R13PathInput -{ - public function __construct(#[Path] public string $id) - { - } -} - -final class R13PathHandler extends TypedHandler -{ - public function handleDto(R13PathInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R13FormInput -{ - public function __construct(#[Body] public string $name) - { - } -} - -final class R13FormHandler extends TypedHandler -{ - public function handleDto(R13FormInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R13ListInput -{ - /** - * @param list $tags - */ - public function __construct(#[Query] public array $tags = []) - { - } -} - -final class R13ListHandler extends TypedHandler -{ - public function handleDto(R13ListInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -final readonly class R13LengthInput -{ - public function __construct( - #[Query] #[Length(max: 2)] public string $short = 'x', - #[Query] #[Pattern('/^.+$/u')] public string $u = 'a', - ) { - } -} - -final class R13LengthHandler extends TypedHandler -{ - public function handleDto(R13LengthInput $input): ResponseInterface - { - return new JsonApiResponse(200, []); - } -} - -enum R13Kind: string -{ - case A = 'a'; - case B = 'b'; -} - -final readonly class R13EnumInput -{ - public function __construct(#[Query] public R13Kind $kind) - { - } -} - -final class R13EnumHandler extends TypedHandler +final class NameHandler extends TypedHandler { - public function handleDto(R13EnumInput $input): ResponseInterface + public function handleDto(NameInput $input): ResponseInterface { return new JsonApiResponse(200, []); } From a68a462bd9a05962a0f8a041b0318ae9cd07ac33 Mon Sep 17 00:00:00 2001 From: Tomas Majer Date: Sun, 15 Nov 2026 10:36:55 +0100 Subject: [PATCH 3/5] Second review pass for typed input DTOs - 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 Claude-Session: https://claude.ai/code/session_012jrra6bHr2Jmk7hfEjoKsr --- CHANGELOG.md | 3 +- UPGRADE-4.0.md | 5 +-- docs/api/reference.md | 1 - docs/examples/typed-input.md | 2 +- docs/guide/api-decider.md | 2 +- docs/guide/console.md | 2 +- docs/guide/input-styles.md | 6 +-- docs/guide/links.md | 2 +- docs/guide/params.md | 4 +- docs/guide/presenter.md | 4 +- docs/guide/typed-input-body.md | 10 ++--- docs/guide/typed-input-conversion.md | 4 +- docs/guide/typed-input.md | 32 +++++++------- docs/index.md | 2 +- docs/sk/api/reference.md | 3 +- docs/sk/examples/typed-input.md | 4 +- docs/sk/faq.md | 4 +- docs/sk/guide/api-decider.md | 2 +- docs/sk/guide/attributes.md | 2 +- docs/sk/guide/console.md | 2 +- docs/sk/guide/errors.md | 2 +- docs/sk/guide/getting-started.md | 4 +- docs/sk/guide/handlers.md | 2 +- docs/sk/guide/input-styles.md | 12 +++--- docs/sk/guide/layers.md | 2 +- docs/sk/guide/links.md | 2 +- docs/sk/guide/outputs.md | 4 +- docs/sk/guide/params.md | 4 +- docs/sk/guide/presenter.md | 4 +- docs/sk/guide/problem-details.md | 4 +- docs/sk/guide/typed-input-body.md | 26 ++++++------ docs/sk/guide/typed-input-conversion.md | 10 ++--- docs/sk/guide/typed-input.md | 42 +++++++++---------- docs/sk/index.md | 4 +- src/ApiDecider.php | 14 +++++-- src/Input/DtoMapper.php | 2 +- src/Input/RequestInput.php | 14 +------ src/Link/ApiLink.php | 10 +++-- src/Misc/ConsoleRequest.php | 9 ++-- src/Params/MappedInputParam.php | 15 ++++++- src/Presenters/ApiPresenter.php | 24 ++++++++++- tests/Input/RequestInputTest.php | 28 +++---------- tests/Link/ApiLinkTest.php | 20 +++++++++ tests/Misc/ConsoleRequestTest.php | 10 +++++ .../ApiPresenterUnsupportedMediaTypeTest.php | 38 +++++++++++++++++ tests/TypedEndpointMatchTest.php | 40 ++++++++++++++++++ 46 files changed, 285 insertions(+), 157 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ce7e93e7..24fbcb8c5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,7 @@ Planned for 4.0, developed on `master`. 3.x is maintained on the `3.x` branch. * `TextApiResponse` throws `InvalidArgumentException` for arrays and non-`Stringable` objects instead of outputting `Array` with a warning (arrays) or failing with an `Error` (objects); non-string values in validation messages, IP headers, console fields and OpenAPI examples are converted to strings instead of raising warnings or `TypeError`. * `Error\ErrorHandlerInterface` methods return `ResponseInterface` instead of `JsonApiResponse`, and the interface has two new methods, `handleNotFound(EndpointInterface)` and `handleRateLimit(RateLimitResponse)`. Own implementations must add them (#196). * `Error\ErrorHandlerInterface` has a new method `handleUnsupportedMediaType(string $detail)` for the `415` of typed handlers. Own implementations must add it (#197). +* `Params\ParamType` has new cases `Path`, `Header` and `Body`, so an exhaustive `match` without a `default` arm fails on them; `InputParam` has new public methods `setOpenApiSchema()`, `getOpenApiSchema()`, `setContentTypes()` and `getContentTypes()`, which a subclass with the same method names must match (#197). * `ApiPresenter` builds the `404` for an unknown endpoint and the `429` for a reached rate limit (without an own error response) through the error handler. `DefaultErrorHandler` sends the same bodies as before, except that a `429` without a known retry time says only `Too many requests.` instead of `Retry after seconds.` (#196). * `Handlers\DefaultHandler` is `final`. `ApiPresenter` does not call its `handle()`, so a subclass could no longer change the `404`; do it in `ErrorHandlerInterface::handleNotFound()` (#196). * Request logs are masked by default (#187): `ApiPresenter` replaces secret header values (`Authorization`, `Proxy-Authorization`, `Cookie`, `Set-Cookie`, `X-Api-Key`, names containing `token`, `secret` or `key`, `X-Auth-*`), secret query parameters in the logged URI (`api_key`, `token`, `access_token`, `password`, `signature`, `code`, ...) and the names used by the API key authentications with `***` before `ApiLoggerInterface::log()`. The DI extension's `logging: maskHeaders` defaults to `true`. Opt out with `setMaskedLogHeaders([])` / `setMaskedLogQueryParams([])` or `maskHeaders: false` / `maskQueryParams: false`. See `UPGRADE-4.0.md`. @@ -64,7 +65,7 @@ Planned for 4.0, developed on `master`. 3.x is maintained on the `3.x` branch. * Endpoint actions can have `{name}` segments, for example `#[Get(1, 'users', '{id}/detail')]`. `ApiDecider::getApi()` keeps its signature; the new `ApiDecider::matchPath()` finds the endpoint of a URL template. `ApiLink::link()` fills `{name}` from the parameter of the same name. * Strict conversion of scalars, backed enums, `DateTimeImmutable` (RFC 3339) and `list`; `#[Cast]` with `CasterInterface` (`DateFormat`, `UnixTimestamp` and `Split` built in); constraints `Range`, `Length`, `Pattern`, `Email` and own `ConstraintInterface`. * Nested DTOs and lists for JSON, form and multipart bodies, with errors reported as `items[1].quantity` in the existing envelope and in Problem Details. - * `#[Consumes]` limits the body media types; any other one is a `415` through the new `ErrorHandlerInterface::handleUnsupportedMediaType()`, which own error handlers must add. + * `#[Consumes]` limits the body media types; any other one is a `415`. * For typed handlers, strings must be valid UTF-8, a JSON body that names another charset is a `400`, and so are a multipart body sent with `PUT` or `PATCH` and a form with more fields than `max_input_vars`. ### Changed diff --git a/UPGRADE-4.0.md b/UPGRADE-4.0.md index f441e9454..3f9f2d635 100644 --- a/UPGRADE-4.0.md +++ b/UPGRADE-4.0.md @@ -74,15 +74,14 @@ new BearerTokenAuthorization(new StaticBearerTokenRepository(['token' => '*']), new BearerTokenAuthorization(new StaticTokenRepository(['token' => '*']), $ipDetector); ``` -## Typed input: new param classes, enum cases and InputParam methods +## Typed input: enum cases and InputParam methods `TypedHandler` is an additional way to declare input; handlers on `params()` keep their conversion, validation and OpenAPI output. What can affect existing code: -* New param classes `PathInputParam`, `HeaderInputParam` and `BodyInputParam`; existing parameter classes are unchanged. * `ParamType` has new cases `Path`, `Header` and `Body`. An exhaustive `match` on `ParamType` without a `default` arm throws `UnhandledMatchError` for them. * `InputParam` has new public methods `setOpenApiSchema()`, `getOpenApiSchema()`, `setContentTypes()` and `getContentTypes()`. A subclass with a method of the same name must match their signatures. -`ApiDecider::getApi()` and `ApiLink::link()` keep their signatures; endpoints with `{name}` segments are found by the new `ApiDecider::matchPath()`, which `ApiPresenter` calls when `getApi()` returns no static endpoint. An own presenter that should serve URL templates calls `matchPath()` the same way. +`ApiDecider::getApi()` and `ApiLink::link()` keep their signatures; endpoints with `{name}` segments are found by the new `ApiDecider::matchPath()`, which `ApiPresenter` calls when `getApi()` returns no static endpoint, and first when the URL has segments after the action. An own presenter that should serve URL templates calls `matchPath()` the same way. ## Stricter types diff --git a/docs/api/reference.md b/docs/api/reference.md index 979f147ee..c1c7200b3 100644 --- a/docs/api/reference.md +++ b/docs/api/reference.md @@ -52,7 +52,6 @@ All classes live under `Tomaj\NetteApi`. | `Validation\Range`, `Length`, `Pattern`, `Email` | built-in constraints | [Constraints](/guide/typed-input-conversion#constraints) | | `Validation\ConstraintInterface`, `ConstraintContext` | your own constraints | [Custom constraints](/guide/typed-input-conversion#custom-constraints) | | `Params\MappedInputParam` | the `InputParam` generated for one DTO property | [Typed input](/guide/typed-input) | -| `Input\RequestInput`, `Params\PathValues` | request state of a typed handler, reset in long-running workers | [Long-running workers](/guide/typed-input#long-running-workers) | The other classes of the `Input` namespace are the machinery behind these (compiler, mapper, metadata, schema and conversion helpers). They are not listed and are not meant to be extended or called directly. diff --git a/docs/examples/typed-input.md b/docs/examples/typed-input.md index af6cc0c81..cb8934377 100644 --- a/docs/examples/typed-input.md +++ b/docs/examples/typed-input.md @@ -25,7 +25,7 @@ Typed handlers, path and header parameters and `#[Consumes]` are new in 4.0.0. | `POST /api/v1/orders` `text/csv` | `415` | content type outside the default pair | | `POST /api/v1/orders` postal code `81101` plus a newline | `400` | `$` in the pattern ends the string | | `POST /api/v1/avatar` multipart | `201` | `FileUpload` | -| `GET /api/v1/openapi` | `200` | path parameter and both body content types | +| `GET /api/v1/openapi` | `200` | path and header parameters, a multipart body | ## A query DTO diff --git a/docs/guide/api-decider.md b/docs/guide/api-decider.md index 626d98ef2..7961d9234 100644 --- a/docs/guide/api-decider.md +++ b/docs/guide/api-decider.md @@ -59,7 +59,7 @@ The 4th argument is the rate limit, `null` means none. Left out, an autowired `R ### Endpoints with {name} segments -An endpoint whose action has `{name}` segments, such as `users/{id}/detail`, needs the path of the request. `ApiPresenter` calls `getApi()` first, and when that finds nothing it calls `matchPath($method, $version, $package, $apiAction, $path)`. A static endpoint therefore always wins. `matchPath()` compares the path with every template of the method and version, stores the matched values for the `#[Path]` properties and returns the `Api`, or `null` when no template matches. When two templates match one path it throws a `LogicException` that lists them, so make a static segment differ. A global preflight also answers `OPTIONS` for a path that matches a template. How to register and route one is in [Typed input](/guide/typed-input#path-values-and-url-templates). +An endpoint whose action has `{name}` segments, such as `users/{id}/detail`, needs the path of the request. `ApiPresenter` calls `getApi()` first, and when that finds nothing it calls `matchPath($method, $version, $package, $apiAction, $path)`, so a static endpoint wins for the same URL. When the URL has segments after the action, `ApiPresenter` tries `matchPath()` first: a template that matches the whole path, such as `users/{id}/detail` for `/users/7/detail`, wins over a shorter static endpoint `users/7`. `matchPath()` compares the path with every template of the method and version, stores the matched values for the `#[Path]` properties and returns the `Api`, or `null` when no template matches. When two templates match one path it throws a `LogicException` that lists them; with the DI extension such templates already fail the container compilation. Make a static segment differ. A global preflight also answers `OPTIONS` for a path that matches a template. How to register and route one is in [Typed input](/guide/typed-input#path-values-and-url-templates). `GET /api/v1/users` and `POST /api/v1/users` are two endpoints with two handlers. A version that is not registered, such as `/api/v3/users`, is a `404`, as the [versions example](/examples/versions) tests. diff --git a/docs/guide/console.md b/docs/guide/console.md index ff1032fb4..cbd873f35 100644 --- a/docs/guide/console.md +++ b/docs/guide/console.md @@ -42,7 +42,7 @@ The console builds the request from the params of the handler, whether they come | body field | the first media type the handler reads that the console can build: JSON, a URL-encoded form or multipart | | file | a multipart upload; with a file attached the body fields go in the same multipart request | -In a JSON body each value keeps its declared type; a nested object, or an object item of a list, takes JSON text. Blank optional fields are not sent; a blank path value shows an error instead of sending. +In a JSON body each value keeps its declared type; a nested object, or an object item of a list, takes JSON text. Blank optional fields are not sent; a blank path value, `.` or `..` shows an error instead of sending. ## FAQ diff --git a/docs/guide/input-styles.md b/docs/guide/input-styles.md index 1eb579f84..e6d0547f3 100644 --- a/docs/guide/input-styles.md +++ b/docs/guide/input-styles.md @@ -102,7 +102,7 @@ final class UserDetailHandler extends BaseHandler public function params(): array { return [ - (new PathInputParam('id', InputType::INTEGER))->setRequired(), + new PathInputParam('id', InputType::INTEGER), // always required new HeaderInputParam('X-Request-Id', InputType::STRING), ]; } @@ -230,7 +230,7 @@ final readonly class CreateOrderInput public function __construct( #[Body] #[Email] public string $customerEmail, #[Body] public AddressInput $address, - #[Body] #[Length(min: 1)] public array $items, + #[Body] #[Length(min: 1, max: 50)] public array $items, ) { } } @@ -304,7 +304,7 @@ final class LoginHandler extends TypedHandler } ``` -The form still sends `email=ada%40example.com&password=...&remember=1`. The DTO mapper rejects unknown boolean strings rather than treating every non-empty string as `true`. +The form still sends `email=ada%40example.com&password=...&remember=1`. The DTO mapper rejects unknown boolean strings rather than treating every non-empty string as `true`. `#[Email]` and `#[Length]` are extra checks that the `params()` version does not make. ### 5. File upload diff --git a/docs/guide/links.md b/docs/guide/links.md index ee57227d6..5e6efb79b 100644 --- a/docs/guide/links.md +++ b/docs/guide/links.md @@ -15,7 +15,7 @@ $url = $apiLink->link(new EndpointIdentifier('GET', 1, 'users', 'detail'), ['id' It needs a route to `Api:Api:default` with `version`, `package` and `apiAction` parameters, as in [Getting started](/guide/getting-started). -For an endpoint whose URL has `{name}` segments, such as `{id}/detail`, `link()` fills each segment from the parameter of the same name (URL-encoded); the other parameters go to the query string. A segment without a value stays literal, which is the OpenAPI path template: +For an endpoint whose URL has `{name}` segments, such as `{id}/detail`, `link()` fills each segment from the parameter of the same name (URL-encoded); the other parameters go to the query string. A segment without a value stays literal, which is the OpenAPI path template. A path value `''`, `'.'` or `'..'` throws `Nette\Application\UI\InvalidLinkException`, because such a segment would never match or would be resolved to another URL: ```php $url = $apiLink->link(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), ['id' => 42, 'limit' => 5]); diff --git a/docs/guide/params.md b/docs/guide/params.md index 63a3f3ab3..bf746cb1c 100644 --- a/docs/guide/params.md +++ b/docs/guide/params.md @@ -63,13 +63,13 @@ In 3.x `?limit=abc` with `INTEGER` is not an error: the value is converted to `n ## Path, header and body params -`PathInputParam` reads a value from the endpoint URL. Declare the placeholder in the endpoint action with `{name}`, for example `users/{id}/detail`, as described in [Typed input](/guide/typed-input#path-values-and-url-templates). The param is always required and its OpenAPI placeholder has the same name. `HeaderInputParam` reads a request header, case-insensitively. `BodyInputParam` reads one field of a JSON object, a URL-encoded form or a multipart body, and `setContentTypes()` lists the media types it accepts. In a typed DTO, `#[Path]`, `#[Header]` and `#[Body]` properties become `MappedInputParam` objects with the type `TYPE_PATH`, `TYPE_HEADER` or `TYPE_BODY`; `params()` declares these classes directly: +`PathInputParam` reads a value from the endpoint URL. Declare the placeholder in the endpoint action with `{name}`, for example `users/{id}/detail`, as described in [Typed input](/guide/typed-input#path-values-and-url-templates). The param is always required and its OpenAPI placeholder has the same name. `HeaderInputParam` reads a request header, case-insensitively. `BodyInputParam` reads one field of a JSON object, a URL-encoded form or a multipart body, and `setContentTypes()` sets the media types documented in OpenAPI and used by the console; they are not enforced, so a `params()` handler never answers `415`. In a typed DTO, `#[Path]`, `#[Header]` and `#[Body]` properties become `MappedInputParam` objects with the type `TYPE_PATH`, `TYPE_HEADER` or `TYPE_BODY`; `params()` declares these classes directly: ```php public function params(): array { return [ - (new PathInputParam('id', InputType::INTEGER))->setRequired(), + new PathInputParam('id', InputType::INTEGER), // always required new HeaderInputParam('X-Request-Id', InputType::STRING), (new BodyInputParam('email', InputType::STRING)) ->setRequired() diff --git a/docs/guide/presenter.md b/docs/guide/presenter.md index e24a978be..1b51894f9 100644 --- a/docs/guide/presenter.md +++ b/docs/guide/presenter.md @@ -12,7 +12,7 @@ description: 'The exact order of steps in Nette API ApiPresenter::run(), from CO | Step | Code | Exit | | --- | --- | --- | | 1. CORS headers | `sendCorsHeaders()` | | -| 2. Endpoint | `$this->apiDecider->getApi(...)`, then `matchPath(...)` for `{name}` URLs | `404` through `DefaultHandler` and `handleNotFound()` | +| 2. Endpoint | `$this->apiDecider->getApi(...)`, then `matchPath(...)` for `{name}` URLs (first when the URL has segments after the action) | `404` through `DefaultHandler` and `handleNotFound()` | | 3. Rate limit | `checkRateLimit($rateLimit)` | `429`, not logged | | 4. Read params | `new ParamsProcessor($handler->params())` | | | 5. Authorization | `checkAuth($authorization, $params)` | `401` or `500`, not logged | @@ -48,7 +48,7 @@ $paramsProcessor = new ParamsProcessor($handler->params()); $params = $paramsProcessor->isError() ? [] : $paramsProcessor->getValues(); ``` -Every param is read and validated. With an error, `$params` is empty and the error waits for step 6. +Every param is read and validated. With an error, `$params` is empty and the error waits for step 6. An exception thrown while reading, for example by the constructor of a nested DTO or by a caster, also waits: after the authorization the error handler answers it with `500`. ## 5. Authorization diff --git a/docs/guide/typed-input-body.md b/docs/guide/typed-input-body.md index deca5bdb9..132e3fe04 100644 --- a/docs/guide/typed-input-body.md +++ b/docs/guide/typed-input-body.md @@ -73,7 +73,7 @@ JSON request body: } ``` -The DTO mapper creates `AddressInput` and both `ItemInput` objects recursively. An array of DTOs needs PHPDoc such as `list`, and a scalar array `list`, `list`, `list` or `list` (`non-empty-list`, `T[]`, `@phpstan-param` and `@psalm-param` work too); associative arrays, unions, `mixed`, `object` and untyped arrays fail when the container is compiled. +The DTO mapper creates `AddressInput` and both `ItemInput` objects recursively. An array of DTOs needs PHPDoc such as `list`, and a scalar array `list`, `list`, `list` or `list` (`T[]`, `@phpstan-param` and `@psalm-param` work too; `non-empty-list` is read as `list`, so add `#[Length(min: 1)]` to require items); associative arrays, unions, `mixed`, `object` and untyped arrays fail when the container is compiled. The same DTO works with URL-encoded form fields, and with multipart fields when it has a `#[File]` property or `#[Consumes('multipart/form-data')]`. Nested fields use PHP bracket notation, such as `address[street]` and `items[0][sku]`; `deliveryAt` keeps the same RFC 3339 string. Body parsing depends on the content type, not on a JSON schema. @@ -156,9 +156,9 @@ final class ImportHandler extends TypedHandler } ``` -An upload-only endpoint uses `#[Consumes('multipart/form-data')]`. Restricting to a form type without `multipart/form-data` means that the endpoint cannot receive files; declaring an impossible combination, such as a required `#[File]` with JSON-only consumption, is a container-compilation error. +An upload-only endpoint uses `#[Consumes('multipart/form-data')]`. A DTO with a `#[File]` property, required or optional, must list `multipart/form-data` in `#[Consumes]`; otherwise the container compilation fails. -A request with another content type is rejected before mapping with **415 Unsupported Media Type**. The 415 is sent after the authorization and the rate limits, so a client without access gets `401` instead, and it is logged by `ApiLoggerInterface` like a handled request. With error details enabled, the message states both the received type and the exact accepted types, for example: +A request with another content type is rejected before mapping with **415 Unsupported Media Type**. The 415 is sent after the authorization and the rate limits, so a client without access gets `401` instead. With error details enabled, the message states both the received type and the exact accepted types, for example: ```json { @@ -179,7 +179,7 @@ With Problem Details enabled, the 415 uses that format, and its `detail` always | Native scalar types | numbers and booleans remain JSON numbers/booleans | values arrive as strings and go through the same strict scalar conversion | | Null | explicit `null` is allowed only for a nullable property | there is no null literal: omit the field to use null or its default | | Empty string | an actual string, not null | an actual string, not null | -| Object vs list | `{}` is an object, including when its properties are missing. `[]` is a list and is rejected wherever an object is required, including an empty list. A JSON object is rejected where a list is required | bracket names build an object (`address[street]`); indexed names build a list (`items[0]`) | +| Object vs list | `{}` is an object (its missing properties are reported one by one). `[]` is a list and is rejected wherever an object is required, including an empty list. A JSON object is rejected where a list is required | bracket names build an object (`address[street]`); indexed names build a list (`items[0]`) | | Files | not supported | `multipart/form-data` only | For example, JSON `"quantity": 2` stays an integer, while form `quantity=2` becomes an integer only after the complete string passes strict conversion. Neither accepts `2pcs`. JSON `false` and form `remember=0` are valid booleans; an arbitrary non-empty form string is not silently `true`. @@ -209,5 +209,5 @@ final readonly class AvatarInput } ``` -`FileUpload` exposes the original name, the client content type, the temporary path, the size and the upload error. `?FileUpload` is an optional upload and `list` accepts several files in one field. The handler checks the upload error, the size and the real type before storing the file; nothing is moved automatically. `#[File]` is allowed only on the root input DTO of the handler, not inside a nested DTO or a list. +`FileUpload` has the properties `originalName`, `clientContentType`, `temporaryPath`, `size` and `error` (a PHP `UPLOAD_ERR_*` code). `?FileUpload` is an optional upload and `list` accepts several files in one field. The handler checks the upload error, the size and the real type before storing the file; nothing is moved automatically. `#[File]` is allowed only on the root input DTO of the handler, not inside a nested DTO or a list. diff --git a/docs/guide/typed-input-conversion.md b/docs/guide/typed-input-conversion.md index 9ac35d9b3..7e65c7da8 100644 --- a/docs/guide/typed-input-conversion.md +++ b/docs/guide/typed-input-conversion.md @@ -74,7 +74,7 @@ final class CastException extends RuntimeException } ``` -Casters are in `Tomaj\NetteApi\Input`, including `DateFormat`, `UnixTimestamp` and `Split`. The caster runs **instead of** the built-in conversion for that property. It runs first, returns the property's declared value, and only then do `Range`, `Length`, `Pattern`, `Email` and custom constraints run on that cast value. Nested paths still work exactly as elsewhere. +Casters are in `Tomaj\NetteApi\Input`, including `DateFormat`, `UnixTimestamp` and `Split`. The caster runs **instead of** the built-in conversion for that property. It runs first, returns the property's declared value, and only then do `Range`, `Length`, `Pattern`, `Email` and custom constraints run on that cast value. A caster reports invalid client input by throwing `Tomaj\NetteApi\Input\CastException` with a clear message. It becomes a 400 in the normal error envelope under the property path: @@ -88,7 +88,7 @@ A caster reports invalid client input by throwing `Tomaj\NetteApi\Input\CastExce } ``` -Any other exception is a server error, not a validation error. Container compilation checks that the caster implements `CasterInterface`, accepts the attribute arguments and declares a native `cast()` return type matching the property type (`array` with list PHPDoc for `list`; `mixed` is not accepted). +Any other exception from a caster, or any exception from the constructor of a nested DTO, is a server error, not a validation error: the error handler answers it with `500` after the authorization. Container compilation checks that the caster implements `CasterInterface`, accepts the attribute arguments and declares a native `cast()` return type matching the property type (`array` with list PHPDoc for `list`; `mixed` is not accepted). ### OpenAPI schema hints diff --git a/docs/guide/typed-input.md b/docs/guide/typed-input.md index 1a8ade19c..578222e24 100644 --- a/docs/guide/typed-input.md +++ b/docs/guide/typed-input.md @@ -26,7 +26,7 @@ A handler declares its input in one of two equal ways. Both are fully supported, Pick `params()` when the endpoint relies on its looser conversion, on a custom `InputParam` or on manual parsing of an unusual body. Pick a DTO when you want typed values, nested bodies, cross-field constraints or the whole request contract in one class. Neither style is deprecated, and choosing one for an endpoint does not affect any other endpoint. [params() and DTO side by side](/guide/input-styles) shows the same endpoint written in both styles. -`TypedHandler` turns the DTO declaration into `InputParam` objects, so validation, OpenAPI and the console work as with `params()`. With the DI extension this metadata is compiled into the container, and changing a DTO, a caster, a constraint or an enum rebuilds it. A constant of another class used in an attribute argument or a default is not tracked; clear the cache after changing it. Without the extension the metadata is built once per process. +`TypedHandler` turns the DTO declaration into `InputParam` objects, so validation, OpenAPI and the console work as with `params()`. ## The smallest handler @@ -83,17 +83,15 @@ Attributes are in `Tomaj\NetteApi\Input` and target promoted constructor propert | `#[Body]` | a field in JSON, form or multipart body | `InputParam::TYPE_BODY`, part of `requestBody` | | `#[File]` | uploaded file | `InputParam::TYPE_FILE`, multipart `requestBody` | -Every DTO property becomes one `MappedInputParam`, an `InputParam` that validates and maps through the DTO metadata. Code that inspects `params()` checks `getType()`, not a concrete class. +Every root DTO property becomes one `MappedInputParam`, an `InputParam` that validates and maps through the DTO metadata. Code that inspects `params()` checks `getType()`, not a concrete class. For example, `#[Header('X-Request-Id')] public ?string $requestId = null` reads `X-Request-Id`, not `requestId`. Header lookup is case-insensitive. A `#[Path]` name starts with a letter or an underscore and has letters, digits and underscores, because it is written as a `{name}` segment; a `#[Header]` name uses dashes, not underscores (`X-Request-Id`, not `X_Request_Id`), because PHP exposes header names with dashes. Anything else is a compile-time error with the corrected name. A path or header value is one string, so a native list or nested DTO there is a compile-time error; split it with a caster, for example `#[Header('X-Tags')] #[Cast(Split::class, ',')] public array $tags`. `PathInputParam`, `HeaderInputParam` and `BodyInputParam` are also public for handlers that use `params()`, see [Input params](/guide/params#path-header-and-body-params). -Do not use `#[Header]` for a header that a proxy sets or strips to carry trust, such as `X-Forwarded-User`. PHP and web servers map `X_Request_Id` and `X-Request-Id` to the same name, so a client can send a look-alike. Authenticate such values in the proxy and drop the client's copy there. - ### Path values and URL templates -A path value is declared in the endpoint URL with `{name}`, for example `users/{id}/detail`. It is required, it cannot be nullable or have a default, and its OpenAPI path placeholder has the same name. A missing or undeclared path parameter is a container-compilation error. Static endpoint URLs work unchanged. A path value is one URL segment. Segments are URL-decoded after the path is split, so an encoded slash stays in the value: `/users/a%2Fb/detail` gives `id` `a/b`. +A path value is declared in the endpoint URL with `{name}`, for example `users/{id}/detail`. It is required, it cannot be nullable or have a default, and its OpenAPI path placeholder has the same name. A `{name}` without a `#[Path]` property, or a `#[Path]` property missing from the URL, fails the container compilation with the DI extension; with `addApi()` it throws a `LogicException` when the endpoint is first matched. Static endpoint URLs work unchanged. A path value is one URL segment. Segments are URL-decoded after the path is split, so an encoded slash stays in the value: `/users/a%2Fb/detail` gives `id` `a/b`. Register the template as the action of the endpoint, in any of the usual ways: @@ -112,13 +110,13 @@ final class UserDetailHandler extends TypedHandler $apiDecider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), new UserDetailHandler(), new NoAuthorization()); ``` -The route has to let the template segments through. The route of the [typed input example](/examples/typed-input), `/api/v/[/][/]`, lets one segment through after the action; a deeper template such as `{id}/orders/{orderId}` needs `[/]` in the route mask, otherwise Nette answers `404` before the API sees the request. A request is looked up among the static endpoints first and then among the templates. If two templates match one URL, the request fails with a `LogicException` that names both, so make a static segment differ. +The route has to let the template segments through. The route of the [typed input example](/examples/typed-input), `/api/v/[/][/]`, lets one segment through after the action; a deeper template such as `{id}/orders/{orderId}` needs `[/]` in the route mask, otherwise Nette answers `404` before the API sees the request. A request is looked up among the static endpoints first and then among the templates. When the URL has segments after the action, a template that matches the whole path wins over a shorter static endpoint: `/users/7/detail` goes to `users/{id}/detail`, not to a static `users/7`. Two templates that can match the same URL fail the container compilation with the DI extension; with `addApi()` the request throws a `LogicException` that names both. Make a static segment differ. ### Required values and defaults A non-nullable property without a default is required. A nullable property or a property with a default is optional. A missing nullable value becomes `null`; a missing value with a default uses that default. This also sets `required` in OpenAPI. -Required path parameters cannot be nullable or have a default. An optional body field accepts an omitted field, while an explicit JSON `null` is accepted only for a nullable property. An empty string is not silently converted to `null`. A default is `null`, a scalar, an array or a backed enum case; an object default such as `= new Inner()` is a compile-time error. Use `= null` and create the object in the handler. +An optional body field accepts an omitted field, while an explicit JSON `null` is accepted only for a nullable property. An empty string is not silently converted to `null`. A default is `null`, a scalar, an array or a backed enum case; an object default such as `= new Inner()` is a compile-time error. Use `= null` and create the object in the handler. ## Complete request example @@ -159,7 +157,7 @@ A request with a body, a nested DTO and a list is in [body, files and content ty ## Error responses -The response envelope stays the same as `ParamsProcessor`. The detail key is the field path: dots enter nested DTOs and brackets identify list items. Top-level sources use their external names. +Errors use the same envelope as `params()` handlers. The detail key is the field path: dots enter nested DTOs and brackets identify list items. Top-level sources use their external names. ```json { @@ -174,11 +172,11 @@ The response envelope stays the same as `ParamsProcessor`. The detail key is the } ``` -When error details are disabled, only `status` and `message` are returned. With Problem Details enabled, the same field paths and messages appear in its input-error extension. Malformed JSON and an unreadable body keep the existing body-parser errors. +When error details are disabled, only `status` and `message` are returned. With Problem Details enabled, the same field paths and messages appear in its `errors` list as `parameter` and `detail`. -Request-level body errors appear under `body`; avoid naming a field `body` (use `#[Body('payload')]`). +Errors of the body as a whole, such as malformed JSON (`Syntax error`), a charset other than UTF-8 or an unreadable body, appear under `body`; avoid naming a field `body` (use `#[Body('payload')]`). -A missing nested object reports the nested object path. Unknown input fields are ignored, matching ordinary query/form parameter handling; they are not silently mapped to properties. +A missing nested object reports the nested object path. Unknown input fields are ignored, as with ordinary query and form params. ## OpenAPI and the API console @@ -210,17 +208,19 @@ parameters: JSON schema is generated here only as an OpenAPI output format. Runtime validation uses the recursive DTO mapper and never requires a JSON schema. -### Long-running workers - -The request values of a typed handler are kept in process-wide static state that `ApiPresenter::run()` resets at the start of every request, so workers (RoadRunner, FrankenPHP, Swoole) are fine as long as each handles one request at a time; concurrent coroutines in one process are not supported. Code that calls a typed handler's `params()` outside the presenter in a worker calls `Tomaj\NetteApi\Input\RequestInput::reset()` and `Tomaj\NetteApi\Params\PathValues::reset()` first. - ## Security notes - **Mapping runs before authorization.** The input is converted and validated before the authorization is checked, and only the answer waits for it: a client without access gets `401`, not field errors. The rate limit still runs first. A caster or a constraint is therefore reachable without a login, so keep them pure and cheap: no database, network or file access. Put `#[Length(max: ...)]` on every list. - **Cap the request body at the web server.** `#[Length(max: ...)]` limits a list before its items are mapped, but the body is decoded first, and a decoded list takes many times more memory in PHP than in the request. Limit the size where the request enters: `client_max_body_size` in nginx, `LimitRequestBody` in Apache, and `post_max_size` and `memory_limit` in PHP. -- **`#[Header]` is not proof of origin.** See the note under [source attributes](#source-attributes). +- **`#[Header]` is not proof of origin.** Do not use it for a header that a proxy sets or strips to carry trust, such as `X-Forwarded-User`. PHP and web servers map `X_Request_Id` and `X-Request-Id` to the same name, so a client can send a look-alike. Authenticate such values in the proxy and drop the client's copy there. - **Form bodies and cookies.** A DTO with body fields accepts URL-encoded forms by default, which any website can submit without a CORS preflight. For an endpoint authenticated by a cookie or by the client address, use `#[Consumes('application/json')]`, see [body, files and content types](/guide/typed-input-body#forms-and-cookie-authenticated-endpoints). +## Compiled metadata and workers + +With the DI extension the DTO metadata is compiled into the container, and changing a DTO, a caster, a constraint or an enum rebuilds it. A constant of another class used in an attribute argument or a default is not tracked; clear the cache after changing it. Without the extension the metadata is built once per process. + +Every read of a typed handler's `params()` parses the current request again, and the path values are set by `ApiDecider` for each request, so workers (RoadRunner, FrankenPHP, Swoole) are fine as long as each handles one request at a time; concurrent coroutines in one process are not supported. + ## Example A runnable project with every source attribute, a nested body and a file upload is described in [Typed input example](/examples/typed-input). diff --git a/docs/index.md b/docs/index.md index 65fbe6898..0cd202374 100644 --- a/docs/index.md +++ b/docs/index.md @@ -71,7 +71,7 @@ and a few lines of configuration register it as `GET /api/v1/hello`: <<< @/../examples/hello-world/config/common.neon{yaml} -The `params()` tab is the [hello world example](/examples/hello-world), which runs in CI; the typed version is `GreetHandler` in [`examples/attributes`](/examples/attributes). +The `params()` tab is the [hello world example](/examples/hello-world), which runs in CI; a variant of the typed version is `GreetHandler` in [`examples/attributes`](/examples/attributes). ## Where to go next diff --git a/docs/sk/api/reference.md b/docs/sk/api/reference.md index 01b651fa4..2bccee6f2 100644 --- a/docs/sk/api/reference.md +++ b/docs/sk/api/reference.md @@ -46,13 +46,12 @@ Všetky triedy sú pod `Tomaj\NetteApi`. | Trieda | Čo robí | Príručka | | --- | --- | --- | | `Input\Query`, `Path`, `Header`, `Body`, `File` | atribúty, ktoré určujú, odkiaľ sa property DTO číta | [Typovaný vstup](/sk/guide/typed-input#atributy-zdroja) | -| `Input\Consumes`, `Input\FileUpload` | obmedzí akceptované media typy tela; typovaná hodnota nahraného súboru | [Telo, súbory a content typy](/sk/guide/typed-input-body) | +| `Input\Consumes`, `Input\FileUpload` | obmedzí akceptované media typy tela; typovaná hodnota nahraného súboru | [Telo, súbory a typy obsahu](/sk/guide/typed-input-body) | | `Input\Cast`, `CasterInterface`, `OpenApiCasterInterface`, `CastException` | vlastná konverzia jednej property | [Konverzia](/sk/guide/typed-input-conversion#vlastne-konverzie-cez-cast) | | `Input\DateFormat`, `UnixTimestamp`, `Split` | vstavané castery | [Konverzia](/sk/guide/typed-input-conversion#vstavane-castery-a-cesky-datum) | | `Validation\Range`, `Length`, `Pattern`, `Email` | vstavané validačné obmedzenia | [Validačné obmedzenia](/sk/guide/typed-input-conversion#validacne-obmedzenia) | | `Validation\ConstraintInterface`, `ConstraintContext` | vaše vlastné validačné obmedzenia | [Vlastné validačné obmedzenia](/sk/guide/typed-input-conversion#vlastne-validacne-obmedzenia) | | `Params\MappedInputParam` | `InputParam` vygenerovaný pre jednu property DTO | [Typovaný vstup](/sk/guide/typed-input) | -| `Input\RequestInput`, `Params\PathValues` | stav požiadavky typovaného handlera, nulovaný v dlho bežiacich workeroch | [Dlho bežiace workery](/sk/guide/typed-input#dlho-beziace-workery) | Ostatné triedy namespace `Input` sú mechanika za týmito (kompilátor, mapper, metadáta, schéma a pomocníci konverzie). Nie sú uvedené a nie sú určené na rozširovanie ani na priame volanie. diff --git a/docs/sk/examples/typed-input.md b/docs/sk/examples/typed-input.md index d80b50631..8d6e95a0c 100644 --- a/docs/sk/examples/typed-input.md +++ b/docs/sk/examples/typed-input.md @@ -22,10 +22,10 @@ Typované handlery, path a header parametre a `#[Consumes]` sú nové v 4.0.0. | `POST /api/v1/orders` JSON | `201` | vnorené DTO a `list` | | `POST /api/v1/orders` formulár | `201` | to isté DTO, zátvorkové mená | | `POST /api/v1/orders` neplatné telo | `400` | `items[1].quantity` | -| `POST /api/v1/orders` `text/csv` | `415` | content type mimo predvolenej dvojice | +| `POST /api/v1/orders` `text/csv` | `415` | typ obsahu mimo predvolenej dvojice | | `POST /api/v1/orders` PSČ `81101` a nový riadok | `400` | `$` vo vzore končí reťazec | | `POST /api/v1/avatar` multipart | `201` | `FileUpload` | -| `GET /api/v1/openapi` | `200` | path parameter a oba content typy tela | +| `GET /api/v1/openapi` | `200` | parametre cesty a hlavičky, multipart telo | ## Query DTO diff --git a/docs/sk/faq.md b/docs/sk/faq.md index 49b1ed79c..8e73a892e 100644 --- a/docs/sk/faq.md +++ b/docs/sk/faq.md @@ -35,11 +35,11 @@ V 3.x presenter skončí pred loggerom. Pozrite si [Logovanie](/sk/guide/logging ## Mám používať params() alebo typované DTO? -Ktorékoľvek: sú to dva rovnocenné spôsoby deklarácie vstupu handlera a jedno API ich môže miešať. V stránke [Typovaný vstup (DTO)](/sk/guide/typed-input) je, v čom sa líšia, a [params() a DTO vedľa seba](/sk/guide/input-styles) ukazuje tie isté endpointy v oboch štýloch. +Ktorékoľvek: sú to dva rovnocenné spôsoby deklarácie vstupu handlera a jedno API ich môže miešať. Na stránke [Typovaný vstup (DTO)](/sk/guide/typed-input) je, v čom sa líšia, a [params() a DTO vedľa seba](/sk/guide/input-styles) ukazuje tie isté endpointy v oboch štýloch. ## Prečo môj typovaný endpoint vracia 415? -Telo má content type, ktorý handler neprijíma, alebo žiadny. DTO s poľami tela predvolene prijíma JSON a URL-enkódovaný formulár a `#[Consumes]` to mení. Pozrite [telo, súbory a content typy](/sk/guide/typed-input-body). +Telo má typ obsahu, ktorý handler neprijíma, alebo žiadny. DTO s poľami tela predvolene prijíma JSON a URL-enkódovaný formulár a `#[Consumes]` to mení. Pozrite [telo, súbory a typy obsahu](/sk/guide/typed-input-body). ## Dá sa API nastaviť bez zoznamu volaní addApi()? diff --git a/docs/sk/guide/api-decider.md b/docs/sk/guide/api-decider.md index 040361768..baa9d55d4 100644 --- a/docs/sk/guide/api-decider.md +++ b/docs/sk/guide/api-decider.md @@ -59,7 +59,7 @@ services: ### Endpointy so segmentmi {name} -Endpoint, ktorého akcia má segmenty `{name}`, napríklad `users/{id}/detail`, potrebuje cestu požiadavky. `ApiPresenter` najprv zavolá `getApi()` a keď ten nič nenájde, zavolá `matchPath($method, $version, $package, $apiAction, $path)`. Statický endpoint teda vždy vyhrá. `matchPath()` porovná cestu so všetkými šablónami danej metódy a verzie, uloží zhodné hodnoty pre properties `#[Path]` a vráti `Api`, alebo `null`, keď nezodpovedá žiadna šablóna. Ak jednej ceste vyhovujú dve šablóny, vyhodí `LogicException`, ktorá ich vymenuje, takže zmeňte statický segment tak, aby sa líšili. Globálny preflight odpovie na `OPTIONS` aj pre cestu, ktorá zodpovedá šablóne. Ako šablónu zaregistrovať a smerovať, je v stránke [Typovaný vstup](/sk/guide/typed-input#hodnoty-z-cesty-a-sablony-url). +Endpoint, ktorého akcia má segmenty `{name}`, napríklad `users/{id}/detail`, potrebuje cestu požiadavky. `ApiPresenter` najprv zavolá `getApi()` a keď ten nič nenájde, zavolá `matchPath($method, $version, $package, $apiAction, $path)`, takže pri tej istej URL vyhrá statický endpoint. Keď má URL za akciou ďalšie segmenty, `ApiPresenter` skúsi `matchPath()` ako prvé: šablóna, ktorá zodpovedá celej ceste, napríklad `users/{id}/detail` pre `/users/7/detail`, vyhrá nad kratším statickým endpointom `users/7`. `matchPath()` porovná cestu so všetkými šablónami danej metódy a verzie, uloží zhodné hodnoty pre properties `#[Path]` a vráti `Api`, alebo `null`, keď nezodpovedá žiadna šablóna. Ak jednej ceste vyhovujú dve šablóny, vyhodí `LogicException`, ktorá ich vymenuje; s DI rozšírením takéto šablóny zastavia už kompiláciu kontajnera. Zmeňte statický segment tak, aby sa líšili. Globálny preflight odpovie na `OPTIONS` aj pre cestu, ktorá zodpovedá šablóne. Ako šablónu zaregistrovať a smerovať, je na stránke [Typovaný vstup](/sk/guide/typed-input#hodnoty-z-cesty-a-sablony-url). `GET /api/v1/users` a `POST /api/v1/users` sú dva endpointy s dvoma handlermi. Nezaregistrovaná verzia, napríklad `/api/v3/users`, je `404`, ako testuje [príklad verzií](/sk/examples/versions). diff --git a/docs/sk/guide/attributes.md b/docs/sk/guide/attributes.md index f3fcd71bd..2f41c5d75 100644 --- a/docs/sk/guide/attributes.md +++ b/docs/sk/guide/attributes.md @@ -31,7 +31,7 @@ final class UsersListHandler extends BaseHandler } ``` -```php [Typed DTO] +```php [Typované DTO] namespace App\Api; use Tomaj\NetteApi\Attribute\Get; diff --git a/docs/sk/guide/console.md b/docs/sk/guide/console.md index cdd87674a..7e824dce0 100644 --- a/docs/sk/guide/console.md +++ b/docs/sk/guide/console.md @@ -42,7 +42,7 @@ Konzola zostaví požiadavku z parametrov handlera, či už pochádzajú z `para | pole tela | prvý media type, ktorý handler číta a konzola ho vie zostaviť: JSON, URL-enkódovaný formulár alebo multipart | | súbor | multipart upload; pri priloženom súbore idú polia tela v tej istej multipart požiadavke | -V tele JSON si každá hodnota zachová deklarovaný typ; vnorený objekt alebo položka zoznamu, ktorá je objekt, berie JSON text. Prázdne voliteľné polia sa neposielajú; pri prázdnej hodnote z cesty konzola namiesto odoslania ukáže chybu. +V tele JSON si každá hodnota zachová deklarovaný typ; vnorený objekt alebo položka zoznamu, ktorá je objekt, berie JSON text. Prázdne voliteľné polia sa neposielajú; pri prázdnej hodnote z cesty, `.` alebo `..` konzola namiesto odoslania ukáže chybu. ## Časté otázky diff --git a/docs/sk/guide/errors.md b/docs/sk/guide/errors.md index 97485af78..f236c7030 100644 --- a/docs/sk/guide/errors.md +++ b/docs/sk/guide/errors.md @@ -18,7 +18,7 @@ description: Ako Nette API mení výnimky, zlý vstup, zlyhanú autorizáciu a p | `handleAuthorizationException(Throwable, array $params)` | `authorized()` vyhodil výnimku | `500 Internal server error`, loguje do Tracy | | `handleNotFound(EndpointInterface)` | URL nezodpovedá žiadny endpoint | `404 Unknown api endpoint` | | `handleRateLimit(RateLimitResponse)` | limit je vyčerpaný a nemá vlastnú odpoveď | `429 Too many requests.`, ak je čas známy, aj `Retry after N seconds.` | -| `handleUnsupportedMediaType(string $detail)` | typovaný handler dostane telo s content typom, ktorý neprijíma | `415 unsupported media type`, s akceptovanými typmi v `detail` len so zapnutými detailmi chýb | +| `handleUnsupportedMediaType(string $detail)` | typovaný handler dostane telo s typom obsahu, ktorý neprijíma | `415 unsupported media type`, s akceptovanými typmi v `detail` len so zapnutými detailmi chýb | Všetky vracajú `ResponseInterface`; `DefaultErrorHandler` vracia `JsonApiResponse` so `status: error` a `message`. diff --git a/docs/sk/guide/getting-started.md b/docs/sk/guide/getting-started.md index 73bfd1838..8e80fe227 100644 --- a/docs/sk/guide/getting-started.md +++ b/docs/sk/guide/getting-started.md @@ -109,7 +109,7 @@ Potom súbor načítajte v `app/Bootstrap.php`: ## 4. Napíšte handler -Vytvorte `app/Api/HelloHandler.php`. Handler deklaruje svoj vstup jedným z dvoch rovnocenných spôsobov: zoznamom parametrov v `params()` alebo typovaným DTO, ktoré dostane `handleDto()`. Oba prechádzajú rovnakým validačným pipeline a dávajú rovnaké OpenAPI aj webovú konzolu a jedno API ich môže kombinovať. Typované DTO konvertuje hodnoty prísnejšie než `params()`. +Vytvorte `app/Api/HelloHandler.php`. Handler deklaruje svoj vstup jedným z dvoch rovnocenných spôsobov: zoznamom parametrov v `params()` alebo typovaným DTO, ktoré dostane `handleDto()`. Oba prechádzajú rovnakou validáciou a dávajú rovnaké OpenAPI aj webovú konzolu a jedno API ich môže kombinovať. Typované DTO konvertuje hodnoty prísnejšie než `params()`. ::: code-group @@ -146,7 +146,7 @@ final class HelloHandler extends BaseHandler } ``` -```php [Typed DTO] +```php [Typované DTO] setRequired(), + new PathInputParam('id', InputType::INTEGER), // vždy povinný new HeaderInputParam('X-Request-Id', InputType::STRING), ]; } @@ -144,7 +144,7 @@ final class UserDetailHandler extends TypedHandler Registrácia endpointu a URL sa nemenia. Deklarácia DTO stále vygeneruje `id` ako povinný parameter cesty a `X-Request-Id` ako voliteľnú hlavičku v OpenAPI. -### 3. POST JSON: vnorený objekt a pole +### 3. POST JSON: vnorený objekt a zoznam S `params()` obsahuje `JsonInputParam` ručne písanú schému. Handler číta vnorené polia a vytvára vlastné hodnoty: @@ -230,7 +230,7 @@ final readonly class CreateOrderInput public function __construct( #[Body] #[Email] public string $customerEmail, #[Body] public AddressInput $address, - #[Body] #[Length(min: 1)] public array $items, + #[Body] #[Length(min: 1, max: 50)] public array $items, ) { } } @@ -253,7 +253,7 @@ final class CreateOrderHandler extends TypedHandler } ``` -`list` je dôležité: mapperu aj OpenAPI hovorí, čo obsahuje položka poľa. Chyba v quantity druhej položky sa nahlási pod `items[1].quantity`. +`list` je dôležité: mapperu aj OpenAPI hovorí, čo obsahuje položka zoznamu. Chyba v quantity druhej položky sa nahlási pod `items[1].quantity`. ### 4. Formulárový POST @@ -304,7 +304,7 @@ final class LoginHandler extends TypedHandler } ``` -Formulár stále posiela `email=ada%40example.com&password=...&remember=1`. Mapper DTO odmietne neznáme boolean reťazce namiesto toho, aby každý neprázdny reťazec považoval za `true`. +Formulár stále posiela `email=ada%40example.com&password=...&remember=1`. Mapper DTO odmietne neznáme boolean reťazce namiesto toho, aby každý neprázdny reťazec považoval za `true`. `#[Email]` a `#[Length]` sú kontroly navyše, ktoré verzia s `params()` nerobí. ### 5. Nahrávanie súboru @@ -440,7 +440,7 @@ final class ScheduleHandler extends TypedHandler 3. **Zachovajte externé názvy:** použite explicitné názvy atribútov ako `#[Header('X-Request-Id')]`, ak sa názov property líši. 4. **Zlaďte povinnosť:** nenulovateľná property bez predvolenej hodnoty je povinná; nulovateľná alebo s predvolenou hodnotou je voliteľná. 5. **Nahraďte ručné deklarácie:** použite enumy s hodnotami (backed enum) pre povolené hodnoty a vstavané validačné obmedzenia tam, kde zodpovedajú existujúcim kontrolám. -6. **Spracujte vnorené dáta:** vytvorte vnorené DTO a pridajte PHPDoc `list` pre polia DTO. +6. **Spracujte vnorené dáta:** vytvorte vnorené DTO a pridajte PHPDoc `list` pre zoznamy DTO. 7. **Presuňte len validáciu kontraktu:** databázové vyhľadávania a obchodné pravidlá nechajte v službách alebo handleri; pre deterministické pravidlá vstupu použite vlastné validačné obmedzenia. 8. **Prepnite základnú triedu:** nahraďte `handle(array $params)` za `handleDto(Input $input)` a odstráňte ručné pretypovania/prístupy k poľu. 9. **Porovnajte správanie:** spustite úspešné aj chybné požiadavky, skontrolujte cesty polí, porovnajte OpenAPI a skontrolujte formulár konzoly a nahrávanie. diff --git a/docs/sk/guide/layers.md b/docs/sk/guide/layers.md index e92f89b0f..aee1a1f8c 100644 --- a/docs/sk/guide/layers.md +++ b/docs/sk/guide/layers.md @@ -114,7 +114,7 @@ public function handle(array $params): ResponseInterface | `handleSchema()` | výstup nezodpovedá | `500` | | `handleAuthorization()` | `authorized()` vrátil false | `401` so správou | | `handleAuthorizationException()` | `authorized()` vyhodil výnimku | `500` so správou výnimky | -| `handleUnsupportedMediaType()` | typovaný handler dostal telo s iným content typom | `415` | +| `handleUnsupportedMediaType()` | typovaný handler dostal telo s iným typom obsahu | `415` | Pozrite si [Spracovanie chýb](/sk/guide/errors). diff --git a/docs/sk/guide/links.md b/docs/sk/guide/links.md index 2d9242eac..a65e35326 100644 --- a/docs/sk/guide/links.md +++ b/docs/sk/guide/links.md @@ -15,7 +15,7 @@ $url = $apiLink->link(new EndpointIdentifier('GET', 1, 'users', 'detail'), ['id' Potrebuje routu na `Api:Api:default` s parametrami `version`, `package` a `apiAction`, ako v [Začíname](/sk/guide/getting-started). -Pri endpointe, ktorého URL má segmenty `{name}`, napríklad `{id}/detail`, `link()` doplní každý segment z rovnomenného parametra (s URL kódovaním); ostatné parametre idú do query stringu. Segment bez hodnoty ostane doslovný, čo je šablóna cesty z OpenAPI: +Pri endpointe, ktorého URL má segmenty `{name}`, napríklad `{id}/detail`, `link()` doplní každý segment z rovnomenného parametra (s URL kódovaním); ostatné parametre idú do query stringu. Segment bez hodnoty ostane doslovný, čo je šablóna cesty z OpenAPI. Hodnota cesty `''`, `'.'` alebo `'..'` vyhodí `Nette\Application\UI\InvalidLinkException`, pretože taký segment by nikdy nezodpovedal alebo by sa vyhodnotil na inú URL: ```php $url = $apiLink->link(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), ['id' => 42, 'limit' => 5]); diff --git a/docs/sk/guide/outputs.md b/docs/sk/guide/outputs.md index 39300c57a..1a1759522 100644 --- a/docs/sk/guide/outputs.md +++ b/docs/sk/guide/outputs.md @@ -12,7 +12,7 @@ description: Vracanie JSON, textu, XML alebo presmerovaní z handlerov Nette API | Trieda | Konštruktor | Posiela | | --- | --- | --- | | `JsonApiResponse` | `(int $code, array\|JsonSerializable $payload, string $contentType = 'application/json', string $charset = 'utf-8', $expiration = null)` | JSON s `Content-Length` | -| `TextApiResponse` | `(int $code, $data)` | reťazec tak, ako je, alebo vykreslí Latte šablónu; content type nenastavuje | +| `TextApiResponse` | `(int $code, $data)` | reťazec tak, ako je, alebo vykreslí Latte šablónu; typ obsahu nenastavuje | | `XmlApiResponse` | `(int $code, string $data, $expiration = null)` | XML reťazec ako `text/xml` s `Content-Length` | | `RedirectResponse` | `(string $url, int $httpCode = 302)` | presmerovanie | @@ -35,7 +35,7 @@ return new TextApiResponse(IResponse::S200_OK, "id,name\n7,Ann\n"); ``` - `XmlApiResponse` berie hotový XML reťazec; zostavte ho cez `SimpleXMLElement`, `DOMDocument` alebo šablónu. -- `TextApiResponse` nenastavuje content type, takže platí predvolený (PHP `default_mimetype`, zvyčajne `text/html`). Pre CSV, YAML alebo súbory si ho nastavte vo vlastnej triede. Vstavaný `OpenApiHandler` posiela cez `TextApiResponse` svoj YAML výstup. +- `TextApiResponse` nenastavuje typ obsahu, takže platí predvolený (PHP `default_mimetype`, zvyčajne `text/html`). Pre CSV, YAML alebo súbory si ho nastavte vo vlastnej triede. Vstavaný `OpenApiHandler` posiela cez `TextApiResponse` svoj YAML výstup. - Pre ľubovoľný iný formát napíšte triedu, ktorá implementuje `ResponseInterface`: Nette `IResponse` s `getCode()`. - Triedu výstupu majú iba `JsonApiResponse` a `RedirectResponse`. So zapnutou validáciou musí endpoint s neprázdnym `outputs()` vrátiť jednu z nich, takže pri XML alebo textových endpointoch nechajte `outputs()` prázdne. diff --git a/docs/sk/guide/params.md b/docs/sk/guide/params.md index 671a53235..30fd16be5 100644 --- a/docs/sk/guide/params.md +++ b/docs/sk/guide/params.md @@ -63,13 +63,13 @@ V 3.x `?limit=abc` s typom `INTEGER` nie je chyba: hodnota sa pred validáciou p ## Parametre Path, Header a Body -`PathInputParam` číta hodnotu z URL endpointu. Placeholder deklarujte v akcii endpointu ako `{name}`, napríklad `users/{id}/detail`, ako popisuje [Typovaný vstup](/sk/guide/typed-input#hodnoty-z-cesty-a-sablony-url). Parameter je vždy povinný a jeho placeholder v OpenAPI má rovnaký názov. `HeaderInputParam` číta hlavičku požiadavky bez ohľadu na veľkosť písmen. `BodyInputParam` číta jedno pole objektu JSON, URL-enkódovaného formulára alebo multipart tela a `setContentTypes()` uvádza media typy, ktoré prijíma. V typovanom DTO sa z properties `#[Path]`, `#[Header]` a `#[Body]` stanú objekty `MappedInputParam` s typom `TYPE_PATH`, `TYPE_HEADER` alebo `TYPE_BODY`; `params()` deklaruje tieto triedy priamo: +`PathInputParam` číta hodnotu z URL endpointu. Placeholder deklarujte v akcii endpointu ako `{name}`, napríklad `users/{id}/detail`, ako popisuje [Typovaný vstup](/sk/guide/typed-input#hodnoty-z-cesty-a-sablony-url). Parameter je vždy povinný a jeho placeholder v OpenAPI má rovnaký názov. `HeaderInputParam` číta hlavičku požiadavky bez ohľadu na veľkosť písmen. `BodyInputParam` číta jedno pole objektu JSON, URL-enkódovaného formulára alebo multipart tela a `setContentTypes()` nastaví media typy, ktoré dokumentuje OpenAPI a používa konzola; nevynucujú sa, takže handler s `params()` nikdy neodpovie `415`. V typovanom DTO sa z properties `#[Path]`, `#[Header]` a `#[Body]` stanú objekty `MappedInputParam` s typom `TYPE_PATH`, `TYPE_HEADER` alebo `TYPE_BODY`; `params()` deklaruje tieto triedy priamo: ```php public function params(): array { return [ - (new PathInputParam('id', InputType::INTEGER))->setRequired(), + new PathInputParam('id', InputType::INTEGER), // vždy povinný new HeaderInputParam('X-Request-Id', InputType::STRING), (new BodyInputParam('email', InputType::STRING)) ->setRequired() diff --git a/docs/sk/guide/presenter.md b/docs/sk/guide/presenter.md index 66e2303bc..981290da0 100644 --- a/docs/sk/guide/presenter.md +++ b/docs/sk/guide/presenter.md @@ -12,7 +12,7 @@ description: 'Presné poradie krokov v Nette API ApiPresenter::run(), od CORS a | Krok | Kód | Výstup | | --- | --- | --- | | 1. CORS hlavičky | `sendCorsHeaders()` | | -| 2. Endpoint | `$this->apiDecider->getApi(...)`, potom `matchPath(...)` pre URL s `{name}` | `404` cez `DefaultHandler` a `handleNotFound()` | +| 2. Endpoint | `$this->apiDecider->getApi(...)`, potom `matchPath(...)` pre URL s `{name}` (ako prvé, keď má URL za akciou ďalšie segmenty) | `404` cez `DefaultHandler` a `handleNotFound()` | | 3. Obmedzenie požiadaviek | `checkRateLimit($rateLimit)` | `429`, neloguje sa | | 4. Načítanie parametrov | `new ParamsProcessor($handler->params())` | | | 5. Autorizácia | `checkAuth($authorization, $params)` | `401` alebo `500`, neloguje sa | @@ -48,7 +48,7 @@ $paramsProcessor = new ParamsProcessor($handler->params()); $params = $paramsProcessor->isError() ? [] : $paramsProcessor->getValues(); ``` -Každý parameter sa načíta a overí. Pri chybe je `$params` prázdne a chyba počká na krok 6. +Každý parameter sa načíta a overí. Pri chybe je `$params` prázdne a chyba počká na krok 6. Počká aj výnimka vyhodená pri načítaní, napríklad z konštruktora vnoreného DTO alebo z castera: po autorizácii na ňu error handler odpovie `500`. ## 5. Autorizácia diff --git a/docs/sk/guide/problem-details.md b/docs/sk/guide/problem-details.md index 4697b0b4a..2df37457b 100644 --- a/docs/sk/guide/problem-details.md +++ b/docs/sk/guide/problem-details.md @@ -44,7 +44,7 @@ Nechajte len jednu službu error handlera: pri dvoch Nette DI nevie autowirovať | `authorized()` je false, `handleAuthorization()` | `401` | `unauthorized` | `getErrorMessage()` | | | neznámy endpoint, `handleNotFound()` | `404` | `not-found` | `Unknown api endpoint` | | | vyčerpaný limit, `handleRateLimit()` | `429` | `rate-limited` | `Too many requests.`, ak je čas známy, aj `Retry after N seconds.` | `limit`, `retryAfter`, ak je známy | -| content type tela nie je akceptovaný, `handleUnsupportedMediaType()` | `415` | `unsupported-media-type` | prijatý typ a akceptované typy | | +| typ obsahu tela nie je akceptovaný, `handleUnsupportedMediaType()` | `415` | `unsupported-media-type` | prijatý typ a akceptované typy | | | výnimka v handleri, `handle()` | `500` | `internal-error` | text výnimky, len so zapnutými detailmi | | | výnimka v `authorized()`, `handleAuthorizationException()` | `500` | `internal-error` | text výnimky, len so zapnutými detailmi | | | výstup nesedí, `handleSchema()` | `500` | `invalid-output` | žiadny | `outputErrors`, len so zapnutými detailmi | @@ -105,7 +105,7 @@ services: ) ``` -Nechajte len jednu službu `OpenApiHandler`: `addApi()` ju hľadá podľa názvu triedy, a ak sú dve, endpoint OpenAPI spadne s chybou „Multiple services of type“. Odpovede, ktoré handler uvádza v `outputs()`, napríklad `409` vyššie, sú opísané ako `application/json`, lebo `JsonOutput` nemá content type. Pozrite si [OpenAPI](/sk/guide/openapi). +Nechajte len jednu službu `OpenApiHandler`: `addApi()` ju hľadá podľa názvu triedy, a ak sú dve, endpoint OpenAPI spadne s chybou „Multiple services of type“. Odpovede, ktoré handler uvádza v `outputs()`, napríklad `409` vyššie, sú opísané ako `application/json`, lebo `JsonOutput` nemá typ obsahu. Pozrite si [OpenAPI](/sk/guide/openapi). ## Časté otázky diff --git a/docs/sk/guide/typed-input-body.md b/docs/sk/guide/typed-input-body.md index 0e747e98e..b5733f4ab 100644 --- a/docs/sk/guide/typed-input-body.md +++ b/docs/sk/guide/typed-input-body.md @@ -1,13 +1,13 @@ --- -title: 'Typovaný vstup: telo, súbory a content typy' -description: 'Polia tela typovaného DTO v Nette API: vnorené objekty a zoznamy, content typy JSON, formulár a multipart, Consumes, 415 a nahrávanie súborov.' +title: 'Typovaný vstup: telo, súbory a typy obsahu' +description: 'Polia tela typovaného DTO v Nette API: vnorené objekty a zoznamy, typy obsahu JSON, formulár a multipart, Consumes, 415 a nahrávanie súborov.' --- -# Typovaný vstup: telo, súbory a content typy +# Typovaný vstup: telo, súbory a typy obsahu -Táto stránka popisuje polia tela typovaného DTO: vnorené objekty a zoznamy, content typy JSON, formulár a multipart, `#[Consumes]` a nahrávanie súborov. Základy sú v stránke [Typovaný vstup (DTO)](/sk/guide/typed-input). +Táto stránka popisuje polia tela typovaného DTO: vnorené objekty a zoznamy, typy obsahu JSON, formulár a multipart, `#[Consumes]` a nahrávanie súborov. Základy sú na stránke [Typovaný vstup (DTO)](/sk/guide/typed-input). -## POST s vnoreným DTO a poľom +## POST s vnoreným DTO a zoznamom ```php final readonly class AddressInput @@ -73,9 +73,9 @@ JSON telo požiadavky: } ``` -Mapper DTO rekurzívne vytvorí `AddressInput` a oba objekty `ItemInput`. Pole DTO potrebuje PHPDoc, napríklad `list`, a pole skalárov `list`, `list`, `list` alebo `list` (fungujú aj `non-empty-list`, `T[]`, `@phpstan-param` a `@psalm-param`); asociatívne polia, union typy, `mixed`, `object` a netypované polia zlyhajú pri kompilácii kontajnera. +Mapper DTO rekurzívne vytvorí `AddressInput` a oba objekty `ItemInput`. Zoznam DTO potrebuje PHPDoc, napríklad `list`, a zoznam skalárov `list`, `list`, `list` alebo `list` (fungujú aj `T[]`, `@phpstan-param` a `@psalm-param`; `non-empty-list` sa číta ako `list`, takže na vyžadovanie položiek pridajte `#[Length(min: 1)]`); asociatívne polia, union typy, `mixed`, `object` a netypované polia zlyhajú pri kompilácii kontajnera. -Rovnaké DTO funguje s URL-enkódovanými formulárovými poľami a s multipart poľami, ak má property `#[File]` alebo `#[Consumes('multipart/form-data')]`. Vnorené polia používajú PHP zápis s hranatými zátvorkami, napríklad `address[street]` a `items[0][sku]`; `deliveryAt` ostáva rovnaký RFC 3339 reťazec. Parsovanie tela závisí od content typu, nie od JSON schémy. +Rovnaké DTO funguje s URL-enkódovanými formulárovými poľami a s multipart poľami, ak má property `#[File]` alebo `#[Consumes('multipart/form-data')]`. Vnorené polia používajú PHP zápis s hranatými zátvorkami, napríklad `address[street]` a `items[0][sku]`; `deliveryAt` ostáva rovnaký RFC 3339 reťazec. Parsovanie tela závisí od typu obsahu, nie od JSON schémy. OpenAPI toto telo zdokumentuje takto (odpovede sú vynechané): @@ -129,9 +129,9 @@ requestBody: address: {style: deepObject, explode: true} ``` -## Content typy tela +## Typy obsahu tela -`TypedHandler` s poľami tela predvolene akceptuje **`application/json`** a **`application/x-www-form-urlencoded`**, alebo **`application/json`** a **`multipart/form-data`**, keď jeho DTO obsahuje property `#[File]`; OpenAPI uvádza rovnaké typy v `requestBody.content` (pri povinnom súbore len multipart). Content type sa porovnáva bez parametrov. JSON musí byť v UTF-8: požiadavka, ktorá uvedie iný `charset`, je `400`. Telo bez `Content-Type` alebo s typom, ktorý handler neprijíma, je `415`. Properties so súbormi sú len v schéme `multipart/form-data` a JSON požiadavka na DTO s povinným súborom dostane `400`, ktorá vysvetlí, že súbory potrebujú `multipart/form-data`. +`TypedHandler` s poľami tela predvolene akceptuje **`application/json`** a **`application/x-www-form-urlencoded`**, alebo **`application/json`** a **`multipart/form-data`**, keď jeho DTO obsahuje property `#[File]`; OpenAPI uvádza rovnaké typy v `requestBody.content` (pri povinnom súbore len multipart). Typ obsahu sa porovnáva bez parametrov. JSON musí byť v UTF-8: požiadavka, ktorá uvedie iný `charset`, je `400`. Telo bez `Content-Type` alebo s typom, ktorý handler neprijíma, je `415`. Properties so súbormi sú len v schéme `multipart/form-data` a JSON požiadavka na DTO s povinným súborom dostane `400`, ktorá vysvetlí, že súbory potrebujú `multipart/form-data`. ### Obmedzenie akceptovaných typov cez Consumes @@ -156,9 +156,9 @@ final class ImportHandler extends TypedHandler } ``` -Endpoint iba na nahrávanie použije `#[Consumes('multipart/form-data')]`. Obmedzenie na formulárový typ bez `multipart/form-data` znamená, že endpoint nemôže prijať súbory; nemožná kombinácia, napríklad povinný `#[File]` s konzumáciou len JSON, je chybou kompilácie kontajnera. +Endpoint iba na nahrávanie použije `#[Consumes('multipart/form-data')]`. DTO s property `#[File]`, povinnou aj voliteľnou, musí mať v `#[Consumes]` uvedený `multipart/form-data`; inak zlyhá kompilácia kontajnera. -Požiadavka s iným content typom sa pred mapovaním odmietne s **415 Unsupported Media Type**. 415 sa pošle až po autorizácii a obmedzeniach požiadaviek, takže klient bez prístupu dostane `401`, a `ApiLoggerInterface` ju zaloguje ako obslúženú požiadavku. Pri zapnutých detailoch chýb hláška uvádza prijatý typ aj presné akceptované typy, napríklad: +Požiadavka s iným typom obsahu sa pred mapovaním odmietne s **415 Unsupported Media Type**. 415 sa pošle až po autorizácii a obmedzeniach požiadaviek, takže klient bez prístupu dostane namiesto nej `401`. Pri zapnutých detailoch chýb hláška uvádza prijatý typ aj presné akceptované typy, napríklad: ```json { @@ -179,7 +179,7 @@ So zapnutými Problem Details má 415 tento formát a jeho `detail` vždy uvádz | Natívne skalárne typy | čísla a booleany ostávajú JSON číslami/booleanmi | hodnoty prichádzajú ako reťazce a prechádzajú rovnakou striktnou konverziou | | Null | explicitné `null` je povolené len pre nulovateľnú property | neexistuje null literál: vynechajte pole, aby použilo null alebo predvolenú hodnotu | | Prázdny reťazec | skutočný reťazec, nie null | skutočný reťazec, nie null | -| Objekt vs zoznam | `{}` je objekt, aj keď mu chýbajú properties. `[]` je zoznam a je zamietnutý všade, kde sa vyžaduje objekt, vrátane prázdneho zoznamu. JSON objekt je zamietnutý tam, kde sa vyžaduje zoznam | názvy so zátvorkami tvoria objekt (`address[street]`); indexované názvy tvoria zoznam (`items[0]`) | +| Objekt vs zoznam | `{}` je objekt (jeho chýbajúce properties sa nahlásia jednotlivo). `[]` je zoznam a je zamietnutý všade, kde sa vyžaduje objekt, vrátane prázdneho zoznamu. JSON objekt je zamietnutý tam, kde sa vyžaduje zoznam | názvy so zátvorkami tvoria objekt (`address[street]`); indexované názvy tvoria zoznam (`items[0]`) | | Súbory | nepodporované | len `multipart/form-data` | Napríklad JSON `"quantity": 2` ostane integer, zatiaľ čo formulárové `quantity=2` sa stane integer až po tom, ako kompletný reťazec prejde striktnou konverziou. Ani jedno neakceptuje `2pcs`. JSON `false` a formulárové `remember=0` sú platné booleany; ľubovoľný neprázdny formulárový reťazec sa potichu nestane `true`. @@ -209,5 +209,5 @@ final readonly class AvatarInput } ``` -`FileUpload` sprístupňuje pôvodný názov, content type od klienta, dočasnú cestu, veľkosť a chybu nahrávania. `?FileUpload` je voliteľný súbor a `list` prijme viac súborov v jednom poli. Handler pred uložením súboru skontroluje chybu nahrávania, veľkosť a skutočný typ; nič sa nepresúva automaticky. `#[File]` je povolený len v koreňovom vstupnom DTO handlera, nie vo vnorenom DTO ani v zozname. +`FileUpload` má properties `originalName`, `clientContentType`, `temporaryPath`, `size` a `error` (PHP kód `UPLOAD_ERR_*`). `?FileUpload` je voliteľný súbor a `list` prijme viac súborov v jednom poli. Handler pred uložením súboru skontroluje chybu nahrávania, veľkosť a skutočný typ; nič sa nepresúva automaticky. `#[File]` je povolený len v koreňovom vstupnom DTO handlera, nie vo vnorenom DTO ani v zozname. diff --git a/docs/sk/guide/typed-input-conversion.md b/docs/sk/guide/typed-input-conversion.md index 703592e45..631e826f7 100644 --- a/docs/sk/guide/typed-input-conversion.md +++ b/docs/sk/guide/typed-input-conversion.md @@ -5,7 +5,7 @@ description: 'Ako typované DTO v Nette API striktne konvertuje hodnoty, spúš # Typovaný vstup: konverzia, castery a validačné obmedzenia -Táto stránka popisuje, čo sa stane s hodnotou medzi požiadavkou a property DTO: striktná konverzia, `#[Cast]` a atribúty validačných obmedzení. Základy sú v stránke [Typovaný vstup (DTO)](/sk/guide/typed-input). +Táto stránka popisuje, čo sa stane s hodnotou medzi požiadavkou a property DTO: striktná konverzia, `#[Cast]` a atribúty validačných obmedzení. Základy sú na stránke [Typovaný vstup (DTO)](/sk/guide/typed-input). ## Striktná konverzia @@ -74,7 +74,7 @@ final class CastException extends RuntimeException } ``` -Castery sú v `Tomaj\NetteApi\Input` vrátane `DateFormat`, `UnixTimestamp` a `Split`. Caster beží **namiesto** vstavanej konverzie pre danú property. Spustí sa ako prvý, vráti deklarovanú hodnotu property a až potom sa na skonvertovanej hodnote spustia `Range`, `Length`, `Pattern`, `Email` a vlastné validačné obmedzenia. Vnorené cesty fungujú presne ako inde. +Castery sú v `Tomaj\NetteApi\Input` vrátane `DateFormat`, `UnixTimestamp` a `Split`. Caster beží **namiesto** vstavanej konverzie pre danú property. Spustí sa ako prvý, vráti deklarovanú hodnotu property a až potom sa na skonvertovanej hodnote spustia `Range`, `Length`, `Pattern`, `Email` a vlastné validačné obmedzenia. Caster hlási neplatný klientsky vstup vyhodením `Tomaj\NetteApi\Input\CastException` so zrozumiteľnou hláškou. Zmení sa na 400 v bežnej chybovej obálke pod cestou property: @@ -88,7 +88,7 @@ Caster hlási neplatný klientsky vstup vyhodením `Tomaj\NetteApi\Input\CastExc } ``` -Každá iná výnimka je chyba servera, nie validačná chyba. Kompilácia kontajnera overí, že caster implementuje `CasterInterface`, akceptuje argumenty atribútu a deklaruje natívny návratový typ `cast()` zhodný s typom property (pre `list` `array` s PHPDoc zoznamu; `mixed` sa neakceptuje). +Každá iná výnimka z castera alebo akákoľvek výnimka z konštruktora vnoreného DTO je chyba servera, nie validačná chyba: error handler na ňu po autorizácii odpovie `500`. Kompilácia kontajnera overí, že caster implementuje `CasterInterface`, akceptuje argumenty atribútu a deklaruje natívny návratový typ `cast()` zhodný s typom property (pre `list` `array` s PHPDoc zoznamu; `mixed` sa neakceptuje). ### Nápovedy OpenAPI schémy @@ -102,7 +102,7 @@ interface OpenApiCasterInterface } ``` -Vrátené `type`, `format` a `example` popisujú **hodnotu na drôte**, nie výsledný PHP objekt. Bez tohto voliteľného rozhrania OpenAPI použije reťazcovú schému a formát môže popísať description/example DTO. Caster nikdy nemení runtime validáciu cez svoju nápovedu schémy. +Vrátené `type`, `format` a `example` popisujú **hodnotu prenášanú v požiadavke**, nie výsledný PHP objekt. Bez tohto voliteľného rozhrania OpenAPI použije reťazcovú schému a formát môže popísať description/example DTO. Caster nikdy nemení runtime validáciu cez svoju nápovedu schémy. ### Vstavané castery a český dátum @@ -110,7 +110,7 @@ Vrátené `type`, `format` a `example` popisujú **hodnotu na drôte**, nie výs | Caster | Príklad vstupu | Výsledok | | --- | --- | --- | -| `#[Cast(DateFormat::class, 'd.m.Y')]` | `'24.12.2026'` | `DateTimeImmutable` o polnoci, odmietne nemožné dátumy a vstup s koncovkou | +| `#[Cast(DateFormat::class, 'd.m.Y')]` | `'24.12.2026'` | `DateTimeImmutable` o polnoci, odmietne nemožné dátumy a nadbytočné znaky na konci | | `#[Cast(UnixTimestamp::class)]` | `1798185600` alebo `'1798185600'` | `DateTimeImmutable` zo sekúnd od Unix epoch | | `#[Cast(Split::class, ',')]` | `'red,green,blue'` | `list` (vždy reťazce: property `list` potrebuje vlastný caster); bez implicitného trimovania alebo odstraňovania prázdnych položiek | diff --git a/docs/sk/guide/typed-input.md b/docs/sk/guide/typed-input.md index deac78716..d477b3952 100644 --- a/docs/sk/guide/typed-input.md +++ b/docs/sk/guide/typed-input.md @@ -9,7 +9,7 @@ Triedy na tejto stránke sú súčasťou Nette API 4.0. Spustiteľný projekt je Typované vstupné DTO drží kontrakt požiadavky pri hodnotách, ktoré handler používa. Atribúty určujú, odkiaľ hodnota pochádza, typy properties určujú jej PHP typ a atribúty validačných obmedzení validáciu. Rovnaká deklarácia napája validáciu, OpenAPI aj API konzolu. -Viac o štýle s DTO: [telo, súbory a content typy](/sk/guide/typed-input-body), [konverzia, castery a validačné obmedzenia](/sk/guide/typed-input-conversion). +Viac o štýle s DTO: [telo, súbory a typy obsahu](/sk/guide/typed-input-body), [konverzia, castery a validačné obmedzenia](/sk/guide/typed-input-conversion). ## params() alebo DTO @@ -26,7 +26,7 @@ Handler deklaruje svoj vstup jedným z dvoch rovnocenných spôsobov. Oba sú pl `params()` zvoľte, keď endpoint spolieha na jeho voľnejšiu konverziu, na vlastný `InputParam` alebo na ručné spracovanie nezvyčajného tela. DTO zvoľte, keď chcete typované hodnoty, vnorené telá, validačné obmedzenia cez viac polí alebo celý kontrakt požiadavky v jednej triede. Ani jeden štýl nie je zastaraný a voľba štýlu pre jeden endpoint neovplyvní žiadny iný. [params() a DTO vedľa seba](/sk/guide/input-styles) ukazuje ten istý endpoint napísaný oboma štýlmi. -`TypedHandler` prevedie deklaráciu DTO na objekty `InputParam`, takže validácia, OpenAPI aj konzola fungujú ako pri `params()`. S DI rozšírením sa tieto metadáta skompilujú do kontajnera a zmena DTO, casteru, validačného obmedzenia alebo enumu ho prebuduje. Konštanta inej triedy použitá v argumente atribútu alebo v predvolenej hodnote sa nesleduje; po jej zmene vymažte cache. Bez rozšírenia sa metadáta zostavia raz za proces. +`TypedHandler` prevedie deklaráciu DTO na objekty `InputParam`, takže validácia, OpenAPI aj konzola fungujú ako pri `params()`. ## Najmenší handler @@ -78,22 +78,20 @@ Atribúty sú v `Tomaj\NetteApi\Input` a cielia na promované properties konštr | Atribút | Zdroj | Typ vygenerovaného parametra | | --- | --- | --- | | `#[Query]` | query string | `InputParam::TYPE_GET`, OpenAPI `in: query` | -| `#[Path]` | nájdená cesta endpointu | `InputParam::TYPE_PATH`, OpenAPI `in: path` | +| `#[Path]` | segment cesty endpointu | `InputParam::TYPE_PATH`, OpenAPI `in: path` | | `#[Header]` | HTTP hlavička | `InputParam::TYPE_HEADER`, OpenAPI `in: header` | | `#[Body]` | pole JSON, formulárového alebo multipart tela | `InputParam::TYPE_BODY`, časť `requestBody` | | `#[File]` | nahraný súbor | `InputParam::TYPE_FILE`, multipart `requestBody` | -Každá property DTO sa stane jedným `MappedInputParam`, teda `InputParam`, ktorý validuje a mapuje cez metadáta DTO. Kód, ktorý skúma `params()`, kontroluje `getType()`, nie konkrétnu triedu. +Každá property koreňového DTO sa stane jedným `MappedInputParam`, teda `InputParam`, ktorý validuje a mapuje cez metadáta DTO. Kód, ktorý skúma `params()`, kontroluje `getType()`, nie konkrétnu triedu. Napríklad `#[Header('X-Request-Id')] public ?string $requestId = null` číta `X-Request-Id`, nie `requestId`. Vyhľadávanie hlavičky nerozlišuje veľkosť písmen. Názov v `#[Path]` začína písmenom alebo podčiarkovníkom a má písmená, číslice a podčiarkovníky, pretože sa píše ako segment `{name}`; názov v `#[Header]` používa pomlčky, nie podčiarkovníky (`X-Request-Id`, nie `X_Request_Id`), pretože PHP sprístupňuje názvy hlavičiek s pomlčkami. Čokoľvek iné je chybou kompilácie s opraveným názvom. Hodnota z cesty alebo hlavičky je jeden reťazec, preto je tam natívny zoznam alebo vnorené DTO chybou kompilácie; rozdeľte ju casterom, napríklad `#[Header('X-Tags')] #[Cast(Split::class, ',')] public array $tags`. `PathInputParam`, `HeaderInputParam` a `BodyInputParam` sú verejné aj pre handlery, ktoré používajú `params()`, pozrite [Vstupné parametre](/sk/guide/params#parametre-path-header-a-body). -`#[Header]` nepoužívajte pre hlavičku, ktorú proxy nastavuje alebo odstraňuje ako nositeľku dôvery, napríklad `X-Forwarded-User`. PHP a webservery mapujú `X_Request_Id` aj `X-Request-Id` na rovnaký názov, takže klient môže poslať podobne vyzerajúcu hlavičku. Takéto hodnoty overte v proxy a kópiu od klienta tam zahoďte. - ### Hodnoty z cesty a šablóny URL -Hodnota z cesty sa deklaruje v URL endpointu ako `{name}`, napríklad `users/{id}/detail`. Je povinná, nemôže byť nulovateľná ani mať predvolenú hodnotu a placeholder v OpenAPI ceste má rovnaký názov. Chýbajúci alebo nedeklarovaný parameter cesty je chybou kompilácie kontajnera. Statické URL endpointov fungujú bez zmeny. Hodnota z cesty je jeden segment URL. Segmenty sa URL-dekódujú až po rozdelení cesty, takže zakódované lomítko ostane v hodnote: `/users/a%2Fb/detail` dá `id` `a/b`. +Hodnota z cesty sa deklaruje v URL endpointu ako `{name}`, napríklad `users/{id}/detail`. Je povinná, nemôže byť nulovateľná ani mať predvolenú hodnotu a placeholder v OpenAPI ceste má rovnaký názov. Segment `{name}` bez property `#[Path]` alebo property `#[Path]`, ktorá v URL chýba, zastaví s DI rozšírením kompiláciu kontajnera; s `addApi()` vyhodí `LogicException` pri prvom nájdení endpointu. Statické URL endpointov fungujú bez zmeny. Hodnota z cesty je jeden segment URL. Segmenty sa URL-dekódujú až po rozdelení cesty, takže zakódované lomítko ostane v hodnote: `/users/a%2Fb/detail` dá `id` `a/b`. Šablónu zaregistrujte ako akciu endpointu niektorým zo zvyčajných spôsobov: @@ -112,13 +110,13 @@ final class UserDetailHandler extends TypedHandler $apiDecider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), new UserDetailHandler(), new NoAuthorization()); ``` -Route musí prepustiť segmenty šablóny. Route z [príkladu typovaného vstupu](/sk/examples/typed-input), `/api/v/[/][/]`, prepustí za akciou jeden segment; hlbšia šablóna ako `{id}/orders/{orderId}` potrebuje v maske route `[/]`, inak Nette odpovie `404` skôr, ako požiadavka dorazí do API. Požiadavka sa hľadá najprv medzi statickými endpointmi a potom medzi šablónami. Ak jednej URL vyhovujú dve šablóny, požiadavka skončí s `LogicException`, ktorá pomenuje obe, takže zmeňte statický segment tak, aby sa líšili. +Routa musí prepustiť segmenty šablóny. Routa z [príkladu typovaného vstupu](/sk/examples/typed-input), `/api/v/[/][/]`, prepustí za akciou jeden segment; hlbšia šablóna ako `{id}/orders/{orderId}` potrebuje v maske routy `[/]`, inak Nette odpovie `404` skôr, ako požiadavka dorazí do API. Požiadavka sa hľadá najprv medzi statickými endpointmi a potom medzi šablónami. Keď má URL za akciou ďalšie segmenty, šablóna, ktorá zodpovedá celej ceste, vyhrá nad kratším statickým endpointom: `/users/7/detail` pôjde na `users/{id}/detail`, nie na statický `users/7`. Dve šablóny, ktoré môžu zodpovedať tej istej URL, zastavia s DI rozšírením kompiláciu kontajnera; s `addApi()` požiadavka vyhodí `LogicException`, ktorá pomenuje obe. Zmeňte statický segment tak, aby sa líšili. ### Povinné hodnoty a predvolené hodnoty Nenulovateľná property bez predvolenej hodnoty je povinná. Nulovateľná property alebo property s predvolenou hodnotou je voliteľná. Chýbajúca nulovateľná hodnota sa stane `null`; chýbajúca hodnota s predvolenou hodnotou použije túto hodnotu. Rovnako sa nastaví `required` v OpenAPI. -Povinné parametre cesty nemôžu byť nulovateľné ani mať predvolenú hodnotu. Voliteľné pole tela akceptuje vynechanie poľa, zatiaľ čo explicitné JSON `null` akceptuje len nulovateľná property. Prázdny reťazec sa potichu nemení na `null`. Predvolená hodnota je `null`, skalár, pole alebo case backed enumu; objekt ako predvolená hodnota, napríklad `= new Inner()`, je chybou kompilácie. Použite `= null` a objekt vytvorte v handleri. +Voliteľné pole tela akceptuje vynechanie poľa, zatiaľ čo explicitné JSON `null` akceptuje len nulovateľná property. Prázdny reťazec sa potichu nemení na `null`. Predvolená hodnota je `null`, skalár, pole alebo case backed enumu; objekt ako predvolená hodnota, napríklad `= new Inner()`, je chybou kompilácie. Použite `= null` a objekt vytvorte v handleri. ## Kompletný príklad požiadavky @@ -155,11 +153,11 @@ X-Request-Id: req-01J8Y7N6R9 Handler dostane `id: 42`, `limit: 10`, `status: UserStatus::Active` a reťazec s ID požiadavky. Nie sú potrebné pretypovania ani prístupy ku kľúčom poľa. -Požiadavka s telom, vnoreným DTO a zoznamom je v stránke [telo, súbory a content typy](/sk/guide/typed-input-body#post-s-vnorenym-dto-a-polom). +Požiadavka s telom, vnoreným DTO a zoznamom je na stránke [telo, súbory a typy obsahu](/sk/guide/typed-input-body#post-s-vnorenym-dto-a-zoznamom). ## Chybové odpovede -Obálka odpovede ostáva rovnaká ako pri `ParamsProcessor`. Kľúč detailu je cesta poľa: bodky vstupujú do vnorených DTO a hranaté zátvorky označujú položky zoznamu. Najvyššie zdroje používajú svoje externé názvy. +Chyby používajú rovnakú obálku ako handlery s `params()`. Kľúč detailu je cesta poľa: bodky vstupujú do vnorených DTO a hranaté zátvorky označujú položky zoznamu. Polia najvyššej úrovne majú kľúč podľa svojho externého názvu. ```json { @@ -174,11 +172,11 @@ Obálka odpovede ostáva rovnaká ako pri `ParamsProcessor`. Kľúč detailu je } ``` -Pri vypnutých detailoch chýb sa vrátia len `status` a `message`. So zapnutými Problem Details sa rovnaké cesty polí a hlášky objavia v jeho rozšírení pre chyby vstupu. Pokazené JSON a nečitateľné telo zachovajú existujúce chyby parsera tela. +Pri vypnutých detailoch chýb sa vrátia len `status` a `message`. So zapnutými Problem Details sa rovnaké cesty polí a hlášky objavia v jeho zozname `errors` ako `parameter` a `detail`. -Chyby tela požiadavky ako celku sa objavia pod `body`; pole nenazývajte `body` (použite `#[Body('payload')]`). +Chyby tela ako celku, napríklad pokazené JSON (`Syntax error`), iný charset než UTF-8 alebo nečitateľné telo, sa objavia pod `body`; pole nenazývajte `body` (použite `#[Body('payload')]`). -Chýbajúci vnorený objekt nahlási cestu vnoreného objektu. Neznáme vstupné polia sa ignorujú, rovnako ako pri bežných query/formulárových parametroch; potichu sa nemapujú na properties. +Chýbajúci vnorený objekt nahlási cestu vnoreného objektu. Neznáme vstupné polia sa ignorujú, rovnako ako pri bežných query a formulárových parametroch. ## OpenAPI a API konzola @@ -210,16 +208,18 @@ parameters: JSON schéma sa tu generuje len ako výstupný formát OpenAPI. Runtime validácia používa rekurzívny mapper DTO a nikdy nevyžaduje JSON schému. -### Dlho bežiace workery - -Hodnoty požiadavky typovaného handlera sa držia v statickom stave celého procesu, ktorý `ApiPresenter::run()` vynuluje na začiatku každej požiadavky, takže workery (RoadRunner, FrankenPHP, Swoole) sú v poriadku, pokiaľ každý spracúva jednu požiadavku naraz; súbežné korutiny v jednom procese podporované nie sú. Kód, ktorý vo workeri volá `params()` typovaného handlera mimo presentera, najprv zavolá `Tomaj\NetteApi\Input\RequestInput::reset()` a `Tomaj\NetteApi\Params\PathValues::reset()`. - ## Bezpečnostné poznámky -- **Mapovanie beží pred autorizáciou.** Vstup sa konvertuje a validuje skôr, ako sa skontroluje autorizácia, a čaká až odpoveď: klient bez prístupu dostane `401`, nie chyby polí. Obmedzenie požiadaviek beží stále ako prvé. Caster alebo validačné obmedzenie je teda dostupné bez prihlásenia, preto ich držte čisté a lacné: žiadny prístup k databáze, sieti ani súborom. Na každý zoznam dajte `#[Length(max: ...)]`. +- **Mapovanie beží pred autorizáciou.** Vstup sa konvertuje a validuje skôr, ako sa skontroluje autorizácia, a na autorizáciu čaká až samotná odpoveď: klient bez prístupu dostane `401`, nie chyby polí. Obmedzenie požiadaviek aj tak beží ako prvé. Caster alebo validačné obmedzenie je teda dostupné bez prihlásenia, preto ich držte čisté a lacné: žiadny prístup k databáze, sieti ani súborom. Na každý zoznam dajte `#[Length(max: ...)]`. - **Veľkosť tela obmedzte na webservery.** `#[Length(max: ...)]` obmedzí zoznam skôr, ako sa jeho položky mapujú, ale telo sa dekóduje ako prvé a dekódovaný zoznam zaberie v PHP mnohonásobne viac pamäte než v požiadavke. Obmedzte veľkosť tam, kde požiadavka vstupuje: `client_max_body_size` v nginx, `LimitRequestBody` v Apache a `post_max_size` s `memory_limit` v PHP. -- **`#[Header]` nie je dôkaz pôvodu.** Pozrite poznámku pod [atribútmi zdroja](#atributy-zdroja). -- **Formuláre a cookies.** DTO s poľami tela predvolene prijíma URL-enkódované formuláre, ktoré môže odoslať ľubovoľný web bez CORS preflightu. Pre endpoint autentifikovaný cookie alebo adresou klienta použite `#[Consumes('application/json')]`, pozrite [telo, súbory a content typy](/sk/guide/typed-input-body#formulare-a-endpointy-autentifikovane-cez-cookie). +- **`#[Header]` nie je dôkaz pôvodu.** Nepoužívajte ho pre hlavičku, ktorú proxy nastavuje alebo odstraňuje ako nositeľku dôvery, napríklad `X-Forwarded-User`. PHP a webservery mapujú `X_Request_Id` aj `X-Request-Id` na rovnaký názov, takže klient môže poslať podobne vyzerajúcu hlavičku. Takéto hodnoty overte v proxy a kópiu od klienta tam zahoďte. +- **Formuláre a cookies.** DTO s poľami tela predvolene prijíma URL-enkódované formuláre, ktoré môže odoslať ľubovoľný web bez CORS preflightu. Pre endpoint autentifikovaný cookie alebo adresou klienta použite `#[Consumes('application/json')]`, pozrite [telo, súbory a typy obsahu](/sk/guide/typed-input-body#formulare-a-endpointy-autentifikovane-cez-cookie). + +## Skompilované metadáta a workery + +S DI rozšírením sa metadáta DTO skompilujú do kontajnera a zmena DTO, casteru, validačného obmedzenia alebo enumu ho prebuduje. Konštanta inej triedy použitá v argumente atribútu alebo v predvolenej hodnote sa nesleduje; po jej zmene vymažte cache. Bez rozšírenia sa metadáta zostavia raz za proces. + +Každé čítanie `params()` typovaného handlera spracuje aktuálnu požiadavku znova a hodnoty z cesty nastaví `ApiDecider` pre každú požiadavku, takže workery (RoadRunner, FrankenPHP, Swoole) sú v poriadku, pokiaľ každý spracúva jednu požiadavku naraz; súbežné korutiny v jednom procese podporované nie sú. ## Príklad diff --git a/docs/sk/index.md b/docs/sk/index.md index 6caccbefd..f5acd18cd 100644 --- a/docs/sk/index.md +++ b/docs/sk/index.md @@ -46,7 +46,7 @@ Handler je jedna trieda. Jej vstup je zoznam parametrov alebo typované DTO, pod <<< @/../examples/hello-world/app/Api/HelloHandler.php [params()] -```php [Typed DTO] +```php [Typované DTO] final readonly class HelloInput { public function __construct( @@ -71,7 +71,7 @@ a niekoľko riadkov konfigurácie ho zaregistruje ako `GET /api/v1/hello`: <<< @/../examples/hello-world/config/common.neon{yaml} -Záložka `params()` je [príklad hello world](/sk/examples/hello-world), ktorý beží v CI; typovaná verzia je `GreetHandler` v [`examples/attributes`](/sk/examples/attributes). +Záložka `params()` je [príklad hello world](/sk/examples/hello-world), ktorý beží v CI; obdobou typovanej verzie je `GreetHandler` v [`examples/attributes`](/sk/examples/attributes). ## Kam ďalej diff --git a/src/ApiDecider.php b/src/ApiDecider.php index 242ce63f5..6071126d5 100644 --- a/src/ApiDecider.php +++ b/src/ApiDecider.php @@ -14,6 +14,7 @@ use Tomaj\NetteApi\Handlers\CorsPreflightHandlerInterface; use Tomaj\NetteApi\Handlers\DefaultHandler; use Tomaj\NetteApi\Handlers\TypedHandler; +use Tomaj\NetteApi\Input\DtoMetadataRegistry; use Tomaj\NetteApi\Input\EndpointTemplate; use Tomaj\NetteApi\Params\InputParam; use Tomaj\NetteApi\Params\PathValues; @@ -232,10 +233,15 @@ private function checkPath(EndpointInterface $endpoint, ApiHandlerInterface $han return; } - $names = []; - foreach ($handler->params() as $param) { - if ($param->getType() === InputParam::TYPE_PATH) { - $names[] = $param->getKey(); + if ($handler instanceof TypedHandler) { + // from the compiled metadata, without building every param and its OpenAPI schema on each request + $names = DtoMetadataRegistry::forHandler($handler::class)->pathNames(); + } else { + $names = []; + foreach ($handler->params() as $param) { + if ($param->getType() === InputParam::TYPE_PATH) { + $names[] = $param->getKey(); + } } } diff --git a/src/Input/DtoMapper.php b/src/Input/DtoMapper.php index f9199fcb2..27353db38 100644 --- a/src/Input/DtoMapper.php +++ b/src/Input/DtoMapper.php @@ -71,7 +71,7 @@ private function evaluate(): void } $this->done = true; - RequestInput::boot($this->metadata->handler, $this->metadata->contentTypes, $this->metadata->bodyRequired, $this->metadata->readsBody); + RequestInput::boot($this->metadata->contentTypes, $this->metadata->bodyRequired, $this->metadata->readsBody); $failure = RequestInput::failure(); $converted = []; foreach ($this->untilTruncated($this->metadata->fields) as $field) { diff --git a/src/Input/RequestInput.php b/src/Input/RequestInput.php index 8f6d23671..683e37705 100644 --- a/src/Input/RequestInput.php +++ b/src/Input/RequestInput.php @@ -9,7 +9,7 @@ use Tomaj\NetteApi\Params\PathValues; /** - * Raw request data for the handler that is running. One read of the body is shared by every field. + * Raw request data of the current request. DtoMapper boots it once per handler params, so every field shares one read of the body. */ final class RequestInput { @@ -18,8 +18,6 @@ final class RequestInput private const string TOO_MANY_FIELDS = 'Too many form fields'; - private static ?string $handler = null; - /** @var array */ private static array $query = []; @@ -37,7 +35,6 @@ final class RequestInput public static function reset(): void { - self::$handler = null; self::$query = []; self::$body = []; self::$files = []; @@ -59,13 +56,8 @@ public static function setRawBody(string $raw): void /** * @param list $consumes */ - public static function boot(string $handler, array $consumes, bool $bodyRequired, bool $readsBody): void + public static function boot(array $consumes, bool $bodyRequired, bool $readsBody): void { - if (self::$handler === $handler) { - return; - } - - self::$handler = null; self::$query = $_GET; self::$body = []; self::$files = []; @@ -74,8 +66,6 @@ public static function boot(string $handler, array $consumes, bool $bodyRequired if ($readsBody) { self::loadBody($consumes, $bodyRequired); } - // only after the body was accepted: a 415 must not leave an empty body behind for the next read - self::$handler = $handler; } public static function failure(): ?string diff --git a/src/Link/ApiLink.php b/src/Link/ApiLink.php index a98fcdfac..a44b801fa 100644 --- a/src/Link/ApiLink.php +++ b/src/Link/ApiLink.php @@ -64,14 +64,18 @@ private function templateLink(EndpointInterface $endpoint, array $params): strin )); } - $path = preg_replace_callback('/\{([A-Za-z_][A-Za-z0-9_]*)\}/', static function (array $match) use (&$params): string { + $path = preg_replace_callback('/\{([A-Za-z_][A-Za-z0-9_]*)\}/', static function (array $match) use (&$params, $endpoint): string { if (!isset($params[$match[1]]) || !is_scalar($params[$match[1]])) { return $match[0]; } - $value = rawurlencode((string) $params[$match[1]]); + $value = (string) $params[$match[1]]; + if (in_array($value, ['', '.', '..'], true)) { + // an empty segment is never matched and a dot segment is resolved away by clients, so the link would lead elsewhere + throw new InvalidLinkException(sprintf("Path value '%s' of %s %s cannot be '%s'.", $match[1], $endpoint->getMethod(), $endpoint->getUrl(), $value)); + } unset($params[$match[1]]); - return $value; + return rawurlencode($value); }, rtrim($endpoint->getUrl(), '/')); $url = substr($sample, 0, $position) . '/' . $path; unset($params['version'], $params['package'], $params['apiAction']); diff --git a/src/Misc/ConsoleRequest.php b/src/Misc/ConsoleRequest.php index 41b753ff1..9fb6c9828 100644 --- a/src/Misc/ConsoleRequest.php +++ b/src/Misc/ConsoleRequest.php @@ -32,10 +32,13 @@ public function makeRequest(string $url, string $method, array $values, array $a [$postFields, $getFields, $cookieFields, $rawPost, $putFields, $pathFields, $headerFields, $bodyFields] = $this->processValues($values); foreach ($pathFields as $name => $value) { - if (trim($value) === '') { - // the request is not sent: the URL would have an empty segment and the server could only answer 404 + if (in_array(trim($value), ['', '.', '..'], true)) { + // the request is not sent: an empty segment cannot match and a dot segment would be resolved to another URL $response = new ConsoleResponse($url, $method, [], [], [], [], null); - $response->logError(0, sprintf("The path value '%s' is empty. Fill it in and send the request again.", $name), 0); + $message = trim($value) === '' + ? sprintf("The path value '%s' is empty. Fill it in and send the request again.", $name) + : sprintf("The path value '%s' cannot be '%s'. Change it and send the request again.", $name, trim($value)); + $response->logError(0, $message, 0); return $response; } diff --git a/src/Params/MappedInputParam.php b/src/Params/MappedInputParam.php index 98a1221b3..74396a9af 100644 --- a/src/Params/MappedInputParam.php +++ b/src/Params/MappedInputParam.php @@ -20,6 +20,9 @@ */ final class MappedInputParam extends InputParam { + /** @var array|null */ + private ?array $schema = null; + public function __construct( private readonly Field $field, private readonly DtoMapper $mapper, @@ -54,12 +57,22 @@ public function __construct( if ($field->listItem !== null && $field->casterClass === null) { $this->setMulti(); } - $this->setOpenApiSchema(SchemaBuilder::build($field, $field->readsBody())); if ($field->readsBody()) { $this->setContentTypes($metadata->contentTypes); } } + /** + * Built on first use: a request only validates, the schema is for OpenAPI and the console. + * + * @return array + */ + #[\Override] + public function getOpenApiSchema(): array + { + return $this->schema ??= parent::getOpenApiSchema() ?? SchemaBuilder::build($this->field, $this->field->readsBody()); + } + #[\Override] public function validate(): ValidationResultInterface { diff --git a/src/Presenters/ApiPresenter.php b/src/Presenters/ApiPresenter.php index 13683c230..d7806b118 100644 --- a/src/Presenters/ApiPresenter.php +++ b/src/Presenters/ApiPresenter.php @@ -324,6 +324,7 @@ public function run(Request $request): IResponse // a body in a media type the typed handler does not accept is answered with 415 after the authorization, // so a client without access learns nothing about the endpoint $unsupportedMediaType = ''; + $paramsFailure = null; $paramsProcessor = null; $params = []; try { @@ -332,6 +333,10 @@ public function run(Request $request): IResponse } catch (UnsupportedMediaTypeException $exception) { $unsupportedMediaType = $exception->getMessage(); $paramsProcessor = null; + } catch (Throwable $throwable) { + // for example the constructor of a nested DTO or a caster; answered by the error handler after the authorization + $paramsFailure = $throwable; + $paramsProcessor = null; } $authResponse = $this->checkAuth($authorization, $params); @@ -351,6 +356,13 @@ public function run(Request $request): IResponse return $rateLimitResponse; } + if ($paramsFailure !== null) { + $response = $this->errorHandler->handle($paramsFailure, $params); + $this->logResponse($request, $response->getCode(), $start, $ip); + $this->response->setCode($response->getCode()); + return $response; + } + if ($paramsProcessor === null) { $response = $this->errorHandler->handleUnsupportedMediaType($unsupportedMediaType); $this->logResponse($request, $response->getCode(), $start, $ip); @@ -424,8 +436,18 @@ private function getApi(Request $request): Api $package = TypeHelper::toString($request->getParameter('package')); $apiAction = $request->getParameter('apiAction') === null ? null : TypeHelper::toString($request->getParameter('apiAction')); + // segments after the action are swallowed by the route's : a static endpoint for the shorter URL must not + // answer them when a URL template matches the whole path, for example users/me/detail with users/{id}/detail + $extraSegments = TypeHelper::toString($request->getParameter('params') ?? '') !== ''; + if ($extraSegments) { + $templated = $this->apiDecider->matchPath($method, $version, $package, $apiAction, $this->requestPath()); + if ($templated !== null) { + return $templated; + } + } + $api = $this->apiDecider->getApi($method, $version, $package, $apiAction); - if ($api->getHandler() instanceof DefaultHandler) { + if (!$extraSegments && $api->getHandler() instanceof DefaultHandler) { // a static endpoint wins; only then are the URL templates of the endpoints tried return $this->apiDecider->matchPath($method, $version, $package, $apiAction, $this->requestPath()) ?? $api; } diff --git a/tests/Input/RequestInputTest.php b/tests/Input/RequestInputTest.php index b5c50c7a8..2b36440e5 100644 --- a/tests/Input/RequestInputTest.php +++ b/tests/Input/RequestInputTest.php @@ -38,7 +38,7 @@ public function testARejectedMediaTypeIsRejectedAgainOnTheNextRead(): void for ($attempt = 1; $attempt <= 2; $attempt++) { try { - RequestInput::boot('Handler', [MediaTypes::JSON], true, true); + RequestInput::boot([MediaTypes::JSON], true, true); $this->fail(sprintf('attempt %d accepted text/plain', $attempt)); } catch (UnsupportedMediaTypeException) { $this->assertNull(RequestInput::mediaType()); @@ -46,28 +46,12 @@ public function testARejectedMediaTypeIsRejectedAgainOnTheNextRead(): void } } - public function testASecondBootOfTheSameHandlerKeepsTheFirstRead(): void + public function testEveryReadOfAHandlersParamsSeesTheCurrentRequest(): void { - $_GET = ['page' => '4']; - $first = $this->payload(new ListUsersHandler()); - $_GET = ['page' => '9']; - $second = $this->payload(new ListUsersHandler()); - $this->assertSame(4, $first['page']); - $this->assertSame(4, $second['page']); + $_GET = ['page' => '2']; + $this->assertSame(2, new ParamsProcessor(new ListUsersHandler()->params())->getValues()['page']); - RequestInput::reset(); - $_GET = ['page' => '9']; - $this->assertSame(9, $this->payload(new ListUsersHandler())['page']); - } - - /** - * @return array - */ - private function payload(object $handler): array - { - $processor = new ParamsProcessor($handler->params()); - $this->assertFalse($processor->isError(), (string) json_encode($processor->getErrors())); - - return $handler->handle($processor->getValues())->getPayload(); + $_GET = ['page' => '5']; + $this->assertSame(5, new ParamsProcessor(new ListUsersHandler()->params())->getValues()['page'], 'a worker or a test must not need RequestInput::reset() between two requests'); } } diff --git a/tests/Link/ApiLinkTest.php b/tests/Link/ApiLinkTest.php index 5247f427b..31f06bad6 100644 --- a/tests/Link/ApiLinkTest.php +++ b/tests/Link/ApiLinkTest.php @@ -4,6 +4,8 @@ namespace Tomaj\NetteApi\Test\Link; +use PHPUnit\Framework\Attributes\DataProvider; +use Nette\Application\UI\InvalidLinkException; use PHPUnit\Framework\TestCase; use Tomaj\NetteApi\EndpointIdentifier; use Tomaj\NetteApi\Test\OpenApi\Fixtures\ApiFixtures; @@ -36,4 +38,22 @@ public function testLinkKeepsASlashInThePackage(): void $link = ApiFixtures::apiLink()->link(new EndpointIdentifier('GET', 1, 'acme/widgets', 'show'), ['q' => 'a b']); $this->assertSame('https://example.com/api/v1/acme/widgets/show?q=a+b', $link); } + + /** + * @return \Iterator + */ + public static function valuesThatLeadElsewhere(): \Iterator + { + yield 'empty' => ['']; + yield 'dot' => ['.']; + yield 'dot dot' => ['..']; + yield 'false' => [false]; + } + + #[DataProvider('valuesThatLeadElsewhere')] + public function testAPathValueThatWouldLeadElsewhereIsRejected(mixed $value): void + { + $this->expectException(InvalidLinkException::class); + ApiFixtures::apiLink()->link(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), ['id' => $value]); + } } diff --git a/tests/Misc/ConsoleRequestTest.php b/tests/Misc/ConsoleRequestTest.php index ef6f566d7..c05eb3f2f 100644 --- a/tests/Misc/ConsoleRequestTest.php +++ b/tests/Misc/ConsoleRequestTest.php @@ -185,6 +185,16 @@ public function link(EndpointInterface $endpoint, $params = []): string $this->assertStringStartsWith('custom:http://127.0.0.1:23523/api/v1/users/create', $request->makeRequest('ignored', 'POST', [])->getUrl()); } + public function testADotPathValueIsNotSentButExplained(): void + { + foreach (['.', '..'] as $dots) { + $response = new ConsoleRequest(new UserDetailHandler())->makeRequest('http://127.0.0.1:23523/api/v1/users/{id}/detail', 'GET', ['id' => $dots]); + + $this->assertTrue($response->isError()); + $this->assertSame(sprintf("The path value 'id' cannot be '%s'. Change it and send the request again.", $dots), $response->getErrorMessage()); + } + } + public function testABlankPathValueIsNotSentButExplained(): void { foreach (['', ' '] as $blank) { diff --git a/tests/Presenters/ApiPresenterUnsupportedMediaTypeTest.php b/tests/Presenters/ApiPresenterUnsupportedMediaTypeTest.php index 79f105af3..e4b1aa2e3 100644 --- a/tests/Presenters/ApiPresenterUnsupportedMediaTypeTest.php +++ b/tests/Presenters/ApiPresenterUnsupportedMediaTypeTest.php @@ -16,6 +16,7 @@ use Tomaj\NetteApi\Authorization\BearerTokenAuthorization; use Tomaj\NetteApi\Authorization\NoAuthorization; use Tomaj\NetteApi\EndpointIdentifier; +use Tomaj\NetteApi\Handlers\AlwaysOkHandler; use Tomaj\NetteApi\Error\DefaultErrorHandler; use Tomaj\NetteApi\Input\RequestInput; use Tomaj\NetteApi\Logger\ApiLoggerInterface; @@ -26,6 +27,8 @@ use Tomaj\NetteApi\Presenters\ApiPresenter; use Tomaj\NetteApi\Response\JsonApiResponse; use Tomaj\NetteApi\Test\Input\Fixtures\CreateOrderHandler; +use Tracy\Debugger; +use Tracy\ILogger; final class ApiPresenterUnsupportedMediaTypeTest extends TestCase { @@ -115,6 +118,41 @@ public function getApi(string $method, string $version, string $package, ?string $this->assertFalse(PathValues::has('id')); } + public function testAFailureWhileReadingTheParamsIsAnsweredAfterTheAuthorization(): void + { + $handler = new class extends AlwaysOkHandler { + public function params(): array + { + throw new \InvalidArgumentException('Unknown currency'); + } + }; + $presenter = $this->presenter(new BearerTokenAuthorization(new StaticTokenRepository(['secret' => '*']), new StaticIpDetector('127.0.0.1'))); + $presenter->apiDecider = new ApiDecider(new Container()); + $presenter->apiDecider->addApi(new EndpointIdentifier('POST', 1, 'orders'), $handler, new BearerTokenAuthorization(new StaticTokenRepository(['secret' => '*']), new StaticIpDetector('127.0.0.1'))); + + $this->assertSame(401, $presenter->run($this->request())->getCode()); + + $_SERVER['HTTP_AUTHORIZATION'] = 'Bearer secret'; + $tracy = new class implements ILogger { + /** @var list */ + public array $logged = []; + + public function log(mixed $value, string $level = self::INFO): void + { + $this->logged[] = $value; + } + }; + $previous = Debugger::getLogger(); + Debugger::setLogger($tracy); + try { + $this->assertSame(500, $presenter->run($this->request())->getCode()); + } finally { + Debugger::setLogger($previous); + } + $this->assertSame([500], $this->logged); + $this->assertInstanceOf(\InvalidArgumentException::class, $tracy->logged[0]); + } + private function request(): Request { return new Request('Api:Api:default', 'POST', ['version' => '1', 'package' => 'orders']); diff --git a/tests/TypedEndpointMatchTest.php b/tests/TypedEndpointMatchTest.php index fe5aa5b22..cc274e278 100644 --- a/tests/TypedEndpointMatchTest.php +++ b/tests/TypedEndpointMatchTest.php @@ -13,6 +13,15 @@ use Tomaj\NetteApi\ApiDecider; use Tomaj\NetteApi\Authorization\NoAuthorization; use Tomaj\NetteApi\EndpointIdentifier; +use Tomaj\NetteApi\Error\DefaultErrorHandler; +use Tomaj\NetteApi\Output\Configurator\DebuggerConfigurator; +use Tomaj\NetteApi\Presenters\ApiPresenter; +use Tomaj\NetteApi\Response\JsonApiResponse; +use Nette\Application\Request; +use Nette\Http\IRequest; +use Nette\Http\Request as HttpRequest; +use Nette\Http\Response as HttpResponse; +use Nette\Http\UrlScript; use Tomaj\NetteApi\Test\Input\Fixtures\UserDetailHandler; use Tomaj\NetteApi\Test\OpenApi\Fixtures\ApiFixtures; @@ -35,6 +44,37 @@ public function testTemplateMatchWinsWhenTheRouteSplitsTheId(): void $this->assertInstanceOf(DefaultHandler::class, $missing->getHandler()); } + public function testAShorterStaticEndpointDoesNotAnswerAPathThatATemplateMatches(): void + { + $decider = new ApiDecider(new Container()); + $decider->addApi(new EndpointIdentifier('GET', 1, 'users', '7'), new AlwaysOkHandler(), new NoAuthorization()); + $decider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), new UserDetailHandler(), new NoAuthorization()); + + $presenter = new ApiPresenter(); + $presenter->apiDecider = $decider; + $presenter->response = new HttpResponse(); + $presenter->outputConfigurator = new DebuggerConfigurator(); + $presenter->errorHandler = new DefaultErrorHandler($presenter->outputConfigurator); + $presenter->context = new class extends Container { + public string $path = ''; + + public function getByType(string $type, bool $throw = true): ?object + { + return $type === IRequest::class ? new HttpRequest(new UrlScript('https://example.com' . $this->path)) : null; + } + }; + + $presenter->context->path = '/api/v1/users/7/detail'; + $response = $presenter->run(new Request('Api:Api:default', 'GET', ['version' => '1', 'package' => 'users', 'apiAction' => '7', 'params' => 'detail'])); + $this->assertInstanceOf(JsonApiResponse::class, $response); + $this->assertSame(7, $response->getPayload()['id']); + + $presenter->context->path = '/api/v1/users/7/other'; + $response = $presenter->run(new Request('Api:Api:default', 'GET', ['version' => '1', 'package' => 'users', 'apiAction' => '7', 'params' => 'other'])); + $this->assertInstanceOf(JsonApiResponse::class, $response); + $this->assertSame(['status' => 'ok'], $response->getPayload(), 'without a matching template the static endpoint still answers, as in 3.x'); + } + public function testGetApiKeepsItsFourArgumentContract(): void { $decider = new ApiDecider(new Container()); From 467fd8c21c3fb9499299f03f8c1473855207564f Mon Sep 17 00:00:00 2001 From: Tomas Majer Date: Sun, 15 Nov 2026 11:49:54 +0100 Subject: [PATCH 4/5] Cover the review fixes for mutation testing 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 Claude-Session: https://claude.ai/code/session_012jrra6bHr2Jmk7hfEjoKsr --- src/Input/DtoMapper.php | 16 +++---- src/Misc/ConsoleRequest.php | 7 +-- src/OpenApi/RequestBodyBuilder.php | 13 +++--- src/Params/MappedInputParam.php | 7 +-- tests/Input/DtoHandlerTest.php | 11 +++++ tests/Link/ApiLinkTest.php | 4 +- tests/Misc/ConsoleRequestTest.php | 4 +- tests/OpenApi/RequestBodyBuilderTest.php | 44 +++++++++++++++++-- tests/Params/PathHeaderBodyParamTest.php | 22 ++++++++++ .../ApiPresenterUnsupportedMediaTypeTest.php | 1 + tests/TypedEndpointMatchTest.php | 16 +++++++ 11 files changed, 115 insertions(+), 30 deletions(-) diff --git a/src/Input/DtoMapper.php b/src/Input/DtoMapper.php index 27353db38..a43000d2a 100644 --- a/src/Input/DtoMapper.php +++ b/src/Input/DtoMapper.php @@ -106,7 +106,7 @@ private function evaluate(): void } /** - * @return array{value: mixed, errors: array>} + * @return array{value: mixed, errors: array{}}|array{errors: non-empty-array>} */ private function convert(Field $field, mixed $raw, string $path): array { @@ -161,7 +161,7 @@ private function convert(Field $field, mixed $raw, string $path): array } /** - * @return array{value: mixed, errors: array>} + * @return array{value: mixed, errors: array{}}|array{errors: non-empty-array>} */ private function object(Field $field, mixed $raw, string $path): array { @@ -194,14 +194,14 @@ private function object(Field $field, mixed $raw, string $path): array } } if ($errors !== []) { - return ['value' => null, 'errors' => $errors]; + return ['errors' => $errors]; } return ['value' => DtoMetadata::construct($field->typeName, $field->children, static fn (Field $child): mixed => $converted[$child->property]), 'errors' => []]; } /** - * @return array{value: mixed, errors: array>} + * @return array{value: mixed, errors: array{}}|array{errors: non-empty-array>} */ private function list(Field $field, Field $item, mixed $raw, string $path): array { @@ -229,14 +229,14 @@ private function list(Field $field, Field $item, mixed $raw, string $path): arra $values[] = $result['value']; } if ($errors !== []) { - return ['value' => null, 'errors' => $errors]; + return ['errors' => $errors]; } return ['value' => $values, 'errors' => []]; } /** - * @return array{value: mixed, errors: array>} + * @return array{value: mixed, errors: array{}}|array{errors: non-empty-array>} */ private function file(Field $field, mixed $raw, string $path): array { @@ -346,13 +346,13 @@ private function untilTruncated(array $items): \Generator } /** - * @return array{value: null, errors: array>} + * @return array{errors: non-empty-array>} */ private function fail(string $path, string $message): array { ++$this->errorCount; - return ['value' => null, 'errors' => [$path => [$message]]]; + return ['errors' => [$path => [$message]]]; } /** diff --git a/src/Misc/ConsoleRequest.php b/src/Misc/ConsoleRequest.php index 9fb6c9828..a75cf3254 100644 --- a/src/Misc/ConsoleRequest.php +++ b/src/Misc/ConsoleRequest.php @@ -32,12 +32,13 @@ public function makeRequest(string $url, string $method, array $values, array $a [$postFields, $getFields, $cookieFields, $rawPost, $putFields, $pathFields, $headerFields, $bodyFields] = $this->processValues($values); foreach ($pathFields as $name => $value) { - if (in_array(trim($value), ['', '.', '..'], true)) { + $trimmed = trim($value); + if (in_array($trimmed, ['', '.', '..'], true)) { // the request is not sent: an empty segment cannot match and a dot segment would be resolved to another URL $response = new ConsoleResponse($url, $method, [], [], [], [], null); - $message = trim($value) === '' + $message = $trimmed === '' ? sprintf("The path value '%s' is empty. Fill it in and send the request again.", $name) - : sprintf("The path value '%s' cannot be '%s'. Change it and send the request again.", $name, trim($value)); + : sprintf("The path value '%s' cannot be '%s'. Change it and send the request again.", $name, $trimmed); $response->logError(0, $message, 0); return $response; diff --git a/src/OpenApi/RequestBodyBuilder.php b/src/OpenApi/RequestBodyBuilder.php index 38d820bb7..4c791588e 100644 --- a/src/OpenApi/RequestBodyBuilder.php +++ b/src/OpenApi/RequestBodyBuilder.php @@ -159,7 +159,7 @@ public function build(ApiHandlerInterface $handler, SchemaRegistry $schemaRegist // OpenAPI 3.0 cannot describe a list of objects (or deeper nesting) in a form body, so such a body is documented // as JSON only, unless no other media type is left if (!$this->formDescribable($typedProperties)) { - $describable = array_values(array_diff($advertised, [MediaTypes::FORM, MediaTypes::MULTIPART])); + $describable = array_diff($advertised, [MediaTypes::FORM, MediaTypes::MULTIPART]); $advertised = $describable !== [] ? $describable : $advertised; } foreach ($advertised as $contentType) { @@ -227,8 +227,7 @@ private function objectSchema(array $properties, array $required): array if ($properties !== []) { $schema['properties'] = $properties; } - // only properties that are listed can be required (a file is never listed outside multipart, and then it is not required) - $required = array_values(array_intersect($required, array_keys($properties))); + // every required property is listed: a required file means only multipart is advertised, and multipart lists files if ($required !== []) { $schema['required'] = $required; } @@ -326,11 +325,9 @@ private static function isComposite(array $schema): bool */ private static function withoutNull(array $schema): array { - if (($schema['nullable'] ?? false) === true) { - unset($schema['nullable']); - if (isset($schema['enum']) && is_array($schema['enum'])) { - $schema['enum'] = array_values(array_filter($schema['enum'], static fn (mixed $value): bool => $value !== null)); - } + unset($schema['nullable']); + if (isset($schema['enum']) && is_array($schema['enum'])) { + $schema['enum'] = array_values(array_filter($schema['enum'], static fn (mixed $value): bool => $value !== null)); } if (isset($schema['properties']) && is_array($schema['properties'])) { foreach ($schema['properties'] as $name => $child) { diff --git a/src/Params/MappedInputParam.php b/src/Params/MappedInputParam.php index 74396a9af..3a54410fe 100644 --- a/src/Params/MappedInputParam.php +++ b/src/Params/MappedInputParam.php @@ -20,9 +20,6 @@ */ final class MappedInputParam extends InputParam { - /** @var array|null */ - private ?array $schema = null; - public function __construct( private readonly Field $field, private readonly DtoMapper $mapper, @@ -63,14 +60,14 @@ public function __construct( } /** - * Built on first use: a request only validates, the schema is for OpenAPI and the console. + * Built on use: a request only validates, the schema is for OpenAPI and the console. A schema set explicitly wins. * * @return array */ #[\Override] public function getOpenApiSchema(): array { - return $this->schema ??= parent::getOpenApiSchema() ?? SchemaBuilder::build($this->field, $this->field->readsBody()); + return parent::getOpenApiSchema() ?? SchemaBuilder::build($this->field, $this->field->readsBody()); } #[\Override] diff --git a/tests/Input/DtoHandlerTest.php b/tests/Input/DtoHandlerTest.php index 8a2f3a579..3d6b9e02a 100644 --- a/tests/Input/DtoHandlerTest.php +++ b/tests/Input/DtoHandlerTest.php @@ -7,6 +7,7 @@ use PHPUnit\Framework\TestCase; use Tomaj\NetteApi\Input\RequestInput; use Tomaj\NetteApi\Input\UnsupportedMediaTypeException; +use Tomaj\NetteApi\Params\InputParam; use Tomaj\NetteApi\Params\ParamsProcessor; use Tomaj\NetteApi\Params\PathValues; use Tomaj\NetteApi\Test\Input\Fixtures\AvatarHandler; @@ -561,6 +562,16 @@ public function testListOfEnumsOffersTheItemValues(): void $params = DtoMetadataRegistry::forHandler(PriorityQueryListHandler::class)->inputParams(); $this->assertSame([1 => 1, 2 => 2], $params[0]->getAvailableValues()); } + + public function testAnExplicitSchemaOfAGeneratedParamWins(): void + { + $param = new ListUsersHandler()->params()[0]; + $this->assertInstanceOf(InputParam::class, $param); + $this->assertSame('integer', $param->getOpenApiSchema()['type'] ?? null); + + $param->setOpenApiSchema(['type' => 'string', 'format' => 'custom']); + $this->assertSame(['type' => 'string', 'format' => 'custom'], $param->getOpenApiSchema()); + } } final readonly class DateInput diff --git a/tests/Link/ApiLinkTest.php b/tests/Link/ApiLinkTest.php index 31f06bad6..bf47dfd1d 100644 --- a/tests/Link/ApiLinkTest.php +++ b/tests/Link/ApiLinkTest.php @@ -53,7 +53,9 @@ public static function valuesThatLeadElsewhere(): \Iterator #[DataProvider('valuesThatLeadElsewhere')] public function testAPathValueThatWouldLeadElsewhereIsRejected(mixed $value): void { + $endpoint = new EndpointIdentifier('GET', 1, 'users', '{id}/detail'); $this->expectException(InvalidLinkException::class); - ApiFixtures::apiLink()->link(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), ['id' => $value]); + $this->expectExceptionMessage(sprintf("Path value 'id' of GET %s cannot be '%s'.", $endpoint->getUrl(), is_scalar($value) ? (string) $value : '')); + ApiFixtures::apiLink()->link($endpoint, ['id' => $value]); } } diff --git a/tests/Misc/ConsoleRequestTest.php b/tests/Misc/ConsoleRequestTest.php index c05eb3f2f..c8f308e26 100644 --- a/tests/Misc/ConsoleRequestTest.php +++ b/tests/Misc/ConsoleRequestTest.php @@ -187,8 +187,8 @@ public function link(EndpointInterface $endpoint, $params = []): string public function testADotPathValueIsNotSentButExplained(): void { - foreach (['.', '..'] as $dots) { - $response = new ConsoleRequest(new UserDetailHandler())->makeRequest('http://127.0.0.1:23523/api/v1/users/{id}/detail', 'GET', ['id' => $dots]); + foreach (['.' => '.', '..' => '..', ' .. ' => '..'] as $value => $dots) { + $response = new ConsoleRequest(new UserDetailHandler())->makeRequest('http://127.0.0.1:23523/api/v1/users/{id}/detail', 'GET', ['id' => (string) $value]); $this->assertTrue($response->isError()); $this->assertSame(sprintf("The path value 'id' cannot be '%s'. Change it and send the request again.", $dots), $response->getErrorMessage()); diff --git a/tests/OpenApi/RequestBodyBuilderTest.php b/tests/OpenApi/RequestBodyBuilderTest.php index 0df23e322..5e1b358ba 100644 --- a/tests/OpenApi/RequestBodyBuilderTest.php +++ b/tests/OpenApi/RequestBodyBuilderTest.php @@ -210,9 +210,9 @@ public function testFormSchemaNamesListsEncodesObjectsAndDropsNull(): void ]; $types = ['application/json', 'application/x-www-form-urlencoded', 'multipart/form-data']; $body = new RequestBodyBuilder()->build(new ConfigurableHandler([ - new BodyInputParam('tags')->setRequired()->setOpenApiSchema(['type' => 'array', 'items' => ['type' => 'string']])->setContentTypes($types), + new BodyInputParam('tags')->setRequired()->setOpenApiSchema(['type' => 'array', 'items' => ['type' => 'string', 'nullable' => true]])->setContentTypes($types), new BodyInputParam('address')->setOpenApiSchema($address)->setContentTypes($types), - new BodyInputParam('status')->setOpenApiSchema(['type' => 'string', 'enum' => ['a', null], 'nullable' => true])->setContentTypes($types), + new BodyInputParam('status')->setOpenApiSchema(['type' => 'string', 'enum' => [null, 'a', 'b'], 'nullable' => true])->setContentTypes($types), ]), new SchemaRegistry()); $this->assertIsArray($body); @@ -227,7 +227,7 @@ public function testFormSchemaNamesListsEncodesObjectsAndDropsNull(): void 'properties' => [ 'tags[]' => ['type' => 'array', 'items' => ['type' => 'string']], 'address' => ['type' => 'object', 'properties' => ['street' => ['type' => 'string']], 'required' => ['street']], - 'status' => ['type' => 'string', 'enum' => ['a']], + 'status' => ['type' => 'string', 'enum' => ['a', 'b']], ], 'required' => ['tags[]'], ], @@ -236,6 +236,44 @@ public function testFormSchemaNamesListsEncodesObjectsAndDropsNull(): void } } + public function testBodyParamsJoinTheFormOfPostParams(): void + { + $body = new RequestBodyBuilder()->build(new ConfigurableHandler([ + new PostInputParam('name')->setRequired(), + new PostInputParam('note')->setRequired(), + new BodyInputParam('name')->setRequired(), + new BodyInputParam('age')->setRequired(), + new BodyInputParam('city')->setRequired(), + ]), new SchemaRegistry()); + + $this->assertIsArray($body); + $this->assertSame(['type' => 'object', 'properties' => ['name' => ['type' => 'string'], 'note' => ['type' => 'string'], 'age' => ['type' => 'string'], 'city' => ['type' => 'string']], 'required' => ['name', 'note', 'age', 'city']], $body['content']['application/x-www-form-urlencoded']['schema']); + } + + public function testOptionalBodyParamsKeepTheBodyOfPostParamsRequired(): void + { + $body = new RequestBodyBuilder()->build(new ConfigurableHandler([ + new PostInputParam('note'), + new BodyInputParam('name'), + ]), new SchemaRegistry()); + + $this->assertIsArray($body); + $this->assertTrue($body['required']); + } + + public function testBodyParamWithLabelsOnlyDescribesLabelsThatDifferFromValues(): void + { + $body = new RequestBodyBuilder()->build(new ConfigurableHandler([ + new BodyInputParam('same')->setAvailableValues(['a' => 'a', 'b' => 'b']), + new BodyInputParam('labelled')->setAvailableValues(['a' => 'Tag A']), + ]), new SchemaRegistry()); + + $this->assertIsArray($body); + $properties = $body['content']['application/json']['schema']['properties']; + $this->assertSame(['type' => 'string', 'enum' => ['a', 'b']], $properties['same']); + $this->assertSame(['type' => 'string', 'enum' => ['a'], 'description' => ' * `a` - Tag A'], $properties['labelled']); + } + public function testListOfObjectsIsDocumentedOnlyAsJson(): void { $items = ['type' => 'array', 'items' => ['type' => 'object', 'properties' => ['sku' => ['type' => 'string']]]]; diff --git a/tests/Params/PathHeaderBodyParamTest.php b/tests/Params/PathHeaderBodyParamTest.php index d05c69ffd..5bba19f55 100644 --- a/tests/Params/PathHeaderBodyParamTest.php +++ b/tests/Params/PathHeaderBodyParamTest.php @@ -86,6 +86,28 @@ public function testBodyReadsAPutFormAndTheContentTypeHeaderLikeTypedHandlers(): $this->assertSame('Ken', new BodyInputParam('name')->getValue()); } + public function testBodyReadsAnyFieldOfAForm(): void + { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; + $_POST = ['name' => 'Ada', 'role' => 'admin']; + $this->assertSame('admin', new BodyInputParam('role')->getValue()); + + $_SERVER['REQUEST_METHOD'] = 'PUT'; + $_POST = []; + RequestInput::setRawBody('name=Linus&role=maintainer'); + $this->assertSame('maintainer', new BodyInputParam('role')->getValue()); + } + + public function testAPostFormIsReadFromPostOnly(): void + { + // PHP already parsed a POST body into $_POST, an empty one is not parsed again from the raw body + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; + RequestInput::setRawBody('name=Linus'); + $this->assertSame('none', new BodyInputParam('name')->setDefault('none')->getValue()); + } + public function testSchemaAndContentTypesRoundTrip(): void { $param = new BodyInputParam('name') diff --git a/tests/Presenters/ApiPresenterUnsupportedMediaTypeTest.php b/tests/Presenters/ApiPresenterUnsupportedMediaTypeTest.php index e4b1aa2e3..44e25a455 100644 --- a/tests/Presenters/ApiPresenterUnsupportedMediaTypeTest.php +++ b/tests/Presenters/ApiPresenterUnsupportedMediaTypeTest.php @@ -149,6 +149,7 @@ public function log(mixed $value, string $level = self::INFO): void } finally { Debugger::setLogger($previous); } + $this->assertSame(500, $presenter->response->getCode()); $this->assertSame([500], $this->logged); $this->assertInstanceOf(\InvalidArgumentException::class, $tracy->logged[0]); } diff --git a/tests/TypedEndpointMatchTest.php b/tests/TypedEndpointMatchTest.php index cc274e278..53f1efd87 100644 --- a/tests/TypedEndpointMatchTest.php +++ b/tests/TypedEndpointMatchTest.php @@ -15,6 +15,7 @@ use Tomaj\NetteApi\EndpointIdentifier; use Tomaj\NetteApi\Error\DefaultErrorHandler; use Tomaj\NetteApi\Output\Configurator\DebuggerConfigurator; +use Tomaj\NetteApi\Params\PathInputParam; use Tomaj\NetteApi\Presenters\ApiPresenter; use Tomaj\NetteApi\Response\JsonApiResponse; use Nette\Application\Request; @@ -44,6 +45,21 @@ public function testTemplateMatchWinsWhenTheRouteSplitsTheId(): void $this->assertInstanceOf(DefaultHandler::class, $missing->getHandler()); } + public function testAPlainHandlerWithAPathParamMatchesATemplate(): void + { + $handler = new class extends AlwaysOkHandler { + public function params(): array + { + return [new PathInputParam('id')]; + } + }; + $decider = new ApiDecider(new Container()); + $decider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), $handler, new NoAuthorization()); + + $matched = self::resolve($decider, 'GET', '1', 'users', '42', '/api/v1/users/42/detail'); + $this->assertSame($handler, $matched->getHandler()); + } + public function testAShorterStaticEndpointDoesNotAnswerAPathThatATemplateMatches(): void { $decider = new ApiDecider(new Container()); From 191400a0ccb0bc1caffe2722f94132cbea01ac03 Mon Sep 17 00:00:00 2001 From: Tomas Majer Date: Sun, 15 Nov 2026 19:02:47 +0100 Subject: [PATCH 5/5] Third review pass for typed input DTOs 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 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 Claude-Session: https://claude.ai/code/session_012jrra6bHr2Jmk7hfEjoKsr --- CHANGELOG.md | 2 +- UPGRADE-4.0.md | 3 +- docs/examples/openapi-console.md | 2 +- docs/guide/api-decider.md | 2 +- docs/guide/console.md | 2 +- docs/guide/links.md | 2 +- docs/guide/params.md | 2 +- docs/guide/typed-input-body.md | 8 +- docs/guide/typed-input.md | 6 +- docs/sk/examples/openapi-console.md | 2 +- docs/sk/guide/api-decider.md | 2 +- docs/sk/guide/console.md | 2 +- docs/sk/guide/links.md | 2 +- docs/sk/guide/params.md | 2 +- docs/sk/guide/typed-input-body.md | 8 +- docs/sk/guide/typed-input.md | 6 +- .../app/Api/BookDetailHandler.php | 47 +++++++ examples/openapi-console/config/common.neon | 3 + examples/openapi-console/e2e.sh | 17 ++- src/ApiDecider.php | 98 +++++++------ src/Handlers/BaseHandler.php | 10 +- src/Input/DtoCompiler.php | 73 ++++++++-- src/Input/DtoMapper.php | 22 ++- src/Input/DtoMetadataRegistry.php | 20 --- src/Input/EndpointTemplate.php | 76 +++++----- src/Input/RequestInput.php | 77 ++++++++-- src/Input/TypeName.php | 44 +++++- src/Input/UnsupportedMediaTypeException.php | 11 +- src/Link/ApiLink.php | 50 +++---- src/Misc/ConsoleRequest.php | 40 ++---- src/OpenApi/RequestBodyBuilder.php | 15 +- src/Params/BodyInputParam.php | 40 +++--- src/Params/HeaderBag.php | 20 +++ src/Params/ParamsProcessor.php | 2 +- src/Presenters/ApiPresenter.php | 46 +++--- src/ValidationResult/FieldErrors.php | 8 -- tests/ApiDeciderTest.php | 66 ++++++++- tests/DI/TypedInputExtensionTest.php | 24 ++-- tests/Handler/DefaultHandlerTest.php | 12 ++ tests/Input/BodyParsingTest.php | 52 ++++++- tests/Input/CasterTest.php | 57 +++++++- tests/Input/DtoHandlerTest.php | 18 ++- tests/Input/DtoMetadataTest.php | 9 +- tests/Input/DtoPhpDocTest.php | 21 +++ tests/Input/DtoPropertyTypeTest.php | 32 +++++ tests/Input/EndpointTemplateTest.php | 40 ++++-- tests/Input/FileUploadTest.php | 21 ++- .../Dependency/DependencyDefaults.php | 10 ++ .../Fixtures/Dependency/DependencyInput.php | 6 + .../Fixtures/Dependency/DependencyLabels.php | 10 ++ .../Fixtures/Dependency/DependencyLimits.php | 10 ++ .../Dependency/DependencyParentInput.php | 2 + .../Fixtures/Dependency/DependencyTrait.php | 4 +- .../Fixtures/Dependency/DependencyUnused.php | 16 +++ .../TraitFixtures/Casters/ItemsCaster.php | 13 ++ tests/Input/TraitFixtures/Items/LineItem.php | 14 ++ tests/Input/TraitFixtures/Lib/CastsItems.php | 18 +++ .../Input/TraitFixtures/Lib/NestedFields.php | 11 ++ tests/Input/TraitFixtures/Lib/OrderFields.php | 18 +++ tests/Input/TraitFixtures/Lib/TagFields.php | 17 +++ tests/Input/TraitFixtures/TraitHandlers.php | 85 ++++++++++++ tests/Input/TypeNameTest.php | 19 +++ tests/Link/ApiLinkTest.php | 31 ++++- tests/Misc/ConsoleRequestTest.php | 12 +- tests/OpenApi/RequestBodyBuilderTest.php | 23 ++- tests/Params/PathHeaderBodyParamTest.php | 120 +++++++++++++++- .../ApiPresenterUnsupportedMediaTypeTest.php | 8 +- tests/TypedEndpointMatchTest.php | 131 +++++++++++++++--- 68 files changed, 1335 insertions(+), 367 deletions(-) create mode 100644 examples/openapi-console/app/Api/BookDetailHandler.php create mode 100644 tests/Input/Fixtures/Dependency/DependencyDefaults.php create mode 100644 tests/Input/Fixtures/Dependency/DependencyLabels.php create mode 100644 tests/Input/Fixtures/Dependency/DependencyLimits.php create mode 100644 tests/Input/Fixtures/Dependency/DependencyUnused.php create mode 100644 tests/Input/TraitFixtures/Casters/ItemsCaster.php create mode 100644 tests/Input/TraitFixtures/Items/LineItem.php create mode 100644 tests/Input/TraitFixtures/Lib/CastsItems.php create mode 100644 tests/Input/TraitFixtures/Lib/NestedFields.php create mode 100644 tests/Input/TraitFixtures/Lib/OrderFields.php create mode 100644 tests/Input/TraitFixtures/Lib/TagFields.php create mode 100644 tests/Input/TraitFixtures/TraitHandlers.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 24fbcb8c5..34f19336b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,7 +66,7 @@ Planned for 4.0, developed on `master`. 3.x is maintained on the `3.x` branch. * Strict conversion of scalars, backed enums, `DateTimeImmutable` (RFC 3339) and `list`; `#[Cast]` with `CasterInterface` (`DateFormat`, `UnixTimestamp` and `Split` built in); constraints `Range`, `Length`, `Pattern`, `Email` and own `ConstraintInterface`. * Nested DTOs and lists for JSON, form and multipart bodies, with errors reported as `items[1].quantity` in the existing envelope and in Problem Details. * `#[Consumes]` limits the body media types; any other one is a `415`. - * For typed handlers, strings must be valid UTF-8, a JSON body that names another charset is a `400`, and so are a multipart body sent with `PUT` or `PATCH` and a form with more fields than `max_input_vars`. + * For typed handlers, strings must be valid UTF-8, a JSON body that names another charset is a `400`, and so are a multipart body sent with `PUT` or `PATCH` and a form with more fields than `max_input_vars` (a multipart form that reaches the limit, as PHP gives no way to count it again). `BodyInputParam` in `params()` reads the body the same way. ### Changed * Dev tools: PHPUnit ^12 || ^13, PHPStan ^2.1 (level max, no baseline), Rector ^2.2, PHP_CodeSniffer ^4.0, Infection; `symfony/yaml` ^7.4.12 || ^8.0.12. diff --git a/UPGRADE-4.0.md b/UPGRADE-4.0.md index 3f9f2d635..cfc8c9c0d 100644 --- a/UPGRADE-4.0.md +++ b/UPGRADE-4.0.md @@ -80,8 +80,9 @@ new BearerTokenAuthorization(new StaticTokenRepository(['token' => '*']), $ipDet * `ParamType` has new cases `Path`, `Header` and `Body`. An exhaustive `match` on `ParamType` without a `default` arm throws `UnhandledMatchError` for them. * `InputParam` has new public methods `setOpenApiSchema()`, `getOpenApiSchema()`, `setContentTypes()` and `getContentTypes()`. A subclass with a method of the same name must match their signatures. +* An own `InputParam` subclass whose `$type` is `'PATH'`, `'HEADER'` or `'BODY'` is now treated as the new `PathInputParam`, `HeaderInputParam` or `BodyInputParam`: OpenAPI lists it `in: path`, `in: header` or in the request body, and the console sends it there. Rename such a type, for example to `'CUSTOM_HEADER'`, to keep the 3.x behaviour. -`ApiDecider::getApi()` and `ApiLink::link()` keep their signatures; endpoints with `{name}` segments are found by the new `ApiDecider::matchPath()`, which `ApiPresenter` calls when `getApi()` returns no static endpoint, and first when the URL has segments after the action. An own presenter that should serve URL templates calls `matchPath()` the same way. +`ApiDecider::getApi()` and `ApiLink::link()` keep their signatures; endpoints with `{name}` segments are found by the new `ApiDecider::matchPath($method, $version, $package, $apiAction, $params)` from the values of the route, where `$params` are the segments after the action. `ApiPresenter` calls it when `getApi()` returns no static endpoint, and first when the URL has segments after the action. An own presenter that should serve URL templates calls `matchPath()` the same way; `getApi()` returns a template only for its literal URL, such as `{id}/detail`, which the presenter must not treat as a match of a request. ## Stricter types diff --git a/docs/examples/openapi-console.md b/docs/examples/openapi-console.md index 8a2bbdd05..e11601bdf 100644 --- a/docs/examples/openapi-console.md +++ b/docs/examples/openapi-console.md @@ -25,7 +25,7 @@ Summary, description, tags, params and outputs all end up in the OpenAPI documen <<< @/../examples/openapi-console/app/UI/Console/ConsolePresenter.php -The `default` view (`default.latte`) renders the endpoint list. Clicking an endpoint redirects to `actionShow`, which renders `show.latte` with the console form for that one endpoint. +The `default` view (`default.latte`) renders the endpoint list. Clicking an endpoint redirects to `actionShow`, which renders `show.latte` with the console form for that one endpoint. `GET /api/v1/books/{id}` has a URL template: the form asks for `id` and the console puts it into the URL. <<< @/../examples/openapi-console/app/UI/Console/default.latte diff --git a/docs/guide/api-decider.md b/docs/guide/api-decider.md index 7961d9234..51c10f25d 100644 --- a/docs/guide/api-decider.md +++ b/docs/guide/api-decider.md @@ -59,7 +59,7 @@ The 4th argument is the rate limit, `null` means none. Left out, an autowired `R ### Endpoints with {name} segments -An endpoint whose action has `{name}` segments, such as `users/{id}/detail`, needs the path of the request. `ApiPresenter` calls `getApi()` first, and when that finds nothing it calls `matchPath($method, $version, $package, $apiAction, $path)`, so a static endpoint wins for the same URL. When the URL has segments after the action, `ApiPresenter` tries `matchPath()` first: a template that matches the whole path, such as `users/{id}/detail` for `/users/7/detail`, wins over a shorter static endpoint `users/7`. `matchPath()` compares the path with every template of the method and version, stores the matched values for the `#[Path]` properties and returns the `Api`, or `null` when no template matches. When two templates match one path it throws a `LogicException` that lists them; with the DI extension such templates already fail the container compilation. Make a static segment differ. A global preflight also answers `OPTIONS` for a path that matches a template. How to register and route one is in [Typed input](/guide/typed-input#path-values-and-url-templates). +An endpoint whose action has `{name}` segments, such as `users/{id}/detail`, is matched by `matchPath($method, $version, $package, $apiAction, $params)`, which takes the values the router parsed; `$params` are the segments after the action (the `` of the route). `ApiPresenter` calls `getApi()` first, and when that finds nothing it calls `matchPath()`, so a static endpoint wins for the same URL. When the URL has segments after the action, `ApiPresenter` tries `matchPath()` first: a template that matches the whole path, such as `users/{id}/detail` for `/users/7/detail`, wins over a shorter static endpoint `users/7`. `matchPath()` compares the path with every template of the method and version, stores the matched values for the path params and returns the `Api`, or `null` when no template matches. `getApi()` finds a template only by its literal URL, for example `getApi('GET', '1', 'users', '{id}/detail')`, which is how the API console opens it. `addApi()` throws a `LogicException` for a malformed `{name}` segment and for two templates that can match one path, and lists them; with the DI extension such templates already fail the container compilation. Make a static segment differ. A global preflight also answers `OPTIONS` for a path that matches a template. How to register and route one is in [Typed input](/guide/typed-input#path-values-and-url-templates). `GET /api/v1/users` and `POST /api/v1/users` are two endpoints with two handlers. A version that is not registered, such as `/api/v3/users`, is a `404`, as the [versions example](/examples/versions) tests. diff --git a/docs/guide/console.md b/docs/guide/console.md index cbd873f35..145232f45 100644 --- a/docs/guide/console.md +++ b/docs/guide/console.md @@ -37,7 +37,7 @@ The console builds the request from the params of the handler, whether they come | Param source | Sent as | | --- | --- | | query | the query string | -| path value | URL-encoded into the `{name}` segment of the URL | +| path value | trimmed and URL-encoded into the `{name}` segment of the URL; an empty value, `.`, `..` or a value with a slash is not sent | | header value | a request header | | body field | the first media type the handler reads that the console can build: JSON, a URL-encoded form or multipart | | file | a multipart upload; with a file attached the body fields go in the same multipart request | diff --git a/docs/guide/links.md b/docs/guide/links.md index 5e6efb79b..b6040b8a7 100644 --- a/docs/guide/links.md +++ b/docs/guide/links.md @@ -15,7 +15,7 @@ $url = $apiLink->link(new EndpointIdentifier('GET', 1, 'users', 'detail'), ['id' It needs a route to `Api:Api:default` with `version`, `package` and `apiAction` parameters, as in [Getting started](/guide/getting-started). -For an endpoint whose URL has `{name}` segments, such as `{id}/detail`, `link()` fills each segment from the parameter of the same name (URL-encoded); the other parameters go to the query string. A segment without a value stays literal, which is the OpenAPI path template. A path value `''`, `'.'` or `'..'` throws `Nette\Application\UI\InvalidLinkException`, because such a segment would never match or would be resolved to another URL: +For an endpoint whose URL has `{name}` segments, such as `{id}/detail`, `link()` fills each segment from the parameter of the same name (URL-encoded); the other parameters go to the query string. A segment without a value stays literal, which is the OpenAPI path template. A path value `''`, `'.'`, `'..'` or one with a slash throws `Nette\Application\UI\InvalidLinkException`, because such a segment would never match or would lead to another URL. `BaseHandler::createLink()` fills the segments the same way. The route mask must have `` and `` as path segments: ```php $url = $apiLink->link(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), ['id' => 42, 'limit' => 5]); diff --git a/docs/guide/params.md b/docs/guide/params.md index bf746cb1c..78be22b0c 100644 --- a/docs/guide/params.md +++ b/docs/guide/params.md @@ -63,7 +63,7 @@ In 3.x `?limit=abc` with `INTEGER` is not an error: the value is converted to `n ## Path, header and body params -`PathInputParam` reads a value from the endpoint URL. Declare the placeholder in the endpoint action with `{name}`, for example `users/{id}/detail`, as described in [Typed input](/guide/typed-input#path-values-and-url-templates). The param is always required and its OpenAPI placeholder has the same name. `HeaderInputParam` reads a request header, case-insensitively. `BodyInputParam` reads one field of a JSON object, a URL-encoded form or a multipart body, and `setContentTypes()` sets the media types documented in OpenAPI and used by the console; they are not enforced, so a `params()` handler never answers `415`. In a typed DTO, `#[Path]`, `#[Header]` and `#[Body]` properties become `MappedInputParam` objects with the type `TYPE_PATH`, `TYPE_HEADER` or `TYPE_BODY`; `params()` declares these classes directly: +`PathInputParam` reads a value from the endpoint URL. Declare the placeholder in the endpoint action with `{name}`, for example `users/{id}/detail`, as described in [Typed input](/guide/typed-input#path-values-and-url-templates). The param is always required and its OpenAPI placeholder has the same name. `HeaderInputParam` reads a request header, case-insensitively. `BodyInputParam` reads one field of a JSON object, a URL-encoded form or a multipart body, and `setContentTypes()` sets the accepted media types, which OpenAPI documents and the console uses (JSON, form and multipart by default). The body is read like a typed handler reads it: malformed JSON or another charset is a `400` error of the param, a body of another media type is a `415`, and an explicit JSON `null` stays `null` instead of taking the default. In a typed DTO, `#[Path]`, `#[Header]` and `#[Body]` properties become `MappedInputParam` objects with the type `TYPE_PATH`, `TYPE_HEADER` or `TYPE_BODY`; `params()` declares these classes directly: ```php public function params(): array diff --git a/docs/guide/typed-input-body.md b/docs/guide/typed-input-body.md index 132e3fe04..eb8a9427f 100644 --- a/docs/guide/typed-input-body.md +++ b/docs/guide/typed-input-body.md @@ -108,7 +108,7 @@ requestBody: deliveryAt: {type: string, format: date-time, nullable: true} ``` -The endpoint accepts a form too, but OpenAPI 3.0 cannot describe a list of objects in a form body, so only JSON is listed here. A DTO whose body has only scalars, lists of scalars and objects of scalars lists both media types; the form schema names a list `tags[]` and sends an object as `deepObject`: +The endpoint accepts a form too, but OpenAPI 3.0 cannot describe a list of objects in a form body, so only JSON is listed here. A DTO that also has a `#[File]` keeps `multipart/form-data`, because a file cannot be sent otherwise; its multipart schema lists such a field by its plain name and says in its description that it is sent in bracket notation (`items[0][sku]`). A DTO whose body has only scalars, lists of scalars and objects of scalars lists both media types; the form schema names a list `tags[]` and sends an object as `deepObject`: ```openapi requestBody: @@ -131,7 +131,7 @@ requestBody: ## Body content types -A `TypedHandler` with body fields accepts **`application/json`** and **`application/x-www-form-urlencoded`** by default, or **`application/json`** and **`multipart/form-data`** when its DTO contains a `#[File]` property; OpenAPI lists the same types in `requestBody.content` (only multipart when a file is required). The content type is matched without parameters. JSON must be UTF-8: a request that names another `charset` is a `400`. A body without a `Content-Type`, or with a type the handler does not accept, is a `415`. File properties appear only in the `multipart/form-data` schema, and a JSON request to a DTO with a required file gets a `400` that says files need `multipart/form-data`. +A `TypedHandler` with body fields accepts **`application/json`** and **`application/x-www-form-urlencoded`** by default, or **`application/json`** and **`multipart/form-data`** when its DTO contains a `#[File]` property; OpenAPI lists the same types in `requestBody.content` (only multipart when a file is required). The content type is matched without parameters. JSON must be UTF-8: a request that names another `charset` is a `400`. A body without a `Content-Type`, or with a type the handler does not accept, is a `415`; a request with no body at all passes when no body field is required, whatever its `Content-Type` says. File properties appear only in the `multipart/form-data` schema, and a JSON request to a DTO with a required file gets a `400` that says files need `multipart/form-data`. ### Restrict accepted types with Consumes @@ -186,7 +186,7 @@ For example, JSON `"quantity": 2` stays an integer, while form `quantity=2` beco For an optional form value, omit `deliveryAt` instead of sending `deliveryAt=null` or an empty value. A multipart file cannot be replaced with a JSON base64 string; an application needing base64 uploads can keep `BaseHandler` and parse its own raw body. -Send multipart with `POST`. Forms over `max_input_vars` are rejected with `400`. +Send multipart with `POST`. Forms over `max_input_vars` are rejected with `400`. PHP does not keep a multipart body to count it again, so a multipart form with exactly `max_input_vars` fields is rejected too; raise the limit if your forms are that large. ## Forms and cookie-authenticated endpoints @@ -209,5 +209,5 @@ final readonly class AvatarInput } ``` -`FileUpload` has the properties `originalName`, `clientContentType`, `temporaryPath`, `size` and `error` (a PHP `UPLOAD_ERR_*` code). `?FileUpload` is an optional upload and `list` accepts several files in one field. The handler checks the upload error, the size and the real type before storing the file; nothing is moved automatically. `#[File]` is allowed only on the root input DTO of the handler, not inside a nested DTO or a list. +`FileUpload` has the properties `originalName`, `clientContentType`, `temporaryPath`, `size` and `error` (a PHP `UPLOAD_ERR_*` code). `?FileUpload` is an optional upload and `list` accepts several files in one field; file inputs of the list the client left empty are left out of it. The handler checks the upload error, the size and the real type before storing the file; nothing is moved automatically. `#[File]` is allowed only on the root input DTO of the handler, not inside a nested DTO or a list. diff --git a/docs/guide/typed-input.md b/docs/guide/typed-input.md index 578222e24..d6dd5ab15 100644 --- a/docs/guide/typed-input.md +++ b/docs/guide/typed-input.md @@ -91,7 +91,7 @@ For example, `#[Header('X-Request-Id')] public ?string $requestId = null` reads ### Path values and URL templates -A path value is declared in the endpoint URL with `{name}`, for example `users/{id}/detail`. It is required, it cannot be nullable or have a default, and its OpenAPI path placeholder has the same name. A `{name}` without a `#[Path]` property, or a `#[Path]` property missing from the URL, fails the container compilation with the DI extension; with `addApi()` it throws a `LogicException` when the endpoint is first matched. Static endpoint URLs work unchanged. A path value is one URL segment. Segments are URL-decoded after the path is split, so an encoded slash stays in the value: `/users/a%2Fb/detail` gives `id` `a/b`. +A path value is declared in the endpoint URL with `{name}`, for example `users/{id}/detail`. It is required, it cannot be nullable or have a default, and its OpenAPI path placeholder has the same name. A `{name}` without a `#[Path]` property, or a `#[Path]` property missing from the URL, fails the container compilation with the DI extension; with `addApi()` it throws a `LogicException` when the endpoint is first used. The same check covers a `PathInputParam` of a `params()` handler. Static endpoint URLs work unchanged. A path value is one URL segment, so it cannot contain a slash: a request with an encoded slash (`%2F`) in the path matches no template. Register the template as the action of the endpoint, in any of the usual ways: @@ -110,7 +110,7 @@ final class UserDetailHandler extends TypedHandler $apiDecider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), new UserDetailHandler(), new NoAuthorization()); ``` -The route has to let the template segments through. The route of the [typed input example](/examples/typed-input), `/api/v/[/][/]`, lets one segment through after the action; a deeper template such as `{id}/orders/{orderId}` needs `[/]` in the route mask, otherwise Nette answers `404` before the API sees the request. A request is looked up among the static endpoints first and then among the templates. When the URL has segments after the action, a template that matches the whole path wins over a shorter static endpoint: `/users/7/detail` goes to `users/{id}/detail`, not to a static `users/7`. Two templates that can match the same URL fail the container compilation with the DI extension; with `addApi()` the request throws a `LogicException` that names both. Make a static segment differ. +The route has to let the template segments through. The route of the [typed input example](/examples/typed-input), `/api/v/[/][/]`, lets one segment through after the action; a deeper template such as `{id}/orders/{orderId}` needs `[/]` in the route mask, otherwise Nette answers `404` before the API sees the request. A request is looked up among the static endpoints first and then among the templates. When the URL has segments after the action, a template that matches the whole path wins over a shorter static endpoint: `/users/7/detail` goes to `users/{id}/detail`, not to a static `users/7`. Two templates that can match the same URL fail the container compilation with the DI extension, and `addApi()` throws a `LogicException` that names both. Make a static segment differ. ### Required values and defaults @@ -174,7 +174,7 @@ Errors use the same envelope as `params()` handlers. The detail key is the field When error details are disabled, only `status` and `message` are returned. With Problem Details enabled, the same field paths and messages appear in its `errors` list as `parameter` and `detail`. -Errors of the body as a whole, such as malformed JSON (`Syntax error`), a charset other than UTF-8 or an unreadable body, appear under `body`; avoid naming a field `body` (use `#[Body('payload')]`). +Errors of the body as a whole, such as malformed JSON (`Syntax error`), a charset other than UTF-8 or an unreadable body, appear under `body`, so no field can be read as `body`: compiling such a DTO fails, give the property another input name, for example `#[Body('payload')]`. A missing nested object reports the nested object path. Unknown input fields are ignored, as with ordinary query and form params. diff --git a/docs/sk/examples/openapi-console.md b/docs/sk/examples/openapi-console.md index 1fddf90b3..47d04af50 100644 --- a/docs/sk/examples/openapi-console.md +++ b/docs/sk/examples/openapi-console.md @@ -25,7 +25,7 @@ Summary, popis, tagy, parametre aj výstupy skončia v OpenAPI dokumente. <<< @/../examples/openapi-console/app/UI/Console/ConsolePresenter.php -Pohľad `default` (`default.latte`) vykreslí zoznam endpointov. Klik na endpoint presmeruje na `actionShow`, ktorá vykreslí `show.latte` s formulárom konzoly pre daný endpoint. +Pohľad `default` (`default.latte`) vykreslí zoznam endpointov. Klik na endpoint presmeruje na `actionShow`, ktorá vykreslí `show.latte` s formulárom konzoly pre daný endpoint. `GET /api/v1/books/{id}` má šablónu URL: formulár sa opýta na `id` a konzola ho dosadí do URL. <<< @/../examples/openapi-console/app/UI/Console/default.latte diff --git a/docs/sk/guide/api-decider.md b/docs/sk/guide/api-decider.md index baa9d55d4..63ff350b6 100644 --- a/docs/sk/guide/api-decider.md +++ b/docs/sk/guide/api-decider.md @@ -59,7 +59,7 @@ services: ### Endpointy so segmentmi {name} -Endpoint, ktorého akcia má segmenty `{name}`, napríklad `users/{id}/detail`, potrebuje cestu požiadavky. `ApiPresenter` najprv zavolá `getApi()` a keď ten nič nenájde, zavolá `matchPath($method, $version, $package, $apiAction, $path)`, takže pri tej istej URL vyhrá statický endpoint. Keď má URL za akciou ďalšie segmenty, `ApiPresenter` skúsi `matchPath()` ako prvé: šablóna, ktorá zodpovedá celej ceste, napríklad `users/{id}/detail` pre `/users/7/detail`, vyhrá nad kratším statickým endpointom `users/7`. `matchPath()` porovná cestu so všetkými šablónami danej metódy a verzie, uloží zhodné hodnoty pre properties `#[Path]` a vráti `Api`, alebo `null`, keď nezodpovedá žiadna šablóna. Ak jednej ceste vyhovujú dve šablóny, vyhodí `LogicException`, ktorá ich vymenuje; s DI rozšírením takéto šablóny zastavia už kompiláciu kontajnera. Zmeňte statický segment tak, aby sa líšili. Globálny preflight odpovie na `OPTIONS` aj pre cestu, ktorá zodpovedá šablóne. Ako šablónu zaregistrovať a smerovať, je na stránke [Typovaný vstup](/sk/guide/typed-input#hodnoty-z-cesty-a-sablony-url). +Endpoint, ktorého akcia má segmenty `{name}`, napríklad `users/{id}/detail`, nájde `matchPath($method, $version, $package, $apiAction, $params)` z hodnôt, ktoré rozparsoval router; `$params` sú segmenty za akciou (`` z routy). `ApiPresenter` najprv zavolá `getApi()` a keď ten nič nenájde, zavolá `matchPath()`, takže pri tej istej URL vyhrá statický endpoint. Keď má URL za akciou ďalšie segmenty, `ApiPresenter` skúsi `matchPath()` ako prvé: šablóna, ktorá zodpovedá celej ceste, napríklad `users/{id}/detail` pre `/users/7/detail`, vyhrá nad kratším statickým endpointom `users/7`. `matchPath()` porovná cestu so všetkými šablónami danej metódy a verzie, uloží zhodné hodnoty pre parametre z cesty a vráti `Api`, alebo `null`, keď nezodpovedá žiadna šablóna. `getApi()` nájde šablónu iba podľa jej doslovnej URL, napríklad `getApi('GET', '1', 'users', '{id}/detail')`, takto ju otvára API konzola. `addApi()` vyhodí `LogicException` pri chybnom segmente `{name}` a pri dvoch šablónach, ktoré môžu zodpovedať jednej ceste, a vymenuje ich; s DI rozšírením takéto šablóny zastavia už kompiláciu kontajnera. Zmeňte statický segment tak, aby sa líšili. Globálny preflight odpovie na `OPTIONS` aj pre cestu, ktorá zodpovedá šablóne. Ako šablónu zaregistrovať a smerovať, je na stránke [Typovaný vstup](/sk/guide/typed-input#hodnoty-z-cesty-a-sablony-url). `GET /api/v1/users` a `POST /api/v1/users` sú dva endpointy s dvoma handlermi. Nezaregistrovaná verzia, napríklad `/api/v3/users`, je `404`, ako testuje [príklad verzií](/sk/examples/versions). diff --git a/docs/sk/guide/console.md b/docs/sk/guide/console.md index 7e824dce0..a668ba340 100644 --- a/docs/sk/guide/console.md +++ b/docs/sk/guide/console.md @@ -37,7 +37,7 @@ Konzola zostaví požiadavku z parametrov handlera, či už pochádzajú z `para | Zdroj parametra | Posiela sa ako | | --- | --- | | query | query string | -| hodnota z cesty | URL-enkódovaná do segmentu `{name}` v URL | +| hodnota z cesty | orezaná a URL-enkódovaná do segmentu `{name}` v URL; prázdna hodnota, `.`, `..` alebo hodnota s lomítkom sa neodošle | | hodnota hlavičky | hlavička požiadavky | | pole tela | prvý media type, ktorý handler číta a konzola ho vie zostaviť: JSON, URL-enkódovaný formulár alebo multipart | | súbor | multipart upload; pri priloženom súbore idú polia tela v tej istej multipart požiadavke | diff --git a/docs/sk/guide/links.md b/docs/sk/guide/links.md index a65e35326..50aff83ff 100644 --- a/docs/sk/guide/links.md +++ b/docs/sk/guide/links.md @@ -15,7 +15,7 @@ $url = $apiLink->link(new EndpointIdentifier('GET', 1, 'users', 'detail'), ['id' Potrebuje routu na `Api:Api:default` s parametrami `version`, `package` a `apiAction`, ako v [Začíname](/sk/guide/getting-started). -Pri endpointe, ktorého URL má segmenty `{name}`, napríklad `{id}/detail`, `link()` doplní každý segment z rovnomenného parametra (s URL kódovaním); ostatné parametre idú do query stringu. Segment bez hodnoty ostane doslovný, čo je šablóna cesty z OpenAPI. Hodnota cesty `''`, `'.'` alebo `'..'` vyhodí `Nette\Application\UI\InvalidLinkException`, pretože taký segment by nikdy nezodpovedal alebo by sa vyhodnotil na inú URL: +Pri endpointe, ktorého URL má segmenty `{name}`, napríklad `{id}/detail`, `link()` doplní každý segment z rovnomenného parametra (s URL kódovaním); ostatné parametre idú do query stringu. Segment bez hodnoty ostane doslovný, čo je šablóna cesty z OpenAPI. Hodnota cesty `''`, `'.'`, `'..'` alebo hodnota s lomítkom vyhodí `Nette\Application\UI\InvalidLinkException`, pretože taký segment by nikdy nezodpovedal alebo by viedol na inú URL. `BaseHandler::createLink()` dopĺňa segmenty rovnako. Maska routy musí mať `` a `` ako segmenty cesty: ```php $url = $apiLink->link(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), ['id' => 42, 'limit' => 5]); diff --git a/docs/sk/guide/params.md b/docs/sk/guide/params.md index 30fd16be5..fcf6f312e 100644 --- a/docs/sk/guide/params.md +++ b/docs/sk/guide/params.md @@ -63,7 +63,7 @@ V 3.x `?limit=abc` s typom `INTEGER` nie je chyba: hodnota sa pred validáciou p ## Parametre Path, Header a Body -`PathInputParam` číta hodnotu z URL endpointu. Placeholder deklarujte v akcii endpointu ako `{name}`, napríklad `users/{id}/detail`, ako popisuje [Typovaný vstup](/sk/guide/typed-input#hodnoty-z-cesty-a-sablony-url). Parameter je vždy povinný a jeho placeholder v OpenAPI má rovnaký názov. `HeaderInputParam` číta hlavičku požiadavky bez ohľadu na veľkosť písmen. `BodyInputParam` číta jedno pole objektu JSON, URL-enkódovaného formulára alebo multipart tela a `setContentTypes()` nastaví media typy, ktoré dokumentuje OpenAPI a používa konzola; nevynucujú sa, takže handler s `params()` nikdy neodpovie `415`. V typovanom DTO sa z properties `#[Path]`, `#[Header]` a `#[Body]` stanú objekty `MappedInputParam` s typom `TYPE_PATH`, `TYPE_HEADER` alebo `TYPE_BODY`; `params()` deklaruje tieto triedy priamo: +`PathInputParam` číta hodnotu z URL endpointu. Placeholder deklarujte v akcii endpointu ako `{name}`, napríklad `users/{id}/detail`, ako popisuje [Typovaný vstup](/sk/guide/typed-input#hodnoty-z-cesty-a-sablony-url). Parameter je vždy povinný a jeho placeholder v OpenAPI má rovnaký názov. `HeaderInputParam` číta hlavičku požiadavky bez ohľadu na veľkosť písmen. `BodyInputParam` číta jedno pole objektu JSON, URL-enkódovaného formulára alebo multipart tela a `setContentTypes()` nastaví akceptované media typy, ktoré dokumentuje OpenAPI a používa konzola (predvolene JSON, formulár a multipart). Telo sa číta rovnako ako v typovanom handleri: pokazené JSON alebo iný charset je chyba parametra s `400`, telo s iným media typom je `415` a explicitné JSON `null` ostane `null` namiesto predvolenej hodnoty. V typovanom DTO sa z properties `#[Path]`, `#[Header]` a `#[Body]` stanú objekty `MappedInputParam` s typom `TYPE_PATH`, `TYPE_HEADER` alebo `TYPE_BODY`; `params()` deklaruje tieto triedy priamo: ```php public function params(): array diff --git a/docs/sk/guide/typed-input-body.md b/docs/sk/guide/typed-input-body.md index b5733f4ab..64556fe07 100644 --- a/docs/sk/guide/typed-input-body.md +++ b/docs/sk/guide/typed-input-body.md @@ -108,7 +108,7 @@ requestBody: deliveryAt: {type: string, format: date-time, nullable: true} ``` -Endpoint prijme aj formulár, ale OpenAPI 3.0 nevie opísať zoznam objektov vo formulárovom tele, preto je tu uvedený len JSON. DTO, ktorého telo má len skaláry, zoznamy skalárov a objekty skalárov, uvádza oba media typy; formulárová schéma pomenuje zoznam `tags[]` a objekt posiela ako `deepObject`: +Endpoint prijme aj formulár, ale OpenAPI 3.0 nevie opísať zoznam objektov vo formulárovom tele, preto je tu uvedený len JSON. DTO, ktoré má aj `#[File]`, si `multipart/form-data` ponechá, lebo súbor sa inak poslať nedá; jeho multipart schéma uvedie také pole pod obyčajným názvom a v popise povie, že sa posiela v zátvorkovej notácii (`items[0][sku]`). DTO, ktorého telo má len skaláry, zoznamy skalárov a objekty skalárov, uvádza oba media typy; formulárová schéma pomenuje zoznam `tags[]` a objekt posiela ako `deepObject`: ```openapi requestBody: @@ -131,7 +131,7 @@ requestBody: ## Typy obsahu tela -`TypedHandler` s poľami tela predvolene akceptuje **`application/json`** a **`application/x-www-form-urlencoded`**, alebo **`application/json`** a **`multipart/form-data`**, keď jeho DTO obsahuje property `#[File]`; OpenAPI uvádza rovnaké typy v `requestBody.content` (pri povinnom súbore len multipart). Typ obsahu sa porovnáva bez parametrov. JSON musí byť v UTF-8: požiadavka, ktorá uvedie iný `charset`, je `400`. Telo bez `Content-Type` alebo s typom, ktorý handler neprijíma, je `415`. Properties so súbormi sú len v schéme `multipart/form-data` a JSON požiadavka na DTO s povinným súborom dostane `400`, ktorá vysvetlí, že súbory potrebujú `multipart/form-data`. +`TypedHandler` s poľami tela predvolene akceptuje **`application/json`** a **`application/x-www-form-urlencoded`**, alebo **`application/json`** a **`multipart/form-data`**, keď jeho DTO obsahuje property `#[File]`; OpenAPI uvádza rovnaké typy v `requestBody.content` (pri povinnom súbore len multipart). Typ obsahu sa porovnáva bez parametrov. JSON musí byť v UTF-8: požiadavka, ktorá uvedie iný `charset`, je `400`. Telo bez `Content-Type` alebo s typom, ktorý handler neprijíma, je `415`; požiadavka úplne bez tela prejde, keď nie je povinné žiadne pole tela, nech je jej `Content-Type` akýkoľvek. Properties so súbormi sú len v schéme `multipart/form-data` a JSON požiadavka na DTO s povinným súborom dostane `400`, ktorá vysvetlí, že súbory potrebujú `multipart/form-data`. ### Obmedzenie akceptovaných typov cez Consumes @@ -186,7 +186,7 @@ Napríklad JSON `"quantity": 2` ostane integer, zatiaľ čo formulárové `quant Pre voliteľnú formulárovú hodnotu vynechajte `deliveryAt` namiesto poslania `deliveryAt=null` alebo prázdnej hodnoty. Multipart súbor nemožno nahradiť JSON base64 reťazcom; aplikácia, ktorá potrebuje base64 uploady, môže ponechať `BaseHandler` a spracovať vlastné raw telo. -Multipart posielajte cez `POST`. Formuláre nad `max_input_vars` sa odmietnu s `400`. +Multipart posielajte cez `POST`. Formuláre nad `max_input_vars` sa odmietnu s `400`. PHP si multipart telo neponechá, aby sa dalo spočítať znova, preto sa odmietne aj multipart formulár s presne `max_input_vars` poľami; pri takých veľkých formulároch limit zvýšte. ## Formuláre a endpointy autentifikované cez cookie @@ -209,5 +209,5 @@ final readonly class AvatarInput } ``` -`FileUpload` má properties `originalName`, `clientContentType`, `temporaryPath`, `size` a `error` (PHP kód `UPLOAD_ERR_*`). `?FileUpload` je voliteľný súbor a `list` prijme viac súborov v jednom poli. Handler pred uložením súboru skontroluje chybu nahrávania, veľkosť a skutočný typ; nič sa nepresúva automaticky. `#[File]` je povolený len v koreňovom vstupnom DTO handlera, nie vo vnorenom DTO ani v zozname. +`FileUpload` má properties `originalName`, `clientContentType`, `temporaryPath`, `size` a `error` (PHP kód `UPLOAD_ERR_*`). `?FileUpload` je voliteľný súbor a `list` prijme viac súborov v jednom poli; súborové polia zoznamu, ktoré klient nechal prázdne, v ňom nebudú. Handler pred uložením súboru skontroluje chybu nahrávania, veľkosť a skutočný typ; nič sa nepresúva automaticky. `#[File]` je povolený len v koreňovom vstupnom DTO handlera, nie vo vnorenom DTO ani v zozname. diff --git a/docs/sk/guide/typed-input.md b/docs/sk/guide/typed-input.md index d477b3952..0fad1e08b 100644 --- a/docs/sk/guide/typed-input.md +++ b/docs/sk/guide/typed-input.md @@ -91,7 +91,7 @@ Napríklad `#[Header('X-Request-Id')] public ?string $requestId = null` číta ` ### Hodnoty z cesty a šablóny URL -Hodnota z cesty sa deklaruje v URL endpointu ako `{name}`, napríklad `users/{id}/detail`. Je povinná, nemôže byť nulovateľná ani mať predvolenú hodnotu a placeholder v OpenAPI ceste má rovnaký názov. Segment `{name}` bez property `#[Path]` alebo property `#[Path]`, ktorá v URL chýba, zastaví s DI rozšírením kompiláciu kontajnera; s `addApi()` vyhodí `LogicException` pri prvom nájdení endpointu. Statické URL endpointov fungujú bez zmeny. Hodnota z cesty je jeden segment URL. Segmenty sa URL-dekódujú až po rozdelení cesty, takže zakódované lomítko ostane v hodnote: `/users/a%2Fb/detail` dá `id` `a/b`. +Hodnota z cesty sa deklaruje v URL endpointu ako `{name}`, napríklad `users/{id}/detail`. Je povinná, nemôže byť nulovateľná ani mať predvolenú hodnotu a placeholder v OpenAPI ceste má rovnaký názov. Segment `{name}` bez property `#[Path]` alebo property `#[Path]`, ktorá v URL chýba, zastaví s DI rozšírením kompiláciu kontajnera; s `addApi()` vyhodí `LogicException` pri prvom použití endpointu. Rovnaká kontrola platí aj pre `PathInputParam` handlera s `params()`. Statické URL endpointov fungujú bez zmeny. Hodnota z cesty je jeden segment URL, preto nemôže obsahovať lomítko: požiadavka so zakódovaným lomítkom (`%2F`) v ceste nezodpovedá žiadnej šablóne. Šablónu zaregistrujte ako akciu endpointu niektorým zo zvyčajných spôsobov: @@ -110,7 +110,7 @@ final class UserDetailHandler extends TypedHandler $apiDecider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), new UserDetailHandler(), new NoAuthorization()); ``` -Routa musí prepustiť segmenty šablóny. Routa z [príkladu typovaného vstupu](/sk/examples/typed-input), `/api/v/[/][/]`, prepustí za akciou jeden segment; hlbšia šablóna ako `{id}/orders/{orderId}` potrebuje v maske routy `[/]`, inak Nette odpovie `404` skôr, ako požiadavka dorazí do API. Požiadavka sa hľadá najprv medzi statickými endpointmi a potom medzi šablónami. Keď má URL za akciou ďalšie segmenty, šablóna, ktorá zodpovedá celej ceste, vyhrá nad kratším statickým endpointom: `/users/7/detail` pôjde na `users/{id}/detail`, nie na statický `users/7`. Dve šablóny, ktoré môžu zodpovedať tej istej URL, zastavia s DI rozšírením kompiláciu kontajnera; s `addApi()` požiadavka vyhodí `LogicException`, ktorá pomenuje obe. Zmeňte statický segment tak, aby sa líšili. +Routa musí prepustiť segmenty šablóny. Routa z [príkladu typovaného vstupu](/sk/examples/typed-input), `/api/v/[/][/]`, prepustí za akciou jeden segment; hlbšia šablóna ako `{id}/orders/{orderId}` potrebuje v maske routy `[/]`, inak Nette odpovie `404` skôr, ako požiadavka dorazí do API. Požiadavka sa hľadá najprv medzi statickými endpointmi a potom medzi šablónami. Keď má URL za akciou ďalšie segmenty, šablóna, ktorá zodpovedá celej ceste, vyhrá nad kratším statickým endpointom: `/users/7/detail` pôjde na `users/{id}/detail`, nie na statický `users/7`. Dve šablóny, ktoré môžu zodpovedať tej istej URL, zastavia s DI rozšírením kompiláciu kontajnera a `addApi()` vyhodí `LogicException`, ktorá pomenuje obe. Zmeňte statický segment tak, aby sa líšili. ### Povinné hodnoty a predvolené hodnoty @@ -174,7 +174,7 @@ Chyby používajú rovnakú obálku ako handlery s `params()`. Kľúč detailu j Pri vypnutých detailoch chýb sa vrátia len `status` a `message`. So zapnutými Problem Details sa rovnaké cesty polí a hlášky objavia v jeho zozname `errors` ako `parameter` a `detail`. -Chyby tela ako celku, napríklad pokazené JSON (`Syntax error`), iný charset než UTF-8 alebo nečitateľné telo, sa objavia pod `body`; pole nenazývajte `body` (použite `#[Body('payload')]`). +Chyby tela ako celku, napríklad pokazené JSON (`Syntax error`), iný charset než UTF-8 alebo nečitateľné telo, sa objavia pod `body`, preto žiadne pole nemôže mať vstupný názov `body`: kompilácia takého DTO zlyhá, dajte property iný vstupný názov, napríklad `#[Body('payload')]`. Chýbajúci vnorený objekt nahlási cestu vnoreného objektu. Neznáme vstupné polia sa ignorujú, rovnako ako pri bežných query a formulárových parametroch. diff --git a/examples/openapi-console/app/Api/BookDetailHandler.php b/examples/openapi-console/app/Api/BookDetailHandler.php new file mode 100644 index 000000000..906cb9021 --- /dev/null +++ b/examples/openapi-console/app/Api/BookDetailHandler.php @@ -0,0 +1,47 @@ + ['id' => 1, 'title' => 'Dune', 'year' => 1965], + 2 => ['id' => 2, 'title' => 'Neuromancer', 'year' => 1984], + ]; + + public function summary(): string + { + return 'Show a book'; + } + + public function tags(): array + { + return ['books']; + } + + public function params(): array + { + return [ + (new PathInputParam('id', InputType::INTEGER))->setDescription('Id of the book'), + ]; + } + + public function handle(array $params): ResponseInterface + { + $book = self::BOOKS[$params['id']] ?? null; + return $book === null + ? new JsonApiResponse(404, ['status' => 'error', 'message' => 'Book not found']) + : new JsonApiResponse(200, ['book' => $book]); + } +} diff --git a/examples/openapi-console/config/common.neon b/examples/openapi-console/config/common.neon index 93a997918..234130439 100644 --- a/examples/openapi-console/config/common.neon +++ b/examples/openapi-console/config/common.neon @@ -29,6 +29,7 @@ services: - App\Api\BookListHandler - App\Api\BookCreateHandler + - App\Api\BookDetailHandler # the listing handlers need ApiDecider, so they are registered by class name below # and created only when their endpoint is called - Tomaj\NetteApi\Handlers\OpenApiHandler(initData: [info: [title: 'Bookshelf API', description: 'Example API documented with OpenAPI']]) @@ -38,6 +39,8 @@ services: factory: Tomaj\NetteApi\ApiDecider setup: - addApi(Tomaj\NetteApi\EndpointIdentifier('GET', 1, 'books'), App\Api\BookListHandler, Tomaj\NetteApi\Authorization\NoAuthorization()) + # GET /api/v1/books/2, the {id} segment is the path parameter of the handler + - addApi(Tomaj\NetteApi\EndpointIdentifier('GET', 1, 'books', '{id}'), App\Api\BookDetailHandler, Tomaj\NetteApi\Authorization\NoAuthorization()) - addApi(Tomaj\NetteApi\EndpointIdentifier('POST', 1, 'books'), App\Api\BookCreateHandler, Tomaj\NetteApi\Authorization\BearerTokenAuthorization(Tomaj\NetteApi\Misc\StaticTokenRepository(%apiTokens%))) # GET /api/v1/openapi, ?format=yaml with symfony/yaml installed - addApi(Tomaj\NetteApi\EndpointIdentifier('GET', 1, 'openapi'), Tomaj\NetteApi\Handlers\OpenApiHandler, Tomaj\NetteApi\Authorization\NoAuthorization()) diff --git a/examples/openapi-console/e2e.sh b/examples/openapi-console/e2e.sh index 5bd86136c..34c379b93 100755 --- a/examples/openapi-console/e2e.sh +++ b/examples/openapi-console/e2e.sh @@ -38,7 +38,22 @@ expect_body 'name="since"' "console form" ok "GET /console/show/GET/1/books renders the form for the since parameter" request -c "$jar" -b "$jar" -d "api_url=$BASE/api/v1/books/&api_method=GET&since=1980&timeout=10&_do=apiConsole-consoleForm-submit&send=1" "$BASE/console/show/GET/1/books" -rm -f "$jar" expect_status 200 "console request" expect_body 'Neuromancer' "console request" ok "submitting the console form calls the endpoint and shows the response" + +request "$BASE/api/v1/books/2" +expect_status 200 "URL template" +expect_body '"title":"Neuromancer"' "URL template" +ok "GET /api/v1/books/2 fills the {id} segment" + +request -c "$jar" -b "$jar" "$BASE/console/show/GET/1/books/%7Bid%7D" +expect_status 200 "console form of a URL template" +expect_body 'name="id"' "console form of a URL template" +ok "GET /console/show/GET/1/books/{id} renders the form for the path parameter" + +request -c "$jar" -b "$jar" -d "api_url=$BASE/api/v1/books/%7Bid%7D&api_method=GET&id=1&timeout=10&_do=apiConsole-consoleForm-submit&send=1" "$BASE/console/show/GET/1/books/%7Bid%7D" +rm -f "$jar" +expect_status 200 "console request of a URL template" +expect_body 'Dune' "console request of a URL template" +ok "the console fills the {id} segment and shows the response" diff --git a/src/ApiDecider.php b/src/ApiDecider.php index 6071126d5..35763dc4c 100644 --- a/src/ApiDecider.php +++ b/src/ApiDecider.php @@ -27,6 +27,9 @@ class ApiDecider /** @var list */ private array $apis = []; + /** @var array holders whose URL template was checked against the path params of the handler */ + private array $checked = []; + private ?ApiHandlerInterface $globalPreflightHandler = null; public function __construct( @@ -38,7 +41,8 @@ public function __construct( * Get api handler that match input method, version, package and apiAction. * If decider cannot find handler for given handler, returns defaults. * - * Endpoints with {name} segments are found by matchPath(), because they need the request path. + * An endpoint with {name} segments is found here only by its literal URL, for example by the API console; + * a request with the values in the path is matched by matchPath(). * * @param string $apiAction * @@ -52,10 +56,6 @@ public function getApi(string $method, string $version, string $package, ?string foreach ($this->apis as $api) { $identifier = $api->getEndpoint(); - if (str_contains($identifier->getUrl(), '{')) { - // a template is matched by matchPath(), a literal "{id}" in the request must not reach it - continue; - } if ($method === $identifier->getMethod() && $identifier->getVersion() === $version && $identifier->getPackage() === $package && $identifier->getApiAction() === $apiAction) { $endpointIdentifier = new EndpointIdentifier($method, $version, $package, $apiAction); $handler = $this->getHandler($api); @@ -73,39 +73,24 @@ public function getApi(string $method, string $version, string $package, ?string /** * Finds an endpoint whose URL has {name} segments, for example users/{id}/detail, and stores the matched values - * for #[Path] properties. Called after getApi() found no static endpoint. Null when no template matches. - * - * @param string|null $requestPath absolute or application path of the request - * - * @throws \LogicException when more than one template matches + * for the path params. Takes the values the router parsed: $params are the segments after the action + * (the of the route). Null when no template matches. */ - public function matchPath(string $method, string $version, string $package, ?string $apiAction, ?string $requestPath): ?Api + public function matchPath(string $method, string $version, string $package, ?string $apiAction, ?string $params = null): ?Api { - if ($requestPath === null) { - return null; - } - $method = strtoupper($method); $apiAction = $apiAction === '' ? null : $apiAction; - $matched = $this->matchTemplate($method, $version, $requestPath); - if (count($matched) > 1) { - $urls = array_map(static fn (array $match): string => $match[0]->getEndpoint()->getUrl(), $matched); - throw new \LogicException(sprintf( - "%s request '%s' matches more than one endpoint (%s). Make a static segment differ so only one URL template matches.", - $method, - $requestPath, - implode(', ', $urls), - )); - } - if (count($matched) === 1) { - [$api, $captured] = $matched[0]; + $path = implode('/', array_filter([$package, $apiAction, $params], static fn (?string $part): bool => $part !== null && $part !== '')); + $matched = $this->matchTemplate($method, $version, $path); + if ($matched !== null) { + [$api, $captured] = $matched; PathValues::set($captured); $handler = $this->getHandler($api); $handler->setEndpointIdentifier($api->getEndpoint()); return new Api($api->getEndpoint(), $handler, $api->getAuthorization(), $api->getRateLimit()); } - if ($method === 'OPTIONS' && $this->globalPreflightHandler && $this->matchTemplate('', $version, $requestPath) !== []) { + if ($method === 'OPTIONS' && $this->globalPreflightHandler && $this->matchTemplate('', $version, $path) !== null) { return new Api(new EndpointIdentifier('OPTIONS', $version, $package, $apiAction), $this->globalPreflightHandler, new NoAuthorization()); } @@ -128,7 +113,8 @@ public function enableGlobalPreflight(?CorsPreflightHandlerInterface $corsHandle * * @param RateLimiterInterface|RateLimitInterface|null $rateLimit a RateLimitInterface (deprecated) still works through LegacyRateLimitAdapter. * Left out, the autowired RateLimitInterface service is used like in 3.x; null means no rate limit. - * @throws \LogicException when it is left out and the container has more autowired RateLimitInterface services + * @throws \LogicException when it is left out and the container has more autowired RateLimitInterface services, + * or when the URL has a malformed {name} segment or can match the same request as another URL template */ public function addApi(EndpointInterface $endpointIdentifier, ApiHandlerInterface|string $handler, ApiAuthorizationInterface $apiAuthorization, RateLimiterInterface|RateLimitInterface|null $rateLimit = new AutowiredRateLimit()): self { @@ -145,6 +131,15 @@ public function addApi(EndpointInterface $endpointIdentifier, ApiHandlerInterfac ), previous: $e); } } + $url = $endpointIdentifier->getUrl(); + if (str_contains($url, '{')) { + EndpointTemplate::assertSyntax($url, sprintf('%s %s', $endpointIdentifier->getMethod(), $url)); + foreach ($this->apis as $api) { + if ($api->getEndpoint()->getMethod() === $endpointIdentifier->getMethod()) { + EndpointTemplate::assertDisjoint([$endpointIdentifier->getMethod() => [$api->getEndpoint()->getUrl(), $url]]); + } + } + } $this->apis[] = new ApiHolder($endpointIdentifier, $handler, $apiAuthorization, $rateLimit); return $this; } @@ -194,51 +189,51 @@ private function getHandler(ApiHolder $api): ApiHandlerInterface $handler = $resolved; } - $this->checkPath($api->getEndpoint(), $handler); + $id = spl_object_id($api); + if (!isset($this->checked[$id]) && $this->checkPath($api->getEndpoint(), $handler)) { + // the configuration does not change, so it is checked once and not on every request + $this->checked[$id] = true; + } return $handler; } /** - * @return list}> + * @return array{0: ApiHolder, 1: array}|null */ - private function matchTemplate(string $method, string $version, string $requestPath): array + private function matchTemplate(string $method, string $version, string $path): ?array { - $normalized = EndpointTemplate::normalize($requestPath, $version); - if ($normalized === null) { - return []; - } - - $matched = []; foreach ($this->apis as $api) { $identifier = $api->getEndpoint(); - if (($method !== '' && $method !== $identifier->getMethod()) || !str_contains($identifier->getUrl(), '{')) { + if (($method !== '' && $method !== $identifier->getMethod()) || $identifier->getVersion() !== $version || !str_contains($identifier->getUrl(), '{')) { continue; } - $captured = EndpointTemplate::match($identifier->getUrl(), $normalized); + // addApi() refuses two templates that can match one request, so the first match is the only one + $captured = EndpointTemplate::match(sprintf('%s/%s', $identifier->getPackage(), $identifier->getApiAction() ?? ''), $path); if ($captured !== null) { - $matched[] = [$api, $captured]; + return [$api, $captured]; } } - return $matched; + return null; } /** - * A URL template must match the path params of its handler. A plain handler on a static URL is skipped, - * so its params() is not called one more time on every request. + * A URL template must match the path params of its handler, and a path param needs a {name} in the URL. + * False when the params of a plain handler cannot be read now; the presenter answers that error after the authorization. */ - private function checkPath(EndpointInterface $endpoint, ApiHandlerInterface $handler): void + private function checkPath(EndpointInterface $endpoint, ApiHandlerInterface $handler): bool { - if (!str_contains($endpoint->getUrl(), '{') && !$handler instanceof TypedHandler) { - return; - } - if ($handler instanceof TypedHandler) { - // from the compiled metadata, without building every param and its OpenAPI schema on each request + // from the compiled metadata, without building every param and its OpenAPI schema $names = DtoMetadataRegistry::forHandler($handler::class)->pathNames(); } else { + try { + $params = $handler->params(); + } catch (\Throwable) { + return false; + } $names = []; - foreach ($handler->params() as $param) { + foreach ($params as $param) { if ($param->getType() === InputParam::TYPE_PATH) { $names[] = $param->getKey(); } @@ -246,5 +241,6 @@ private function checkPath(EndpointInterface $endpoint, ApiHandlerInterface $han } EndpointTemplate::assert($endpoint->getUrl(), $names, $handler::class); + return true; } } diff --git a/src/Handlers/BaseHandler.php b/src/Handlers/BaseHandler.php index ece82a0b5..10a1e5088 100644 --- a/src/Handlers/BaseHandler.php +++ b/src/Handlers/BaseHandler.php @@ -10,6 +10,7 @@ use Nette\Application\UI\InvalidLinkException; use Nette\InvalidStateException; use Tomaj\NetteApi\EndpointInterface; +use Tomaj\NetteApi\Link\ApiLink; use Tomaj\NetteApi\Response\ResponseInterface; abstract class BaseHandler implements ApiHandlerInterface @@ -121,7 +122,7 @@ final public function setupLinkGenerator(LinkGenerator $linkGenerator): self } /** - * Create link to actual handler endpoint + * Create link to actual handler endpoint, a {name} segment of a URL template is filled from $params[name] * * @param array $params * @@ -137,12 +138,7 @@ final public function createLink(array $params = []): string throw new InvalidStateException('You have setEndpoint() for this handler if you want to generate link in this handler'); } - $params = array_merge([ - 'version' => $this->endpoint->getVersion(), - 'package' => $this->endpoint->getPackage(), - 'apiAction' => $this->endpoint->getApiAction(), - ], $params); - return $this->linkGenerator->link('Api:Api:default', $params) ?: ''; + return new ApiLink($this->linkGenerator)->link($this->endpoint, $params); } /** diff --git a/src/Input/DtoCompiler.php b/src/Input/DtoCompiler.php index bd33ac028..46fb4cfdf 100644 --- a/src/Input/DtoCompiler.php +++ b/src/Input/DtoCompiler.php @@ -20,7 +20,7 @@ */ final class DtoCompiler { - /** @var array */ + /** @var array> a class of each file the metadata is read from, keyed by the file */ private array $files = []; /** @var list */ @@ -32,7 +32,7 @@ public static function compile(string $handler): DtoMetadata } /** - * Also returns the absolute paths of the handler, DTO, enum, constraint and caster files, so editing one rebuilds the container. + * Also returns the absolute paths of the handler, DTO, enum, constraint and caster files and of the classes whose constants they read, so editing one rebuilds the container. * * @return array{metadata: DtoMetadata, files: list} */ @@ -40,8 +40,23 @@ public static function compileWithFiles(string $handler): array { $compiler = new self(); $metadata = $compiler->handler($handler); + $files = []; + foreach ($compiler->files as $file => $class) { + $files[$file] = $file; + // a constant of another class in an attribute argument or a default is copied into the metadata, so its file is a dependency too + foreach (TypeName::constantClasses($class) as $name) { + if (!class_exists($name) && !interface_exists($name)) { + continue; + } + // a built-in class has no file + $referenced = new \ReflectionClass($name)->getFileName(); + if (is_string($referenced)) { + $files[$referenced] = $referenced; + } + } + } - return ['metadata' => $metadata, 'files' => array_values($compiler->files)]; + return ['metadata' => $metadata, 'files' => array_values($files)]; } private function handler(string $handler): DtoMetadata @@ -65,6 +80,17 @@ private function handler(string $handler): DtoMetadata $this->touch($reflection); $dto = $this->dtoClass($reflection); $fields = $this->dto($dto, true); + foreach ($fields as $field) { + if ($field->externalName === DtoMapper::REQUEST_ERRORS) { + $this->fail(sprintf( + "%s::$%s is read as '%s', the key under which errors of the request as a whole are reported. Give it another input name, for example #[%s('payload')].", + $dto, + $field->property, + DtoMapper::REQUEST_ERRORS, + ucfirst($field->source->value), + )); + } + } $contentTypes = $this->contentTypes($reflection, $fields); $readsBody = false; $bodyRequired = false; @@ -718,11 +744,11 @@ private function list(\ReflectionProperty $property, \ReflectionClass $dto, stri private function documentedType(\ReflectionProperty $property, \ReflectionClass $dto): ?array { $propertyDoc = $property->getDocComment() ?: ''; - $propertyScope = $property->getDeclaringClass(); + $propertyScope = self::traitScope($property->getDeclaringClass(), static fn (\ReflectionClass $trait): bool => $trait->hasProperty($property->getName()) && $trait->getProperty($property->getName())->getDocComment() === $property->getDocComment()); $constructor = $dto->getConstructor(); $docs = [[$propertyDoc, $propertyScope]]; if ($constructor instanceof \ReflectionMethod) { - $docs[] = [$constructor->getDocComment() ?: '', $constructor->getDeclaringClass()]; + $docs[] = [$constructor->getDocComment() ?: '', self::methodScope($constructor)]; } $name = $property->getName(); @@ -974,8 +1000,8 @@ private function casterReturn(\ReflectionClass $caster, \ReflectionClass $dto, s } $documented = $this->documentedList($method); $expected = $listItem; - // relative to the class that declares cast(), which is a parent when the method is inherited - if ($documented === null || TypeName::resolve($documented, $method->getDeclaringClass()) !== $expected) { + // relative to the class or trait that declares cast(), which is a parent when the method is inherited + if ($documented === null || TypeName::resolve($documented, self::methodScope($method)) !== $expected) { $this->fail(sprintf( '%s::cast() must document `@return list<%s>` because %s::$%s is that list%s. The check reads the docblock of cast().', $caster->getName(), @@ -1013,6 +1039,37 @@ private function casterReturn(\ReflectionClass $caster, \ReflectionClass $dto, s } } + /** + * The class or trait whose file holds the method. Reflection reports a method that comes from a trait as declared by the class using it. + * + * @return \ReflectionClass<*> + */ + private static function methodScope(\ReflectionMethod $method): \ReflectionClass + { + return self::traitScope($method->getDeclaringClass(), static fn (\ReflectionClass $trait): bool => array_any( + $trait->getMethods(), + static fn (\ReflectionMethod $candidate): bool => $candidate->getFileName() === $method->getFileName() && $candidate->getStartLine() === $method->getStartLine(), + )); + } + + /** + * The trait, possibly used by another trait, that declares a member of the class, or the class itself. + * + * @param \ReflectionClass<*> $class + * @param \Closure(\ReflectionClass<*>): bool $declares + * @return \ReflectionClass<*> + */ + private static function traitScope(\ReflectionClass $class, \Closure $declares): \ReflectionClass + { + foreach ($class->getTraits() as $trait) { + if ($declares($trait)) { + return self::traitScope($trait, $declares); + } + } + + return $class; + } + private function documentedList(\ReflectionMethod $method): ?string { $doc = $method->getDocComment(); @@ -1150,7 +1207,7 @@ private function touchFile(\ReflectionClass $class): void { $file = $class->getFileName(); if (is_string($file)) { - $this->files[$file] = $file; + $this->files[$file] = $class; } } diff --git a/src/Input/DtoMapper.php b/src/Input/DtoMapper.php index a43000d2a..c67717183 100644 --- a/src/Input/DtoMapper.php +++ b/src/Input/DtoMapper.php @@ -15,6 +15,9 @@ final class DtoMapper /** One request reports at most this many errors, however many lists and objects are nested. The rest of the body is not checked. */ public const int MAX_ERRORS = 100; + /** Errors of the request as a whole, such as malformed JSON, are reported under this key; no field may use it. */ + public const string REQUEST_ERRORS = 'body'; + private bool $done = false; /** @var array */ @@ -29,8 +32,12 @@ final class DtoMapper /** Something was left unchecked because the budget was spent. */ private bool $skipped = false; + /** @var \WeakMap one caster per field, however many list items it converts */ + private \WeakMap $casters; + public function __construct(private readonly DtoMetadata $metadata) { + $this->casters = new \WeakMap(); } public function value(Field $field): mixed @@ -57,8 +64,8 @@ public function errors(Field $field): array } } // errors of the request as a whole belong to one field, so that they are reported once: the first body field, or the first field when nothing reads a body - if ($field->property === ($this->metadata->firstBody ?? $this->metadata->fields[0]->property) && isset($this->errors['body'])) { - $own['body'] = $this->errors['body']; + if ($field->property === ($this->metadata->firstBody ?? $this->metadata->fields[0]->property) && isset($this->errors[self::REQUEST_ERRORS])) { + $own[self::REQUEST_ERRORS] = $this->errors[self::REQUEST_ERRORS]; } return $own; @@ -96,11 +103,11 @@ private function evaluate(): void } } if ($failure !== null) { - $this->errors['body'][] = $failure; + $this->errors[self::REQUEST_ERRORS][] = $failure; } if ($this->skipped) { // under `body` because it is about the request as a whole, not about the field that happened to use the last of the budget - $this->errors['body'][] = sprintf('Only the first %d errors are reported, the rest of the request was not checked', self::MAX_ERRORS); + $this->errors[self::REQUEST_ERRORS][] = sprintf('Only the first %d errors are reported, the rest of the request was not checked', self::MAX_ERRORS); } $this->values = $converted; } @@ -134,7 +141,7 @@ private function convert(Field $field, mixed $raw, string $path): array if ($field->casterClass !== null) { try { - $caster = new ($field->casterClass)(...$field->casterArguments); + $caster = $this->casters[$field] ??= new ($field->casterClass)(...$field->casterArguments); $value = $caster->cast($raw); } catch (CastException $exception) { return $this->fail($path, $exception->getMessage()); @@ -246,7 +253,10 @@ private function file(Field $field, mixed $raw, string $path): array } $uploads = []; foreach (self::fileList($raw) as $file) { - $uploads[] = FileUpload::fromFile($file); + // a file input of the list the client left empty is not an upload + if (($file['error'] ?? null) !== \UPLOAD_ERR_NO_FILE) { + $uploads[] = FileUpload::fromFile($file); + } } return ['value' => $uploads, 'errors' => []]; diff --git a/src/Input/DtoMetadataRegistry.php b/src/Input/DtoMetadataRegistry.php index 9cf6da329..7e86555b6 100644 --- a/src/Input/DtoMetadataRegistry.php +++ b/src/Input/DtoMetadataRegistry.php @@ -15,8 +15,6 @@ final class DtoMetadataRegistry /** @var array serialized DtoMetadata from the container, keyed by the handler */ private static array $installed = []; - private static bool $isInstalled = false; - /** @var array */ private static array $metadata = []; @@ -26,26 +24,9 @@ final class DtoMetadataRegistry public static function install(array $serialized): void { self::$installed = $serialized; - self::$isInstalled = true; self::$metadata = []; } - /** - * @internal - */ - public static function installed(): bool - { - return self::$isInstalled; - } - - /** - * @internal - */ - public static function installs(string $handler): bool - { - return isset(self::$installed[$handler]); - } - /** * @param class-string $handler */ @@ -73,7 +54,6 @@ public static function forHandler(string $handler): DtoMetadata public static function reset(): void { self::$installed = []; - self::$isInstalled = false; self::$metadata = []; } } diff --git a/src/Input/EndpointTemplate.php b/src/Input/EndpointTemplate.php index 2ad884dba..20b796fb1 100644 --- a/src/Input/EndpointTemplate.php +++ b/src/Input/EndpointTemplate.php @@ -41,7 +41,7 @@ public static function isComposite(string $value): bool /** * Captured path parameters when $path matches $template, otherwise null. - * Both values are endpoint URLs such as v1/users/{id}/detail and v1/users/42/detail; $path is still URL-encoded. + * Both are paths after the version, such as users/{id}/detail and users/42/detail; $path is already decoded by the router. * * @return array|null */ @@ -55,8 +55,7 @@ public static function match(string $template, string $path): ?array $captured = []; foreach ($expected as $index => $segment) { - // decoded per segment, so an encoded slash (%2F) stays inside its value - $value = rawurldecode($actual[$index]); + $value = $actual[$index]; $name = self::placeholderName($segment); if ($name !== null) { if ($value === '') { @@ -74,32 +73,59 @@ public static function match(string $template, string $path): ?array } /** - * Request path reduced to the endpoint URL (v1/users/42), or null when the version is not in the path. - * Segments stay URL-encoded; match() decodes them one by one. + * Fills the {name} segments of $template with URL-encoded values from $values. A segment without a scalar value + * stays literal, which is the OpenAPI path template. Returns the path and the values that were not used. + * + * @param array $values + * @return array{0: string, 1: array} + * @throws \InvalidArgumentException when a value is empty, a dot segment or contains a slash, so the URL would lead elsewhere */ - public static function normalize(string $requestPath, string $version): ?string + public static function fill(string $template, array $values): array { - $path = parse_url($requestPath, PHP_URL_PATH); - $path = is_string($path) ? $path : $requestPath; - $marker = sprintf('/v%s/', $version); - $position = strpos($path, $marker); - if ($position === false) { - $trimmed = trim($path, '/'); - $prefix = sprintf('v%s', $version); - if ($trimmed === $prefix || str_starts_with($trimmed, sprintf('%s/', $prefix))) { - return $trimmed; + $path = preg_replace_callback('/\{([A-Za-z_][A-Za-z0-9_]*)\}/', static function (array $match) use (&$values): string { + $name = $match[1]; + if (!isset($values[$name]) || !is_scalar($values[$name])) { + return $match[0]; + } + $value = (string) $values[$name]; + if (in_array($value, ['', '.', '..'], true) || str_contains($value, '/')) { + // an empty segment is never matched, a dot segment is resolved away by clients and a slash splits the segment + throw new \InvalidArgumentException(sprintf("Path value '%s' cannot be '%s'. Use a non-empty value without a slash that is not '.' or '..'.", $name, $value)); } + unset($values[$name]); - return null; - } + return rawurlencode($value); + }, $template); - return trim(substr($path, $position), '/'); + return [(string) $path, $values]; } /** * @param list $declared external names of the path parameters */ public static function assert(string $url, array $declared, string $where): void + { + self::assertSyntax($url, $where); + $placeholders = self::placeholders($url); + $missing = array_diff($placeholders, $declared); + $undeclared = array_diff($declared, $placeholders); + if ($missing === [] && $undeclared === []) { + return; + } + + throw new \LogicException(sprintf( + "%s: the endpoint URL '%s' and its path parameters do not match. The URL has {%s} and the handler declares [%s]. Every {name} needs a #[Path] property or a PathInputParam with that name, and every path parameter must appear in the URL, for example #[Get(1, 'users', '{id}/detail')] with #[Path] public int \$id.", + $where, + trim($url, '/'), + implode(', ', $placeholders), + implode(', ', $declared), + )); + } + + /** + * Each {name} is a whole segment and appears once. + */ + public static function assertSyntax(string $url, string $where): void { $placeholders = self::placeholders($url); $duplicatePlaceholders = array_diff_assoc($placeholders, array_unique($placeholders)); @@ -122,20 +148,6 @@ public static function assert(string $url, array $declared, string $where): void )); } } - - $missing = array_diff($placeholders, $declared); - $undeclared = array_diff($declared, $placeholders); - if ($missing === [] && $undeclared === []) { - return; - } - - throw new \LogicException(sprintf( - "%s: the endpoint URL '%s' and its path parameters do not match. The URL has {%s} and the handler declares [%s]. Every {name} needs a #[Path] property or a PathInputParam with that name, and every path parameter must appear in the URL, for example #[Get(1, 'users', '{id}/detail')] with #[Path] public int \$id.", - $where, - trim($url, '/'), - implode(', ', $placeholders), - implode(', ', $declared), - )); } /** diff --git a/src/Input/RequestInput.php b/src/Input/RequestInput.php index 683e37705..ea4c858b8 100644 --- a/src/Input/RequestInput.php +++ b/src/Input/RequestInput.php @@ -33,6 +33,12 @@ final class RequestInput private static ?string $rawOverride = null; + /** @var array{key: list, body: array, failure: ?string}|null the body read for BodyInputParam */ + private static ?array $plain = null; + + /** + * Forgets what was read from the previous request. ApiPresenter calls it when a request starts; a body set by setRawBody() stays. + */ public static function reset(): void { self::$query = []; @@ -40,17 +46,18 @@ public static function reset(): void self::$files = []; self::$failure = null; self::$mediaType = null; - self::$rawOverride = null; + self::$plain = null; } /** - * Replaces php://input. Used by tests; a real request leaves this unset. + * Replaces php://input, null reads it again. Used by tests; a real request leaves this unset. * * @internal */ - public static function setRawBody(string $raw): void + public static function setRawBody(?string $raw): void { self::$rawOverride = $raw; + self::$plain = null; } /** @@ -73,6 +80,27 @@ public static function failure(): ?string return self::$failure; } + /** + * The body fields for BodyInputParam of a params() handler, read like a typed handler reads them and once per request. + * + * @param list $consumes + * @return array{body: array, failure: ?string} + * @throws UnsupportedMediaTypeException + */ + public static function plainBody(array $consumes): array + { + // a test or a worker that changes the request without reset() still gets this request's body + $key = [HeaderBag::get('Content-Type'), $_SERVER['REQUEST_METHOD'] ?? null, $_POST, $consumes]; + if (self::$plain !== null && self::$plain['key'] === $key) { + return self::$plain; + } + + // a typed handler reads the request in one go when it is first validated, so booting again here does not disturb it + self::boot($consumes, false, true); + + return self::$plain = ['key' => $key, 'body' => self::$body, 'failure' => self::$failure]; + } + /** * The accepted body media type without parameters, or null when the request has no body. */ @@ -148,17 +176,14 @@ private static function loadBody(array $consumes, bool $bodyRequired): void { $header = HeaderBag::get('Content-Type'); $type = MediaTypes::normalize($header); - if ($type === '') { - // a body that arrives without a type is never read silently: it would be dropped without a word - $raw = self::rawBody(); - if ($bodyRequired || (is_string($raw) && $raw !== '')) { - throw UnsupportedMediaTypeException::missing($consumes); + if ($type === '' || !in_array($type, $consumes, true)) { + // a request without a body is fine when nothing in the body is required, whatever its Content-Type says; + // a body that cannot be read is never dropped silently + if (!$bodyRequired && self::bodyless()) { + return; } - return; - } - if (!in_array($type, $consumes, true)) { - throw UnsupportedMediaTypeException::received($type, $consumes); + throw $type === '' ? UnsupportedMediaTypeException::missing($consumes) : UnsupportedMediaTypeException::received($type, $consumes); } self::$mediaType = $type; if ($type === MediaTypes::JSON) { @@ -226,10 +251,11 @@ private static function loadForm(): void if ($method === 'POST' || $_POST !== [] || $_FILES !== []) { self::$body = $_POST; self::$files = $_FILES; - // PHP drops the variables over max_input_vars without a word, so a form that was cut is found by parsing its body again - if (self::$mediaType === MediaTypes::FORM && count($_POST, COUNT_RECURSIVE) >= self::maxInputVars()) { + // PHP drops the variables over max_input_vars without a word, so a form that was cut is found by parsing its body again; + // a multipart body cannot be parsed again, so one that reaches the limit is taken as cut + if (self::fieldCount($_POST) >= self::maxInputVars()) { $raw = self::rawBody(); - if (is_string($raw) && self::parseForm($raw) === null) { + if (self::$mediaType === MediaTypes::MULTIPART || (is_string($raw) && self::parseForm($raw) === null)) { self::$failure = self::TOO_MANY_FIELDS; self::$body = []; } @@ -253,6 +279,27 @@ private static function loadForm(): void self::$files = $_FILES; } + private static function bodyless(): bool + { + // PHP moves a multipart body into $_POST and $_FILES, so php://input is empty for it + return $_POST === [] && $_FILES === [] && in_array(self::rawBody(), ['', false], true); + } + + /** + * The values of a form, which is what max_input_vars counts: `a[]=1&a[]=2` is two. + * + * @param array $fields + */ + private static function fieldCount(array $fields): int + { + $count = 0; + array_walk_recursive($fields, static function () use (&$count): void { + $count++; + }); + + return $count; + } + private static function maxInputVars(): int { return (int) ini_get('max_input_vars'); diff --git a/src/Input/TypeName.php b/src/Input/TypeName.php index 29e4f4a72..856527356 100644 --- a/src/Input/TypeName.php +++ b/src/Input/TypeName.php @@ -36,6 +36,29 @@ public static function resolve(string $name, \ReflectionClass $scope): string return $namespace === '' ? $name : $namespace . '\\' . $name; } + /** + * Classes whose constants or enum cases the file of the class reads, as in `#[Length(max: Limits::NAME)]` or `= Status::Active`. + * Names are resolved in the namespace of the class, and a class read twice is listed twice. + * + * @param \ReflectionClass<*> $scope + * @return list + */ + public static function constantClasses(\ReflectionClass $scope): array + { + $tokens = self::tokens(self::code($scope)); + $classes = []; + foreach ($tokens as $i => $token) { + // valid code never ends right after a name, the fallbacks only keep the lookahead inside the list + [$separator, $member, $after] = [$tokens[$i + 1] ?? $token, $tokens[$i + 2] ?? $token, $tokens[$i + 3] ?? $token]; + if ($token->is([T_STRING, T_NAME_QUALIFIED, T_NAME_FULLY_QUALIFIED]) && $separator->is(T_DOUBLE_COLON) && $member->is(T_STRING) && $after->text !== '(') { + // self::X and parent::X resolve to no class, so the caller drops them + $classes[] = self::resolve($token->text, $scope); + } + } + + return $classes; + } + /** * Class imports of the namespace block of the class, keyed by the lowercase alias. * @@ -43,11 +66,25 @@ public static function resolve(string $name, \ReflectionClass $scope): string * @return array */ private static function imports(\ReflectionClass $scope): array + { + return self::importsOf(self::code($scope), $scope->getNamespaceName()); + } + + /** @param \ReflectionClass<*> $scope */ + private static function code(\ReflectionClass $scope): string { $file = $scope->getFileName(); $code = is_string($file) && is_file($file) ? file_get_contents($file) : ''; - return self::importsOf(is_string($code) ? $code : '', $scope->getNamespaceName()); + return is_string($code) ? $code : ''; + } + + /** + * @return list<\PhpToken> + */ + private static function tokens(string $code): array + { + return array_values(array_filter(\PhpToken::tokenize($code), static fn (\PhpToken $token): bool => !$token->isIgnorable())); } /** @@ -58,7 +95,7 @@ private static function imports(\ReflectionClass $scope): array */ public static function importsOf(string $code, string $namespace): array { - $tokens = array_values(array_filter(\PhpToken::tokenize($code), static fn (\PhpToken $token): bool => !$token->isIgnorable())); + $tokens = self::tokens($code); $imports = []; $current = ''; // braces opened inside the current namespace; a `use` at 0 is an import @@ -76,7 +113,8 @@ public static function importsOf(string $code, string $namespace): array $current = $tokens[$i]->text; } $level = 0; - } elseif ($token->is(T_USE) && $level === 0) { + } elseif ($token->is(T_USE) && $level === 0 && $tokens[$i + 1]->text !== '(') { + // `function () use ($x)` of a closure outside any class is not an import $i = self::useStatement($tokens, $i, $current === $namespace, $imports); } } diff --git a/src/Input/UnsupportedMediaTypeException.php b/src/Input/UnsupportedMediaTypeException.php index 65f938117..f8ea5908d 100644 --- a/src/Input/UnsupportedMediaTypeException.php +++ b/src/Input/UnsupportedMediaTypeException.php @@ -9,20 +9,12 @@ */ final class UnsupportedMediaTypeException extends \RuntimeException { - /** - * @param list $accepted - */ - private function __construct(string $detail, public readonly array $accepted) - { - parent::__construct($detail); - } - /** * @param list $accepted */ public static function missing(array $accepted): self { - return new self('Content-Type is missing. Use one of: ' . implode(', ', $accepted) . '.', $accepted); + return new self('Content-Type is missing. Use one of: ' . implode(', ', $accepted) . '.'); } /** @@ -32,7 +24,6 @@ public static function received(string $type, array $accepted): self { return new self( "Content-Type '" . $type . "' is not supported for this endpoint. Use one of: " . implode(', ', $accepted) . '.', - $accepted, ); } } diff --git a/src/Link/ApiLink.php b/src/Link/ApiLink.php index a44b801fa..b5884faae 100644 --- a/src/Link/ApiLink.php +++ b/src/Link/ApiLink.php @@ -7,9 +7,14 @@ use Nette\Application\LinkGenerator; use Nette\Application\UI\InvalidLinkException; use Tomaj\NetteApi\EndpointInterface; +use Tomaj\NetteApi\Input\EndpointTemplate; class ApiLink { + private const string PACKAGE = 'nette-api-package'; + + private const string ACTION = 'nette-api-action'; + /** * Create ApiLink */ @@ -43,46 +48,35 @@ public function link(EndpointInterface $endpoint, $params = []): string } /** - * Keeps {name} segments literal. A normal route parameter would encode the slash and the braces. + * The router would encode the slash and the braces of a template, so the link is made with stand-in values + * of the package and the action, and the filled path replaces them. * * @param array $params */ private function templateLink(EndpointInterface $endpoint, array $params): string { - $sample = $this->linkGenerator->link('Api:Api:default', [ + $action = $endpoint->getApiAction(); + try { + [$path, $params] = EndpointTemplate::fill(rtrim(sprintf('%s/%s', $endpoint->getPackage(), $action ?? ''), '/'), $params); + } catch (\InvalidArgumentException $exception) { + throw new InvalidLinkException(sprintf('Cannot build a link for %s %s. %s', $endpoint->getMethod(), $endpoint->getUrl(), $exception->getMessage()), previous: $exception); + } + + $standIn = $action === null ? self::PACKAGE : self::PACKAGE . '/' . self::ACTION; + $link = $this->linkGenerator->link('Api:Api:default', array_merge($params, [ 'version' => $endpoint->getVersion(), - 'package' => 'package', - 'apiAction' => 'action', - ]) ?: ''; - $needle = sprintf('/v%s/package/action', $endpoint->getVersion()); - $position = strpos($sample, $needle); + 'package' => self::PACKAGE, + 'apiAction' => $action === null ? null : self::ACTION, + ])) ?: ''; + $position = strpos($link, $standIn); if ($position === false) { throw new InvalidLinkException(sprintf( - "Cannot build a link for %s %s. The router mask must contain version, package and apiAction, for example '/api/v/[/]'.", + "Cannot build a link for %s %s. The router mask must have and as path segments, for example '/api/v/[/]'.", $endpoint->getMethod(), $endpoint->getUrl(), )); } - $path = preg_replace_callback('/\{([A-Za-z_][A-Za-z0-9_]*)\}/', static function (array $match) use (&$params, $endpoint): string { - if (!isset($params[$match[1]]) || !is_scalar($params[$match[1]])) { - return $match[0]; - } - $value = (string) $params[$match[1]]; - if (in_array($value, ['', '.', '..'], true)) { - // an empty segment is never matched and a dot segment is resolved away by clients, so the link would lead elsewhere - throw new InvalidLinkException(sprintf("Path value '%s' of %s %s cannot be '%s'.", $match[1], $endpoint->getMethod(), $endpoint->getUrl(), $value)); - } - unset($params[$match[1]]); - - return rawurlencode($value); - }, rtrim($endpoint->getUrl(), '/')); - $url = substr($sample, 0, $position) . '/' . $path; - unset($params['version'], $params['package'], $params['apiAction']); - if ($params !== []) { - $url = sprintf('%s?%s', $url, http_build_query($params)); - } - - return $url; + return substr_replace($link, $path, $position, strlen($standIn)); } } diff --git a/src/Misc/ConsoleRequest.php b/src/Misc/ConsoleRequest.php index a75cf3254..fbfee27e5 100644 --- a/src/Misc/ConsoleRequest.php +++ b/src/Misc/ConsoleRequest.php @@ -7,6 +7,7 @@ use Nette\Http\FileUpload; use Tomaj\NetteApi\EndpointInterface; use Tomaj\NetteApi\Handlers\ApiHandlerInterface; +use Tomaj\NetteApi\Input\EndpointTemplate; use Tomaj\NetteApi\Input\MediaTypes; use Tomaj\NetteApi\Link\ApiLink; use Tomaj\NetteApi\Params\InputParam; @@ -31,20 +32,6 @@ public function makeRequest(string $url, string $method, array $values, array $a { [$postFields, $getFields, $cookieFields, $rawPost, $putFields, $pathFields, $headerFields, $bodyFields] = $this->processValues($values); - foreach ($pathFields as $name => $value) { - $trimmed = trim($value); - if (in_array($trimmed, ['', '.', '..'], true)) { - // the request is not sent: an empty segment cannot match and a dot segment would be resolved to another URL - $response = new ConsoleResponse($url, $method, [], [], [], [], null); - $message = $trimmed === '' - ? sprintf("The path value '%s' is empty. Fill it in and send the request again.", $name) - : sprintf("The path value '%s' cannot be '%s'. Change it and send the request again.", $name, $trimmed); - $response->logError(0, $message, 0); - - return $response; - } - } - $postFields = array_merge($postFields, $additionalValues['postFields'] ?? []); $getFields = array_merge($getFields, $additionalValues['getFields'] ?? []); $cookieFields = array_merge($cookieFields, $additionalValues['cookieFields'] ?? []); @@ -58,7 +45,16 @@ public function makeRequest(string $url, string $method, array $values, array $a // link() builds the URL, so an overridden link() still decides it; the path values go into the {name} segments afterwards $url = $this->apiLink->link($this->endpoint, $getFields); } - $url = self::substitutePath($url, $pathFields); + try { + // trimmed, as the console shows the value; the value that is checked is the one that is sent + $url = EndpointTemplate::fill($url, array_map(trim(...), $pathFields))[0]; + } catch (\InvalidArgumentException $exception) { + // not sent: an empty segment cannot match and a dot segment or a slash would lead to another URL + $response = new ConsoleResponse($url, $method, [], [], [], [], null); + $response->logError(0, $exception->getMessage() . ' Change it and send the request again.', 0); + + return $response; + } if (!($this->endpoint && $this->apiLink) && $getFields !== []) { $parts = []; @@ -285,20 +281,6 @@ private function bodyMediaType(): string return MediaTypes::JSON; } - /** - * Replaces {name} segments with URL-encoded values. - * - * @param array $pathFields - */ - private static function substitutePath(string $url, array $pathFields): string - { - foreach ($pathFields as $name => $value) { - $url = str_replace('{' . $name . '}', rawurlencode($value), $url); - } - - return $url; - } - /** * Console fields are strings. A JSON body needs the declared wire type. * diff --git a/src/OpenApi/RequestBodyBuilder.php b/src/OpenApi/RequestBodyBuilder.php index 4c791588e..dad2a4d2c 100644 --- a/src/OpenApi/RequestBodyBuilder.php +++ b/src/OpenApi/RequestBodyBuilder.php @@ -157,9 +157,9 @@ public function build(ApiHandlerInterface $handler, SchemaRegistry $schemaRegist $advertised = [MediaTypes::JSON, $typedFiles === [] && !$filesInBody ? MediaTypes::FORM : MediaTypes::MULTIPART]; } // OpenAPI 3.0 cannot describe a list of objects (or deeper nesting) in a form body, so such a body is documented - // as JSON only, unless no other media type is left + // as JSON only, unless no other media type is left; files are sent only as multipart, so a body with files keeps it if (!$this->formDescribable($typedProperties)) { - $describable = array_diff($advertised, [MediaTypes::FORM, MediaTypes::MULTIPART]); + $describable = array_diff($advertised, $typedFiles === [] ? [MediaTypes::FORM, MediaTypes::MULTIPART] : [MediaTypes::FORM]); $advertised = $describable !== [] ? $describable : $advertised; } foreach ($advertised as $contentType) { @@ -268,6 +268,15 @@ private function formMediaType(array $properties, array $required): array foreach ($properties as $name => $schema) { $schema = self::withoutNull($schema); $type = $schema['type'] ?? null; + if (!$this->formDescribable([$schema])) { + // still listed, so that no field of the body is missing from the document, with the wire shape in words + $schema['description'] = ltrim(TypeHelper::toString($schema['description'] ?? '') . sprintf("\n\nSent as form fields in bracket notation (`%s[...]`), which OpenAPI 3.0 cannot describe.", $name)); + $formProperties[$name] = $schema; + if (in_array($name, $required, true)) { + $formRequired[] = $name; + } + continue; + } $formName = $type === 'array' ? $name . '[]' : $name; $formProperties[$formName] = $schema; if (in_array($name, $required, true)) { @@ -290,7 +299,7 @@ private function formMediaType(array $properties, array $required): array * A form can carry a scalar, a list of scalars (`tags[]`) and an object of scalars (deepObject); OpenAPI 3.0 defines no * serialization for anything nested deeper. * - * @param array> $properties + * @param array> $properties */ private function formDescribable(array $properties): bool { diff --git a/src/Params/BodyInputParam.php b/src/Params/BodyInputParam.php index ddc4433c0..58c339e92 100644 --- a/src/Params/BodyInputParam.php +++ b/src/Params/BodyInputParam.php @@ -7,9 +7,12 @@ use Tomaj\NetteApi\Input\MediaTypes; use Tomaj\NetteApi\Input\RequestInput; use Tomaj\NetteApi\Validation\InputValidator; +use Tomaj\NetteApi\ValidationResult\ValidationResult; +use Tomaj\NetteApi\ValidationResult\ValidationResultInterface; /** * One field of a JSON or form body. Typed handlers generate these; params() can declare them directly. + * The body is read like a typed handler reads it: malformed JSON is an error and another media type is 415. */ class BodyInputParam extends InputParam { @@ -18,34 +21,29 @@ class BodyInputParam extends InputParam #[\Override] public function getValue(): mixed { - $value = self::body()[$this->getKey()] ?? $this->default; + $body = $this->body()['body']; + // an explicit null stays null, only a missing field takes the default + $value = array_key_exists($this->getKey(), $body) ? $body[$this->getKey()] : $this->default; return new InputValidator()->transformType($value, $this->valueType, $this->isRequired()); } - /** - * @return array - */ - private static function body(): array + #[\Override] + public function validate(): ValidationResultInterface { - $type = MediaTypes::normalize(HeaderBag::get('Content-Type')); - if ($type === MediaTypes::JSON) { - $raw = RequestInput::rawContents(); - $decoded = json_decode(is_string($raw) ? $raw : ''); - - return $decoded instanceof \stdClass ? get_object_vars($decoded) : []; - } - if ($_POST !== [] || ($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') { - return $_POST; + $failure = $this->body()['failure']; + if ($failure !== null) { + return new ValidationResult(ValidationResult::STATUS_ERROR, [$failure]); } - if ($type === MediaTypes::FORM) { - // PHP fills $_POST only for POST, a PUT or PATCH form is parsed here - $raw = RequestInput::rawContents(); - parse_str(is_string($raw) ? $raw : '', $parsed); - return $parsed; - } + return parent::validate(); + } - return []; + /** + * @return array{body: array, failure: ?string} + */ + private function body(): array + { + return RequestInput::plainBody($this->getContentTypes() ?: MediaTypes::ALL); } } diff --git a/src/Params/HeaderBag.php b/src/Params/HeaderBag.php index 49da74153..308431360 100644 --- a/src/Params/HeaderBag.php +++ b/src/Params/HeaderBag.php @@ -9,6 +9,12 @@ */ final class HeaderBag { + /** @var array|null the $_SERVER the headers were read from */ + private static ?array $server = null; + + /** @var array */ + private static array $headers = []; + public static function has(string $name): bool { return array_key_exists(strtolower($name), self::all()); @@ -24,6 +30,20 @@ public static function get(string $name): ?string * @return array */ private static function all(): array + { + // read again only when $_SERVER changed, which a copy of the same array tells at no cost + if (self::$server !== $_SERVER) { + self::$server = $_SERVER; + self::$headers = self::read(); + } + + return self::$headers; + } + + /** + * @return array + */ + private static function read(): array { $headers = []; foreach ($_SERVER as $key => $value) { diff --git a/src/Params/ParamsProcessor.php b/src/Params/ParamsProcessor.php index a2b07ede9..3114866f9 100644 --- a/src/Params/ParamsProcessor.php +++ b/src/Params/ParamsProcessor.php @@ -24,7 +24,7 @@ public function isError(): bool $validationResult = $param->validate(); if (!$validationResult->isOk()) { if ($validationResult instanceof FieldErrors) { - foreach ($validationResult->fieldErrors() as $path => $messages) { + foreach ($validationResult->getErrors() as $path => $messages) { $this->errors[$path] = $messages; } continue; diff --git a/src/Presenters/ApiPresenter.php b/src/Presenters/ApiPresenter.php index d7806b118..480ca02df 100644 --- a/src/Presenters/ApiPresenter.php +++ b/src/Presenters/ApiPresenter.php @@ -16,8 +16,10 @@ use Tracy\ILogger; use Tomaj\NetteApi\Api; use Tomaj\NetteApi\ApiDecider; +use Tomaj\NetteApi\EndpointIdentifier; use Tomaj\NetteApi\Authorization\ApiAuthorizationInterface; use Tomaj\NetteApi\Authorization\AuthorizationIdentityInterface; +use Tomaj\NetteApi\Authorization\NoAuthorization; use Tomaj\NetteApi\Authorization\CookieApiKeyAuthentication; use Tomaj\NetteApi\Authorization\HeaderApiKeyAuthentication; use Tomaj\NetteApi\Authorization\QueryApiKeyAuthentication; @@ -323,20 +325,13 @@ public function run(Request $request): IResponse // a body in a media type the typed handler does not accept is answered with 415 after the authorization, // so a client without access learns nothing about the endpoint - $unsupportedMediaType = ''; - $paramsFailure = null; - $paramsProcessor = null; + // as does an exception while the params are read, for example from the constructor of a nested DTO or a caster $params = []; try { $paramsProcessor = new ParamsProcessor($handler->params()); $params = $paramsProcessor->isError() ? [] : $paramsProcessor->getValues(); - } catch (UnsupportedMediaTypeException $exception) { - $unsupportedMediaType = $exception->getMessage(); - $paramsProcessor = null; } catch (Throwable $throwable) { - // for example the constructor of a nested DTO or a caster; answered by the error handler after the authorization - $paramsFailure = $throwable; - $paramsProcessor = null; + $paramsProcessor = $throwable; } $authResponse = $this->checkAuth($authorization, $params); @@ -356,15 +351,10 @@ public function run(Request $request): IResponse return $rateLimitResponse; } - if ($paramsFailure !== null) { - $response = $this->errorHandler->handle($paramsFailure, $params); - $this->logResponse($request, $response->getCode(), $start, $ip); - $this->response->setCode($response->getCode()); - return $response; - } - - if ($paramsProcessor === null) { - $response = $this->errorHandler->handleUnsupportedMediaType($unsupportedMediaType); + if ($paramsProcessor instanceof Throwable) { + $response = $paramsProcessor instanceof UnsupportedMediaTypeException + ? $this->errorHandler->handleUnsupportedMediaType($paramsProcessor->getMessage()) + : $this->errorHandler->handle($paramsProcessor, $params); $this->logResponse($request, $response->getCode(), $start, $ip); $this->response->setCode($response->getCode()); return $response; @@ -435,32 +425,40 @@ private function getApi(Request $request): Api $version = TypeHelper::toString($request->getParameter('version')); $package = TypeHelper::toString($request->getParameter('package')); $apiAction = $request->getParameter('apiAction') === null ? null : TypeHelper::toString($request->getParameter('apiAction')); + $params = $request->getParameter('params') === null ? null : TypeHelper::toString($request->getParameter('params')); // segments after the action are swallowed by the route's : a static endpoint for the shorter URL must not // answer them when a URL template matches the whole path, for example users/me/detail with users/{id}/detail - $extraSegments = TypeHelper::toString($request->getParameter('params') ?? '') !== ''; + $extraSegments = $params !== null && $params !== ''; if ($extraSegments) { - $templated = $this->apiDecider->matchPath($method, $version, $package, $apiAction, $this->requestPath()); + $templated = $this->matchPath($method, $version, $package, $apiAction, $params); if ($templated !== null) { return $templated; } } $api = $this->apiDecider->getApi($method, $version, $package, $apiAction); + if (str_contains($api->getEndpoint()->getUrl(), '{')) { + // getApi() found a template by its literal URL, so the request holds "{id}" as a value; it is matched as one + $api = new Api(new EndpointIdentifier($method, $version, $package, $apiAction), new DefaultHandler(), new NoAuthorization()); + } if (!$extraSegments && $api->getHandler() instanceof DefaultHandler) { // a static endpoint wins; only then are the URL templates of the endpoints tried - return $this->apiDecider->matchPath($method, $version, $package, $apiAction, $this->requestPath()) ?? $api; + return $this->matchPath($method, $version, $package, $apiAction, $params) ?? $api; } return $api; } - private function requestPath(): ?string + private function matchPath(string $method, string $version, string $package, ?string $apiAction, ?string $params): ?Api { - // without an http request service (for example in a CLI or a test container) templates are matched without a path + // the router decodes the path, so an encoded slash (%2F) inside a value would split it into two segments $httpRequest = $this->context->getByType(IRequest::class, false); + if ($httpRequest instanceof IRequest && stripos($httpRequest->getUrl()->getPath(), '%2F') !== false) { + return null; + } - return $httpRequest instanceof IRequest ? $httpRequest->getUrl()->getPath() : null; + return $this->apiDecider->matchPath($method, $version, $package, $apiAction, $params); } /** diff --git a/src/ValidationResult/FieldErrors.php b/src/ValidationResult/FieldErrors.php index b29d79e0c..92d236ba9 100644 --- a/src/ValidationResult/FieldErrors.php +++ b/src/ValidationResult/FieldErrors.php @@ -30,12 +30,4 @@ public function getErrors(): array { return $this->errors; } - - /** - * @return array> - */ - public function fieldErrors(): array - { - return $this->errors; - } } diff --git a/tests/ApiDeciderTest.php b/tests/ApiDeciderTest.php index 182f31384..8456c2cc8 100644 --- a/tests/ApiDeciderTest.php +++ b/tests/ApiDeciderTest.php @@ -12,6 +12,7 @@ use Tomaj\NetteApi\Handlers\AlwaysOkHandler; use Tomaj\NetteApi\Handlers\CorsPreflightHandler; use Tomaj\NetteApi\Handlers\DefaultHandler; +use Tomaj\NetteApi\Params\PathInputParam; final class ApiDeciderTest extends TestCase { @@ -34,7 +35,7 @@ public function testDefaultHandlerWithNoRegisteredHandlers(): void $this->assertInstanceOf(DefaultHandler::class, $result->getHandler()); } - public function testAPlainHandlerOnAStaticUrlIsNotAskedForItsParams(): void + public function testThePathParamsOfAHandlerAreCheckedOnce(): void { $handler = new class extends AlwaysOkHandler { public int $calls = 0; @@ -49,15 +50,70 @@ public function params(): array $apiDecider->addApi(new EndpointIdentifier('GET', 1, 'users', 'list'), $handler, new NoAuthorization()); $this->assertSame($handler, $apiDecider->getApi('GET', '1', 'users', 'list')->getHandler()); - $this->assertSame(0, $handler->calls, 'the presenter reads params() once, the lookup must not add a call'); + $this->assertSame($handler, $apiDecider->getApi('GET', '1', 'users', 'list')->getHandler()); + $this->assertSame(1, $handler->calls, 'the configuration is checked once, not on every request'); + } + + public function testParamsThatCannotBeReadYetAreCheckedOnTheNextLookup(): void + { + $handler = new class extends AlwaysOkHandler { + public int $calls = 0; + + public function params(): array + { + if (++$this->calls === 1) { + throw new \RuntimeException('not ready'); + } + return [new PathInputParam('id')]; + } + }; + $apiDecider = new ApiDecider($this->container); + $apiDecider->addApi(new EndpointIdentifier('GET', 1, 'users', 'list'), $handler, new NoAuthorization()); + + $this->assertSame($handler, $apiDecider->getApi('GET', '1', 'users', 'list')->getHandler(), 'the presenter answers the exception after the authorization'); + $this->expectException(\LogicException::class); + $this->expectExceptionMessage("the endpoint URL 'v1/users/list' and its path parameters do not match"); + $apiDecider->getApi('GET', '1', 'users', 'list'); + } + + public function testAPathParamOfAPlainHandlerNeedsItsSegmentInTheUrl(): void + { + $handler = new class extends AlwaysOkHandler { + public function params(): array + { + return [new PathInputParam('id')]; + } + }; + $apiDecider = new ApiDecider($this->container); + $apiDecider->addApi(new EndpointIdentifier('GET', 1, 'users', 'detail'), $handler, new NoAuthorization()); + + $this->expectException(\LogicException::class); + $this->expectExceptionMessage('The URL has {} and the handler declares [id]'); + $apiDecider->getApis(); } - public function testALiteralPlaceholderInTheRequestDoesNotMatchATemplate(): void + public function testAMalformedTemplateIsRefusedWhenItIsAdded(): void { $apiDecider = new ApiDecider($this->container); - $apiDecider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id}'), new AlwaysOkHandler(), new NoAuthorization()); - $this->assertInstanceOf(DefaultHandler::class, $apiDecider->getApi('GET', '1', 'users', '{id}')->getHandler()); + $this->expectException(\LogicException::class); + $this->expectExceptionMessage("GET v1/users/{id: '{id' is not a path parameter in the endpoint URL 'v1/users/{id'."); + $apiDecider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id'), AlwaysOkHandler::class, new NoAuthorization()); + } + + public function testAnEndpointWithATemplateIsFoundByItsLiteralUrl(): void + { + $handler = new class extends AlwaysOkHandler { + public function params(): array + { + return [new PathInputParam('id')]; + } + }; + $apiDecider = new ApiDecider($this->container); + $apiDecider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), $handler, new NoAuthorization()); + + // the API console opens the endpoint like this + $this->assertSame($handler, $apiDecider->getApi('GET', '1', 'users', '{id}/detail')->getHandler()); } public function testFindRightHandler(): void diff --git a/tests/DI/TypedInputExtensionTest.php b/tests/DI/TypedInputExtensionTest.php index 980d04df5..b7ae3ebbc 100644 --- a/tests/DI/TypedInputExtensionTest.php +++ b/tests/DI/TypedInputExtensionTest.php @@ -98,7 +98,7 @@ public function testContainerInstallsSerializedMetadataAndUnpacksItOnFirstUse(): $container = new $match[1](); $this->assertInstanceOf(Container::class, $container); $container->initialize(); - $this->assertTrue(DtoMetadataRegistry::installs(ScheduleHandler::class)); + $this->assertContains(ScheduleHandler::class, self::installedHandlers()); $unpacked = new \ReflectionProperty(DtoMetadataRegistry::class, 'metadata'); $this->assertSame([], $unpacked->getValue(), 'nothing is unserialized until a handler is used'); @@ -130,9 +130,9 @@ public function testExtensionInstallsTypedHandlersAndTheirFiles(): void - {method: POST, version: 1, package: orders, handler: Tomaj\NetteApi\Test\Input\Fixtures\CreateOrderHandler()} NEON); $container->initialize(); - $this->assertTrue(DtoMetadataRegistry::installed()); - $this->assertTrue(DtoMetadataRegistry::installs(ListUsersHandler::class)); - $this->assertTrue(DtoMetadataRegistry::installs(CreateOrderHandler::class)); + $this->assertNotSame([], self::installedHandlers()); + $this->assertContains(ListUsersHandler::class, self::installedHandlers()); + $this->assertContains(CreateOrderHandler::class, self::installedHandlers()); $urls = []; foreach ($container->getByType(ApiDecider::class)->getApis() as $api) { $urls[] = $api->getEndpoint()->getUrl(); @@ -143,7 +143,7 @@ public function testExtensionInstallsTypedHandlersAndTheirFiles(): void DtoMetadataRegistry::reset(); $empty = ContainerFactory::create("api:\n endpoints: []\n"); $empty->initialize(); - $this->assertFalse(DtoMetadataRegistry::installed()); + $this->assertSame([], self::installedHandlers()); $compiler = new Compiler(); $compiler->addExtension('api', new NetteApiExtension()); @@ -169,7 +169,7 @@ public function testBackslashHandlerIsInstalledUnderItsRealName(): void - {method: GET, version: 1, package: people, action: list, handler: \Tomaj\NetteApi\Test\Input\Fixtures\ListUsersHandler} NEON); $container->initialize(); - $this->assertTrue(DtoMetadataRegistry::installs(ListUsersHandler::class)); + $this->assertContains(ListUsersHandler::class, self::installedHandlers()); } public function testContainerKeepsTypedHandlersAfterAPlainOneAndRejectsOverlap(): void @@ -184,8 +184,8 @@ public function testContainerKeepsTypedHandlersAfterAPlainOneAndRejectsOverlap() - {method: POST, version: 1, package: notes, handler: \Tomaj\NetteApi\Test\Input\Fixtures\Separate\NoteHandler()} NEON); $container->initialize(); - $this->assertTrue(DtoMetadataRegistry::installs(ListUsersHandler::class)); - $this->assertTrue(DtoMetadataRegistry::installs(NoteHandler::class)); + $this->assertContains(ListUsersHandler::class, self::installedHandlers()); + $this->assertContains(NoteHandler::class, self::installedHandlers()); $this->assertInstanceOf(AlwaysOkHandler::class, $container->getByType(AlwaysOkHandler::class)); $compiler = new Compiler(); @@ -212,6 +212,14 @@ public function testContainerKeepsTypedHandlersAfterAPlainOneAndRejectsOverlap() - {method: GET, version: 1, package: users, action: '{slug}', handler: Tomaj\NetteApi\Test\DI\SlugOnlyHandler} NEON); } + + /** + * @return list + */ + private static function installedHandlers(): array + { + return array_keys((array) new \ReflectionProperty(DtoMetadataRegistry::class, 'installed')->getValue()); + } } #[\Attribute(\Attribute::TARGET_PROPERTY)] diff --git a/tests/Handler/DefaultHandlerTest.php b/tests/Handler/DefaultHandlerTest.php index 950e865b0..5ecc1cb01 100644 --- a/tests/Handler/DefaultHandlerTest.php +++ b/tests/Handler/DefaultHandlerTest.php @@ -10,6 +10,7 @@ use Tomaj\NetteApi\EndpointIdentifier; use Tomaj\NetteApi\Handlers\DefaultHandler; use Nette\Application\LinkGenerator; +use Nette\Application\Routers\RouteList; use Nette\Application\Routers\SimpleRouter; final class DefaultHandlerTest extends TestCase @@ -67,4 +68,15 @@ public function testCreateLink(): void $this->assertSame('http://test/?version=1&package=article&apiAction=detail&page=2&action=default&presenter=Api%3AApi', $defaultHandler->createLink(['page' => 2])); } + + public function testCreateLinkFillsAUrlTemplate(): void + { + $router = new RouteList(); + $router->addRoute('api/v/[/]', 'Api:Api:default'); + $handler = new DefaultHandler(); + $handler->setupLinkGenerator(new LinkGenerator($router, new UrlScript('http://test/'))); + $handler->setEndpointIdentifier(new EndpointIdentifier('GET', '1', 'users', '{id}/detail')); + + $this->assertSame('http://test/api/v1/users/5/detail?page=2', $handler->createLink(['id' => 5, 'page' => 2])); + } } diff --git a/tests/Input/BodyParsingTest.php b/tests/Input/BodyParsingTest.php index 7ef13569b..2ec5a700d 100644 --- a/tests/Input/BodyParsingTest.php +++ b/tests/Input/BodyParsingTest.php @@ -4,6 +4,7 @@ namespace Tomaj\NetteApi\Test\Input; +use Tomaj\NetteApi\Test\Input\Fixtures\CreateOrderHandler; use PHPUnit\Framework\TestCase; use Tomaj\NetteApi\Input\RequestInput; use PHPUnit\Framework\Attributes\DataProvider; @@ -170,13 +171,58 @@ public function testASmallPostFormIsNotParsedAgain(): void $this->assertNull($this->post('application/x-www-form-urlencoded', self::pairs('f', $limit + 1), new BodyFieldHandler())); } - public function testAMultipartPostIsLeftToPhp(): void + public function testAMultipartPostThatReachesTheLimitIsTakenAsCut(): void { $limit = (int) ini_get('max_input_vars'); $_POST = array_fill_keys(array_map(static fn (int $i): string => 'f' . $i, range(1, $limit)), '1'); - // PHP does not give a multipart body back, so a form that was cut cannot be told from a complete one - $this->assertNull($this->post('multipart/form-data; boundary=x', self::pairs('f', $limit + 1), new BodyFieldMultipartHandler())); + // PHP does not give a multipart body back to count it again, so a form at the limit is taken as one PHP cut + $this->assertSame(['body' => ['Too many form fields']], $this->post('multipart/form-data; boundary=x', '', new BodyFieldMultipartHandler())); + } + + public function testAMultipartPostUnderTheLimitIsAccepted(): void + { + $limit = (int) ini_get('max_input_vars'); + // max_input_vars counts the values, not the arrays that hold them + $_POST = ['a' => 'x', 'list' => array_fill(0, $limit - 2, '1')]; + + $this->assertNull($this->post('multipart/form-data; boundary=x', '', new BodyFieldMultipartHandler())); + } + + public function testARequestWithoutABodyIsNotRejectedForItsContentType(): void + { + $this->assertNull($this->post('text/plain', '', new OptionalHandler())); + } + + public function testABodyInAnotherMediaTypeIsRejected(): void + { + foreach ([ + 'raw body' => static fn () => RequestInput::setRawBody('x'), + 'form fields' => static function (): void { + $_POST = ['a' => 'x']; + }, + 'files' => static function (): void { + $_FILES = ['a' => ['name' => 'a.txt', 'error' => UPLOAD_ERR_OK]]; + }, + ] as $case => $fill) { + [$_POST, $_FILES] = [[], []]; + RequestInput::setRawBody(''); + $_SERVER['CONTENT_TYPE'] = 'text/plain'; + $_SERVER['REQUEST_METHOD'] = 'POST'; + $fill(); + try { + new ParamsProcessor(new OptionalHandler()->params())->isError(); + $this->fail($case . ' was accepted'); + } catch (UnsupportedMediaTypeException $exception) { + $this->assertStringContainsString("Content-Type 'text/plain' is not supported", $exception->getMessage(), $case); + } + } + } + + public function testARequiredBodyInAnotherMediaTypeIsRejectedEvenWhenEmpty(): void + { + $this->expectException(UnsupportedMediaTypeException::class); + $this->post('text/plain', '', new CreateOrderHandler()); } public function testAJsonCharsetOtherThanUtf8IsRejected(): void diff --git a/tests/Input/CasterTest.php b/tests/Input/CasterTest.php index 36a17e1ad..cf5ba7cdc 100644 --- a/tests/Input/CasterTest.php +++ b/tests/Input/CasterTest.php @@ -128,10 +128,23 @@ public function testNamedCasterArgumentsSurviveTheCompiledContainer(): void $this->assertSame('integer', $imported->fields[0]->casterSchema['type'] ?? null); DtoMetadataRegistry::install([NamedCasterHandler::class => serialize(DtoCompiler::compile(NamedCasterHandler::class))]); - $this->assertTrue(DtoMetadataRegistry::installs(NamedCasterHandler::class)); $this->assertSame(['value' => 'STARTXEND', 'other' => 'AYB'], $this->payload(new NamedCasterHandler())); } + public function testOneCasterInstanceServesEveryValueOfItsField(): void + { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_SERVER['CONTENT_TYPE'] = 'application/json'; + RequestInput::setRawBody('{"items":[{"name":"a"},{"name":"b"},{"name":"c"}],"title":"x"}'); + $handler = new CountedHandler(); + // compiling checks the caster arguments by constructing it + DtoMetadataRegistry::forHandler(CountedHandler::class); + CountingCaster::$instances = 0; + + $this->assertSame(['names' => ['a!', 'b!', 'c!'], 'title' => 'x?'], $this->payload($handler)); + $this->assertSame(2, CountingCaster::$instances, 'one per field, not one per list item'); + } + public function testNulByteIsAFieldError(): void { try { @@ -327,3 +340,45 @@ public function handleDto(WireSchemaInput $input): ResponseInterface return new JsonApiResponse(200, []); } } + +final class CountingCaster implements CasterInterface +{ + public static int $instances = 0; + + public function __construct(private readonly string $suffix) + { + self::$instances++; + } + + public function cast(mixed $value): string + { + return (is_string($value) ? $value : '') . $this->suffix; + } +} + +final readonly class CountedItem +{ + public function __construct(#[Body] #[Cast(CountingCaster::class, '!')] public string $name) + { + } +} + +final readonly class CountedInput +{ + /** + * @param list $items + */ + public function __construct( + #[Body] public array $items, + #[Body] #[Cast(CountingCaster::class, '?')] public string $title, + ) { + } +} + +final class CountedHandler extends TypedHandler +{ + public function handleDto(CountedInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['names' => array_map(static fn (CountedItem $item): string => $item->name, $input->items), 'title' => $input->title]); + } +} diff --git a/tests/Input/DtoHandlerTest.php b/tests/Input/DtoHandlerTest.php index 3d6b9e02a..e603ab20c 100644 --- a/tests/Input/DtoHandlerTest.php +++ b/tests/Input/DtoHandlerTest.php @@ -33,8 +33,24 @@ final class DtoHandlerTest extends TestCase { + /** @var array */ + private array $server = []; + + protected function tearDown(): void + { + $_SERVER = $this->server; + $_GET = []; + $_POST = []; + $_FILES = []; + RequestInput::reset(); + RequestInput::setRawBody(null); + PathValues::reset(); + DtoMetadataRegistry::reset(); + } + protected function setUp(): void { + $this->server = $_SERVER; $_GET = []; $_POST = []; $_FILES = []; @@ -513,7 +529,7 @@ public function testConstraintAndBodyErrorsStayOnTheirFields(): void $this->assertArrayNotHasKey('body', $bodyErrors['address'] ?? []); RequestInput::reset(); - RequestInput::reset(); + RequestInput::setRawBody(null); $_GET = ['page' => '1a']; $both = $this->errors(new QueryThenBodyHandler()); $this->assertArrayHasKey('page', $both); diff --git a/tests/Input/DtoMetadataTest.php b/tests/Input/DtoMetadataTest.php index 25a55efe8..0153884b8 100644 --- a/tests/Input/DtoMetadataTest.php +++ b/tests/Input/DtoMetadataTest.php @@ -91,10 +91,15 @@ public function testHandlerAndDtoFilesAreBothRecorded(): void public function testEveryReflectedDependencyRebuildsTheContainer(): void { $files = array_map(basename(...), DtoCompiler::compileWithFiles(DependencyHandler::class)['files']); - foreach (['DependencyHandler.php', 'DependencyInput.php', 'DependencyParentInput.php', 'DependencyCaster.php', 'DependencyEnum.php', 'DependencyItemEnum.php', 'DependencyConstraint.php', 'DependencyTrait.php', 'DependencyNestedTrait.php', 'DependencyParentTrait.php'] as $file) { + foreach (['DependencyHandler.php', 'DependencyInput.php', 'DependencyParentInput.php', 'DependencyCaster.php', 'DependencyEnum.php', 'DependencyItemEnum.php', 'DependencyConstraint.php', 'DependencyTrait.php', 'DependencyNestedTrait.php', 'DependencyParentTrait.php', 'DependencyLimits.php', 'DependencyDefaults.php', 'DependencyLabels.php'] as $file) { $this->assertContains($file, $files); } + // a constant read in an attribute or a default is copied into the metadata; a static call is not + $this->assertNotContains('DependencyUnused.php', $files); $this->assertSame(array_values(array_unique($files)), $files); + foreach (DtoCompiler::compileWithFiles(DependencyHandler::class)['files'] as $file) { + $this->assertFileExists($file); + } } public function testSameInstanceIsReusedUntilReset(): void @@ -106,9 +111,7 @@ public function testSameInstanceIsReusedUntilReset(): void $installed = new DtoMetadata($first->handler, $first->class, $first->fields, $first->contentTypes, $first->bodyRequired, $first->readsBody, 'from-install'); DtoMetadataRegistry::reset(); DtoMetadataRegistry::install([ListUsersHandler::class => serialize($installed)]); - $this->assertTrue(DtoMetadataRegistry::installs(ListUsersHandler::class)); $this->assertSame('from-install', DtoMetadataRegistry::forHandler(ListUsersHandler::class)->firstBody); - $this->assertFalse(DtoMetadataRegistry::installs(CreateOrderHandler::class)); $this->assertSame(CreateOrderHandler::class, DtoMetadataRegistry::forHandler(CreateOrderHandler::class)->handler); } } diff --git a/tests/Input/DtoPhpDocTest.php b/tests/Input/DtoPhpDocTest.php index 0690b2a44..0b4f9eeb1 100644 --- a/tests/Input/DtoPhpDocTest.php +++ b/tests/Input/DtoPhpDocTest.php @@ -11,6 +11,11 @@ use Tomaj\NetteApi\Input\DtoCompiler; use Tomaj\NetteApi\Input\Field; use Tomaj\NetteApi\Input\Query; +use Tomaj\NetteApi\Input\RequestInput; +use Tomaj\NetteApi\Params\ParamsProcessor; +use Tomaj\NetteApi\Test\Input\TraitFixtures\Items\LineItem; +use Tomaj\NetteApi\Test\Input\TraitFixtures\TraitHandlers; +use Tomaj\NetteApi\Test\Input\TraitFixtures\TraitOrderHandler; use Tomaj\NetteApi\Response\JsonApiResponse; use Tomaj\NetteApi\Response\ResponseInterface; @@ -31,6 +36,22 @@ public function testEveryCommonPhpDocSpellingOfAListIsRead(): void ); } + public function testAListDocumentedInATraitResolvesInTheFileOfTheTrait(): void + { + foreach (TraitHandlers::all() as $handler) { + $this->assertSame(LineItem::class, DtoCompiler::compile($handler)->fields[0]->listItem, $handler); + } + + RequestInput::reset(); + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_SERVER['CONTENT_TYPE'] = 'application/json'; + RequestInput::setRawBody('{"items":[{"sku":"A"},{"sku":"B"}]}'); + $handler = new TraitOrderHandler(); + $processor = new ParamsProcessor($handler->params()); + $this->assertFalse($processor->isError()); + $this->assertSame(['skus' => ['A', 'B']], $handler->handle($processor->getValues())->getPayload()); + } + /** * @return \Iterator, string}> */ diff --git a/tests/Input/DtoPropertyTypeTest.php b/tests/Input/DtoPropertyTypeTest.php index 379883f95..81278f505 100644 --- a/tests/Input/DtoPropertyTypeTest.php +++ b/tests/Input/DtoPropertyTypeTest.php @@ -102,6 +102,8 @@ public static function invalid(): \Iterator yield 'empty body name' => [EmptyBodyHandler::class, "for example #[Body('my_name')]"]; yield 'empty header name' => [EmptyHeaderHandler::class, "for example #[Header('X-Request-Id')]"]; yield 'name that starts with a digit' => [DigitNameHandler::class, 'must start with a letter or an underscore']; + yield 'field named body' => [BodyNamedHandler::class, 'Tomaj\\NetteApi\\Test\\Input\\BodyNamedInput::$text is read as \'body\', the key under which errors of the request as a whole are reported. Give it another input name, for example #[Body(\'payload\')].']; + yield 'query named body' => [QueryNamedBodyHandler::class, "for example #[Query('payload')]"]; } /** @@ -804,3 +806,33 @@ public function handleDto(PureEnumListInput $input): ResponseInterface return new JsonApiResponse(200, []); } } + +final readonly class BodyNamedInput +{ + public function __construct(#[Body('body')] public string $text) + { + } +} + +final class BodyNamedHandler extends TypedHandler +{ + public function handleDto(BodyNamedInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class QueryNamedBodyInput +{ + public function __construct(#[Query] public ?string $page = null, #[Query] public ?string $body = null) + { + } +} + +final class QueryNamedBodyHandler extends TypedHandler +{ + public function handleDto(QueryNamedBodyInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} diff --git a/tests/Input/EndpointTemplateTest.php b/tests/Input/EndpointTemplateTest.php index 25bec1fc9..5dc8a1e20 100644 --- a/tests/Input/EndpointTemplateTest.php +++ b/tests/Input/EndpointTemplateTest.php @@ -9,14 +9,11 @@ final class EndpointTemplateTest extends TestCase { - public function testMatchAndNormalize(): void + public function testMatch(): void { $this->assertSame(['id' => '42'], EndpointTemplate::match('v1/users/{id}/detail', 'v1/users/42/detail')); - $this->assertSame(['id' => '42'], EndpointTemplate::match('v1/users/{id}/detail/', EndpointTemplate::normalize('/api/v1/users/42/detail?x=1', '1'))); $this->assertNull(EndpointTemplate::match('v1/users/{id}/detail', 'v1/users/42')); $this->assertNull(EndpointTemplate::match('v1/users/{id}', 'v1/orders/42')); - $this->assertSame('v1/users/42', EndpointTemplate::normalize('v1/users/42', '1')); - $this->assertNull(EndpointTemplate::normalize('/api/v2/users', '1')); $this->assertSame(['id'], EndpointTemplate::placeholders('v1/users/{id}/detail')); $this->assertSame([], EndpointTemplate::placeholders('v1/users/x{id}')); $this->assertSame([], EndpointTemplate::placeholders('v1/users/{id}x')); @@ -32,18 +29,34 @@ public function testMatchAndNormalize(): void $this->assertFalse(EndpointTemplate::isComposite('users/detail')); $this->assertFalse(EndpointTemplate::isComposite('{id-1}/detail')); $this->assertFalse(EndpointTemplate::isComposite('{id}/detail ')); - $this->assertNull(EndpointTemplate::normalize('/api/v12/users', '1')); - $this->assertSame('v12/users', EndpointTemplate::normalize('/api/v12/users', '12')); - $this->assertSame('v1', EndpointTemplate::normalize('/v1', '1')); - $this->assertNull(EndpointTemplate::normalize('/api/v1extra', '1')); } - public function testAnEncodedSlashStaysInsideItsValue(): void + public function testThePathIsComparedAsTheRouterDecodedIt(): void { - $this->assertSame(['id' => 'a/b'], EndpointTemplate::match('v1/users/{id}', EndpointTemplate::normalize('/api/v1/users/a%2Fb', '1'))); - $this->assertNull(EndpointTemplate::match('v1/users/{id}/detail', EndpointTemplate::normalize('/api/v1/users/a%2Fdetail', '1'))); - $this->assertSame(['id' => 'a b'], EndpointTemplate::match('v1/users/{id}/detail', EndpointTemplate::normalize('/api/v1/users/a%20b/detail', '1'))); - $this->assertSame(['id' => '1'], EndpointTemplate::match('v1/users/{id}', 'v1/us%65rs/1'), 'a static segment is compared decoded'); + $this->assertSame(['id' => 'a b'], EndpointTemplate::match('users/{id}/detail', 'users/a b/detail')); + $this->assertSame(['id' => '%41'], EndpointTemplate::match('users/{id}', 'users/%41'), 'not decoded twice'); + $this->assertNull(EndpointTemplate::match('users/{id}', 'us%65rs/1')); + } + + public function testFillEncodesTheValuesAndReturnsTheUnusedOnes(): void + { + $this->assertSame(['users/a%20b/detail', ['q' => 1]], EndpointTemplate::fill('users/{id}/detail', ['id' => 'a b', 'q' => 1])); + $this->assertSame(['users/{id}', ['id' => ['x']]], EndpointTemplate::fill('users/{id}', ['id' => ['x']])); + $this->assertSame(['users/7/0', []], EndpointTemplate::fill('users/{id}/{page}', ['id' => 7, 'page' => 0])); + $this->assertSame(['users/{id}', ['id' => null]], EndpointTemplate::fill('users/{id}', ['id' => null])); + } + + public function testFillRejectsAValueThatLeadsElsewhere(): void + { + foreach (['', '.', '..', 'a/b'] as $value) { + try { + EndpointTemplate::fill('users/{id}', ['id' => $value]); + $this->fail($value); + } catch (\InvalidArgumentException $exception) { + $this->assertSame(sprintf("Path value 'id' cannot be '%s'. Use a non-empty value without a slash that is not '.' or '..'.", $value), $exception->getMessage()); + } + } + $this->assertSame(['users/..a', []], EndpointTemplate::fill('users/{id}', ['id' => '..a'])); } public function testAssertNamesTheMismatch(): void @@ -83,7 +96,6 @@ public function testOverlap(): void public function testEndpointMessagesUseTheRealUrl(): void { - $this->assertSame('v1/users', EndpointTemplate::normalize('/api/v1/users/', '1')); foreach (['v1/x{id}', 'v1/{id}x'] as $url) { try { EndpointTemplate::assert($url, [], 'Handler'); diff --git a/tests/Input/FileUploadTest.php b/tests/Input/FileUploadTest.php index b77273b21..1e4cc9cdf 100644 --- a/tests/Input/FileUploadTest.php +++ b/tests/Input/FileUploadTest.php @@ -26,8 +26,23 @@ final class FileUploadTest extends TestCase { + /** @var array */ + private array $server = []; + + protected function tearDown(): void + { + $_SERVER = $this->server; + $_GET = []; + $_POST = []; + $_FILES = []; + RequestInput::reset(); + RequestInput::setRawBody(null); + PathValues::reset(); + } + protected function setUp(): void { + $this->server = $_SERVER; $_GET = []; $_POST = []; $_FILES = []; @@ -231,11 +246,11 @@ public function testListWithOneFileIsAList(): void $this->assertSame(['count' => 1, 'name' => 'only.txt'], $this->payload(new FilesHandler())); } - public function testListKeepsAMixOfEmptyAndRealSlots(): void + public function testListLeavesOutTheInputsTheClientLeftEmpty(): void { $_POST = ['issuedOn' => '24.12.2026', 'copies' => '1']; - $_FILES = ['attachments' => self::files(['', 'b.txt'], [UPLOAD_ERR_NO_FILE, UPLOAD_ERR_OK])]; - $this->assertSame([['', UPLOAD_ERR_NO_FILE], ['b.txt', UPLOAD_ERR_OK]], $this->payload(new DocumentHandler())['attachments']); + $_FILES = ['attachments' => self::files(['', 'b.txt', '', 'big.txt'], [UPLOAD_ERR_NO_FILE, UPLOAD_ERR_OK, UPLOAD_ERR_NO_FILE, UPLOAD_ERR_INI_SIZE])]; + $this->assertSame([['b.txt', UPLOAD_ERR_OK], ['big.txt', UPLOAD_ERR_INI_SIZE]], $this->payload(new DocumentHandler())['attachments']); } /** diff --git a/tests/Input/Fixtures/Dependency/DependencyDefaults.php b/tests/Input/Fixtures/Dependency/DependencyDefaults.php new file mode 100644 index 000000000..6bfd33bd8 --- /dev/null +++ b/tests/Input/Fixtures/Dependency/DependencyDefaults.php @@ -0,0 +1,10 @@ + + */ + public function cast(mixed $value): array + { + return array_map(static fn (string $sku): LineItem => new LineItem($sku), explode(',', is_string($value) ? $value : '')); + } +} diff --git a/tests/Input/TraitFixtures/Lib/NestedFields.php b/tests/Input/TraitFixtures/Lib/NestedFields.php new file mode 100644 index 000000000..fc38ac580 --- /dev/null +++ b/tests/Input/TraitFixtures/Lib/NestedFields.php @@ -0,0 +1,11 @@ + $items + */ + public function __construct(#[Body] public readonly array $items) + { + } +} diff --git a/tests/Input/TraitFixtures/Lib/TagFields.php b/tests/Input/TraitFixtures/Lib/TagFields.php new file mode 100644 index 000000000..b999d8ccd --- /dev/null +++ b/tests/Input/TraitFixtures/Lib/TagFields.php @@ -0,0 +1,17 @@ + */ + #[Body] public readonly array $tags, + ) { + } +} diff --git a/tests/Input/TraitFixtures/TraitHandlers.php b/tests/Input/TraitFixtures/TraitHandlers.php new file mode 100644 index 000000000..d0a637d5d --- /dev/null +++ b/tests/Input/TraitFixtures/TraitHandlers.php @@ -0,0 +1,85 @@ + is resolved in the file of the trait that documents it + +final class TraitOrderInput +{ + use OrderFields; +} + +final class NestedTraitOrderInput +{ + use NestedFields; +} + +final class TraitTagInput +{ + use TagFields; +} + +final readonly class TraitCastInput +{ + /** + * @param list $items + */ + public function __construct(#[Body] #[Cast(ItemsCaster::class)] public array $items) + { + } +} + +final class TraitHandlers +{ + /** + * @return list> + */ + public static function all(): array + { + return [TraitOrderHandler::class, NestedTraitOrderHandler::class, TraitTagHandler::class, TraitCastHandler::class]; + } +} + +final class TraitOrderHandler extends TypedHandler +{ + public function handleDto(TraitOrderInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['skus' => array_map(static fn (object $item): mixed => get_object_vars($item)['sku'], $input->items)]); + } +} + +final class NestedTraitOrderHandler extends TypedHandler +{ + public function handleDto(NestedTraitOrderInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['count' => count($input->items)]); + } +} + +final class TraitTagHandler extends TypedHandler +{ + public function handleDto(TraitTagInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['count' => count($input->tags)]); + } +} + +final class TraitCastHandler extends TypedHandler +{ + public function handleDto(TraitCastInput $input): ResponseInterface + { + return new JsonApiResponse(200, ['count' => count($input->items)]); + } +} diff --git a/tests/Input/TypeNameTest.php b/tests/Input/TypeNameTest.php index 921ef5ef7..2ae998a97 100644 --- a/tests/Input/TypeNameTest.php +++ b/tests/Input/TypeNameTest.php @@ -4,8 +4,12 @@ namespace Tomaj\NetteApi\Test\Input; +use Tomaj\NetteApi\Test\Input\Fixtures\Dependency\DependencyLimits; +use Tomaj\NetteApi\Test\Input\Fixtures\Dependency\DependencyDefaults; use FooEval\Bar; use PHPUnit\Framework\TestCase; +use Tomaj\NetteApi\Test\Input\Fixtures\Dependency\DependencyParentInput; +use Tomaj\NetteApi\Test\Input\Fixtures\Dependency\DependencyTrait; use Tomaj\NetteApi\Input\Body; use Tomaj\NetteApi\Input\File; use Tomaj\NetteApi\Input\Query; @@ -129,6 +133,21 @@ class K { use T; } $this->assertSame(['thing' => 'Global\Thing'], TypeName::importsOf($code, '')); } + public function testAClosureOutsideAClassIsNotAnImport(): void + { + $code = 'assertSame(['first' => 'A\\First', 'second' => 'B\\Second'], TypeName::importsOf($code, 'N')); + } + + public function testConstantClassesListsTheClassesWhoseConstantsAreRead(): void + { + $this->assertSame([ + DependencyLimits::class, + DependencyDefaults::class, + ], TypeName::constantClasses(new \ReflectionClass(DependencyParentInput::class))); + $this->assertSame(['Tomaj\\NetteApi\\Test\\Input\\Fixtures\\Dependency\\self'], TypeName::constantClasses(new \ReflectionClass(DependencyTrait::class)), 'a static call is left out, self is dropped by the caller'); + } + public function testDollarBraceInterpolationKeepsTheDepth(): void { $code = 'link(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), ['id' => 'a/b c', 'q' => 1]); + $link = ApiFixtures::apiLink()->link(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), ['id' => 'a b', 'q' => 1, 'package' => 'ignored']); - $this->assertSame('https://example.com/api/v1/users/a%2Fb%20c/detail?q=1', $link); + $this->assertSame('https://example.com/api/v1/users/a%20b/detail?q=1', $link); } public function testATemplateWithoutAValueStaysLiteral(): void @@ -48,6 +52,7 @@ public static function valuesThatLeadElsewhere(): \Iterator yield 'dot' => ['.']; yield 'dot dot' => ['..']; yield 'false' => [false]; + yield 'slash' => ['a/b']; } #[DataProvider('valuesThatLeadElsewhere')] @@ -55,7 +60,27 @@ public function testAPathValueThatWouldLeadElsewhereIsRejected(mixed $value): vo { $endpoint = new EndpointIdentifier('GET', 1, 'users', '{id}/detail'); $this->expectException(InvalidLinkException::class); - $this->expectExceptionMessage(sprintf("Path value 'id' of GET %s cannot be '%s'.", $endpoint->getUrl(), is_scalar($value) ? (string) $value : '')); + $this->expectExceptionMessage(sprintf("Cannot build a link for GET %s. Path value 'id' cannot be '%s'.", $endpoint->getUrl(), is_scalar($value) ? (string) $value : '')); ApiFixtures::apiLink()->link($endpoint, ['id' => $value]); } + + public function testATemplateLinkDoesNotNeedAVersionPrefixInTheRouteMask(): void + { + $router = new RouteList(); + $router->addRoute('rest//[/]', 'Api:Api:default'); + $link = new ApiLink(new LinkGenerator($router, new UrlScript('https://example.com/'))); + + $this->assertSame('https://example.com/rest/2/users/7/detail', $link->link(new EndpointIdentifier('GET', 2, 'users', '{id}/detail'), ['id' => 7])); + } + + public function testARouteThatDoesNotPutThePackageInThePathCannotLinkATemplate(): void + { + $router = new RouteList(); + $router->addRoute('api/', 'Api:Api:default'); + $link = new ApiLink(new LinkGenerator($router, new UrlScript('https://example.com/'))); + + $this->expectException(InvalidLinkException::class); + $this->expectExceptionMessage('Cannot build a link for GET v1/users/{id}. The router mask must have and as path segments'); + $link->link(new EndpointIdentifier('GET', 1, 'users', '{id}'), ['id' => 7]); + } } diff --git a/tests/Misc/ConsoleRequestTest.php b/tests/Misc/ConsoleRequestTest.php index c8f308e26..e6082e8a9 100644 --- a/tests/Misc/ConsoleRequestTest.php +++ b/tests/Misc/ConsoleRequestTest.php @@ -156,9 +156,9 @@ public function testTypedPathAndHeaderGoToTheirSources(): void { $endpoint = new EndpointIdentifier('GET', 1, 'users', '{id}/detail'); $request = new ConsoleRequest(new UserDetailHandler(), $endpoint, self::localLink()); - $response = $request->makeRequest('ignored', 'GET', ['id' => '4/2 x', 'limit' => '5', 'X-Request-Id' => "abc\r\nX-Evil: 1"]); + $response = $request->makeRequest('ignored', 'GET', ['id' => ' 4 2x ', 'limit' => '5', 'X-Request-Id' => "abc\r\nX-Evil: 1"]); - $this->assertSame('http://127.0.0.1:23523/api/v1/users/4%2F2%20x/detail?limit=5', $response->getUrl()); + $this->assertSame('http://127.0.0.1:23523/api/v1/users/4%202x/detail?limit=5', $response->getUrl()); $this->assertSame(['X-Request-Id: abcX-Evil: 1'], $response->getHeaders()); $this->assertSame([], $response->getPostFields()); $this->assertNull($response->getRawPost()); @@ -185,13 +185,13 @@ public function link(EndpointInterface $endpoint, $params = []): string $this->assertStringStartsWith('custom:http://127.0.0.1:23523/api/v1/users/create', $request->makeRequest('ignored', 'POST', [])->getUrl()); } - public function testADotPathValueIsNotSentButExplained(): void + public function testADotPathValueOrASlashIsNotSentButExplained(): void { - foreach (['.' => '.', '..' => '..', ' .. ' => '..'] as $value => $dots) { + foreach (['.' => '.', '..' => '..', ' .. ' => '..', '4/2' => '4/2'] as $value => $dots) { $response = new ConsoleRequest(new UserDetailHandler())->makeRequest('http://127.0.0.1:23523/api/v1/users/{id}/detail', 'GET', ['id' => (string) $value]); $this->assertTrue($response->isError()); - $this->assertSame(sprintf("The path value 'id' cannot be '%s'. Change it and send the request again.", $dots), $response->getErrorMessage()); + $this->assertSame(sprintf("Path value 'id' cannot be '%s'. Use a non-empty value without a slash that is not '.' or '..'. Change it and send the request again.", $dots), $response->getErrorMessage()); } } @@ -202,7 +202,7 @@ public function testABlankPathValueIsNotSentButExplained(): void $response = $request->makeRequest('http://127.0.0.1:23523/api/v1/users/{id}/detail', 'GET', ['id' => $blank, 'limit' => '5']); $this->assertTrue($response->isError()); - $this->assertSame("The path value 'id' is empty. Fill it in and send the request again.", $response->getErrorMessage()); + $this->assertSame("Path value 'id' cannot be ''. Use a non-empty value without a slash that is not '.' or '..'. Change it and send the request again.", $response->getErrorMessage()); $this->assertSame(0, $response->getErrorNumber()); $this->assertSame(0, $response->getResponseTime()); $this->assertSame('http://127.0.0.1:23523/api/v1/users/{id}/detail', $response->getUrl()); diff --git a/tests/OpenApi/RequestBodyBuilderTest.php b/tests/OpenApi/RequestBodyBuilderTest.php index 5e1b358ba..fcf187583 100644 --- a/tests/OpenApi/RequestBodyBuilderTest.php +++ b/tests/OpenApi/RequestBodyBuilderTest.php @@ -293,7 +293,28 @@ public function testListOfObjectsIsDocumentedOnlyAsJson(): void ]), new SchemaRegistry()); $this->assertIsArray($body); $this->assertSame(['application/x-www-form-urlencoded'], array_keys($body['content'])); - $this->assertArrayHasKey('items[]', $body['content']['application/x-www-form-urlencoded']['schema']['properties']); + $form = $body['content']['application/x-www-form-urlencoded']; + $this->assertSame(['items'], array_keys($form['schema']['properties']), 'a list of objects is not a list of scalars, so it is not named items[]'); + $this->assertSame("Sent as form fields in bracket notation (`items[...]`), which OpenAPI 3.0 cannot describe.", $form['schema']['properties']['items']['description']); + $this->assertArrayNotHasKey('encoding', $form); + } + + public function testAFileStaysDocumentedNextToAListOfObjects(): void + { + $items = ['type' => 'array', 'items' => ['type' => 'object', 'properties' => ['sku' => ['type' => 'string']]], 'description' => 'Order lines']; + $body = new RequestBodyBuilder()->build(new ConfigurableHandler([ + new BodyInputParam('items')->setOpenApiSchema($items)->setRequired()->setContentTypes(['application/json', 'application/x-www-form-urlencoded', 'multipart/form-data']), + new FileInputParam('attachment')->setOpenApiSchema(['type' => 'string', 'format' => 'binary']), + new BodyInputParam('note'), + ]), new SchemaRegistry()); + + $this->assertIsArray($body); + $this->assertSame(['application/json', 'multipart/form-data'], array_keys($body['content']), 'multipart is the only way to send the file'); + $this->assertSame(['items', 'note'], array_keys($body['content']['application/json']['schema']['properties'])); + $multipart = $body['content']['multipart/form-data']['schema']; + $this->assertSame(['items', 'attachment', 'note'], array_keys($multipart['properties'])); + $this->assertSame(['items'], $multipart['required']); + $this->assertSame("Order lines\n\nSent as form fields in bracket notation (`items[...]`), which OpenAPI 3.0 cannot describe.", $multipart['properties']['items']['description']); } public function testOpenApiUsesTheDeclaredBodyMediaTypeAndDescription(): void diff --git a/tests/Params/PathHeaderBodyParamTest.php b/tests/Params/PathHeaderBodyParamTest.php index 5bba19f55..b935fd5dc 100644 --- a/tests/Params/PathHeaderBodyParamTest.php +++ b/tests/Params/PathHeaderBodyParamTest.php @@ -6,6 +6,7 @@ use PHPUnit\Framework\TestCase; use Tomaj\NetteApi\Input\RequestInput; +use Tomaj\NetteApi\Input\UnsupportedMediaTypeException; use Tomaj\NetteApi\Params\BodyInputParam; use Tomaj\NetteApi\Params\HeaderInputParam; use Tomaj\NetteApi\Params\PathInputParam; @@ -51,6 +52,8 @@ public function testHeaderIsCaseInsensitive(): void public function testBodyReadsPostAndJson(): void { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; $_POST = ['name' => 'Ada']; $param = new BodyInputParam('name', InputType::STRING); $this->assertSame('Ada', $param->getValue()); @@ -60,19 +63,128 @@ public function testBodyReadsPostAndJson(): void RequestInput::setRawBody('{"name":"Grace","extra":1}'); $this->assertSame('Grace', $param->getValue()); - RequestInput::reset(); - $_SERVER['CONTENT_TYPE'] = 'application/json'; RequestInput::setRawBody('[1,2]'); $empty = new BodyInputParam('name')->setDefault('none'); $this->assertSame('none', $empty->getValue()); + $this->assertSame(['Value must be an object'], $empty->validate()->getErrors()); - RequestInput::reset(); + unset($_SERVER['REQUEST_METHOD']); $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; - $_POST = []; RequestInput::setRawBody('{"name":"from-json"}'); $this->assertSame('none', new BodyInputParam('name')->setDefault('none')->getValue()); } + public function testMalformedJsonIsAnErrorOfTheBodyParam(): void + { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_SERVER['CONTENT_TYPE'] = 'application/json'; + RequestInput::setRawBody('{"limit": 5,,}'); + $param = new BodyInputParam('limit')->setDefault('10'); + $this->assertSame(['Syntax error'], $param->validate()->getErrors()); + + $_SERVER['CONTENT_TYPE'] = 'application/json; charset=latin1'; + $this->assertSame(['JSON must be UTF-8; the request says charset=latin1'], $param->validate()->getErrors()); + + $_SERVER['CONTENT_TYPE'] = 'application/json'; + RequestInput::setRawBody('{"limit": 5}'); + $this->assertTrue($param->validate()->isOk()); + } + + public function testAnExplicitNullIsNotReplacedByTheDefault(): void + { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_SERVER['CONTENT_TYPE'] = 'application/json'; + RequestInput::setRawBody('{"note":null}'); + $this->assertNull(new BodyInputParam('note')->setDefault('fallback')->getValue()); + $this->assertSame(['Field is required'], new BodyInputParam('note')->setRequired()->validate()->getErrors()); + } + + public function testAnUnsupportedMediaTypeIsRejected(): void + { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_SERVER['CONTENT_TYPE'] = 'text/csv'; + RequestInput::setRawBody('a,b'); + $this->expectException(UnsupportedMediaTypeException::class); + $this->expectExceptionMessage("Content-Type 'text/csv' is not supported for this endpoint. Use one of: application/json, application/x-www-form-urlencoded, multipart/form-data."); + new BodyInputParam('note')->getValue(); + } + + public function testDeclaredContentTypesAreTheAcceptedOnes(): void + { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; + $_POST = ['note' => 'hi']; + $this->expectException(UnsupportedMediaTypeException::class); + $this->expectExceptionMessage('Use one of: application/json.'); + new BodyInputParam('note')->setContentTypes(['application/json'])->getValue(); + } + + public function testTheBodyIsReadOncePerRequest(): void + { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_SERVER['CONTENT_TYPE'] = 'application/json'; + RequestInput::setRawBody('{"a":"1","b":"2"}'); + $reads = new \ReflectionProperty(RequestInput::class, 'plain'); + $a = new BodyInputParam('a'); + $this->assertSame('1', $a->getValue()); + $first = $reads->getValue(); + $this->assertSame('2', new BodyInputParam('b')->getValue()); + $this->assertTrue($a->validate()->isOk()); + $this->assertSame($first, $reads->getValue()); + + // the next request through the presenter starts with reset(), a test may change the request without it + RequestInput::reset(); + $this->assertNull($reads->getValue()); + $this->assertSame('1', $a->getValue(), 'reset() keeps a body given by setRawBody()'); + $_SERVER['REQUEST_METHOD'] = 'PUT'; + RequestInput::setRawBody('{"a":"3"}'); + $this->assertSame('3', $a->getValue()); + } + + public function testAnUnchangedRequestIsNotParsedAgain(): void + { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_SERVER['CONTENT_TYPE'] = 'application/json'; + RequestInput::setRawBody('{"a":"1"}'); + $param = new BodyInputParam('a'); + $this->assertSame('1', $param->getValue()); + + // php://input of a real request does not change, the parsed body is reused + new \ReflectionProperty(RequestInput::class, 'rawOverride')->setValue(null, '{"a":"2"}'); + $this->assertSame('1', $param->getValue()); + } + + public function testAnOptionalBodyParamAcceptsARequestWithoutABody(): void + { + $_SERVER['REQUEST_METHOD'] = 'POST'; + RequestInput::setRawBody(''); + $param = new BodyInputParam('a'); + $this->assertNull($param->getValue()); + $this->assertTrue($param->validate()->isOk()); + } + + public function testAChangedRequestIsReadAgain(): void + { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; + $_POST = ['a' => '1']; + $param = new BodyInputParam('a'); + $this->assertSame('1', $param->getValue()); + $_POST = ['a' => '2']; + $this->assertSame('2', $param->getValue()); + + $_POST = []; + RequestInput::setRawBody('a=3'); + $this->assertNull($param->getValue(), 'PHP parsed a POST form already'); + $_SERVER['REQUEST_METHOD'] = 'PATCH'; + $this->assertSame('3', $param->getValue()); + + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $this->assertSame(['Syntax error'], $param->validate()->getErrors()); + $this->expectException(UnsupportedMediaTypeException::class); + $param->setContentTypes(['application/x-www-form-urlencoded'])->getValue(); + } + public function testBodyReadsAPutFormAndTheContentTypeHeaderLikeTypedHandlers(): void { $_SERVER['REQUEST_METHOD'] = 'PUT'; diff --git a/tests/Presenters/ApiPresenterUnsupportedMediaTypeTest.php b/tests/Presenters/ApiPresenterUnsupportedMediaTypeTest.php index 44e25a455..62ad5d9e4 100644 --- a/tests/Presenters/ApiPresenterUnsupportedMediaTypeTest.php +++ b/tests/Presenters/ApiPresenterUnsupportedMediaTypeTest.php @@ -53,7 +53,11 @@ protected function setUp(): void protected function tearDown(): void { $_SERVER = $this->server; + $_POST = []; + $_FILES = []; + RequestInput::setRawBody(null); RequestInput::reset(); + PathValues::reset(); } public function testUnsupportedMediaTypeIsAnsweredWith415AndLogged(): void @@ -211,7 +215,7 @@ public function getByType(string $type, bool $throw = true): ?object return $presenter; } - public function testPresenterDropsAStaleBody(): void + public function testABodySetByATestReachesTheHandlerThroughThePresenter(): void { RequestInput::setRawBody('{"customerEmail":"ada@example.com","address":{"street":"Main","postalCode":"81101"},"items":[{"sku":"A","quantity":1}]}'); $_SERVER['CONTENT_TYPE'] = 'application/json'; @@ -225,6 +229,6 @@ public function testPresenterDropsAStaleBody(): void $presenter->outputConfigurator = new DebuggerConfigurator(); $presenter->errorHandler = new DefaultErrorHandler($presenter->outputConfigurator); $result = $presenter->run(new Request('Api:Api:default', 'POST', ['version' => '1', 'package' => 'orders'])); - $this->assertSame(400, $result->getCode()); + $this->assertSame(200, $result->getCode(), 'the presenter forgets the previous request, not the body a test set'); } } diff --git a/tests/TypedEndpointMatchTest.php b/tests/TypedEndpointMatchTest.php index 53f1efd87..a2b13d389 100644 --- a/tests/TypedEndpointMatchTest.php +++ b/tests/TypedEndpointMatchTest.php @@ -18,6 +18,7 @@ use Tomaj\NetteApi\Params\PathInputParam; use Tomaj\NetteApi\Presenters\ApiPresenter; use Tomaj\NetteApi\Response\JsonApiResponse; +use Tomaj\NetteApi\Response\ResponseInterface; use Nette\Application\Request; use Nette\Http\IRequest; use Nette\Http\Request as HttpRequest; @@ -34,14 +35,14 @@ public function testTemplateMatchWinsWhenTheRouteSplitsTheId(): void $decider->addApi(new EndpointIdentifier('GET', 1, 'users', 'list'), new AlwaysOkHandler(), new NoAuthorization()); $decider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), new UserDetailHandler(), new NoAuthorization()); - $exact = self::resolve($decider, 'GET', '1', 'users', 'list', '/api/v1/users/list'); + $exact = self::resolve($decider, 'GET', '1', 'users', 'list', null); $this->assertInstanceOf(AlwaysOkHandler::class, $exact->getHandler()); - $matched = self::resolve($decider, 'GET', '1', 'users', '42', '/api/v1/users/42/detail'); + $matched = self::resolve($decider, 'GET', '1', 'users', '42', 'detail'); $this->assertInstanceOf(UserDetailHandler::class, $matched->getHandler()); $this->assertSame('v1/users/{id}/detail', $matched->getHandler()->getEndpoint()?->getUrl()); - $missing = self::resolve($decider, 'GET', '1', 'users', '42', '/api/v1/users/42'); + $missing = self::resolve($decider, 'GET', '1', 'users', '42', null); $this->assertInstanceOf(DefaultHandler::class, $missing->getHandler()); } @@ -56,7 +57,7 @@ public function params(): array $decider = new ApiDecider(new Container()); $decider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), $handler, new NoAuthorization()); - $matched = self::resolve($decider, 'GET', '1', 'users', '42', '/api/v1/users/42/detail'); + $matched = self::resolve($decider, 'GET', '1', 'users', '42', 'detail'); $this->assertSame($handler, $matched->getHandler()); } @@ -91,6 +92,41 @@ public function getByType(string $type, bool $throw = true): ?object $this->assertSame(['status' => 'ok'], $response->getPayload(), 'without a matching template the static endpoint still answers, as in 3.x'); } + public function testALiteralPlaceholderInTheRequestIsAValueOfTheTemplate(): void + { + $decider = new ApiDecider(new Container()); + $decider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id}'), self::echoPathHandler(), new NoAuthorization()); + $presenter = self::presenter($decider); + + $response = $presenter->run(new Request('Api:Api:default', 'GET', ['version' => '1', 'package' => 'users', 'apiAction' => '{id}'])); + $this->assertInstanceOf(JsonApiResponse::class, $response); + $this->assertSame(['id' => '{id}'], $response->getPayload()); + + $response = $presenter->run(new Request('Api:Api:default', 'GET', ['version' => '1', 'package' => 'users', 'apiAction' => '{id}', 'params' => 'more'])); + $this->assertSame(404, $response->getCode(), 'the literal URL of a template is not an endpoint of a request'); + } + + public function testATemplateIsMatchedFromTheRouterValuesWithoutAnHttpRequest(): void + { + $decider = new ApiDecider(new Container()); + $decider->addApi(new EndpointIdentifier('GET', 2, 'users', '{id}/detail'), self::echoPathHandler(), new NoAuthorization()); + + // for example a forwarded request, or a route mask without the "v" prefix + $response = self::presenter($decider)->run(new Request('Api:Api:default', 'GET', ['version' => '2', 'package' => 'users', 'apiAction' => 'a b', 'params' => 'detail'])); + $this->assertInstanceOf(JsonApiResponse::class, $response); + $this->assertSame(['id' => 'a b'], $response->getPayload()); + } + + public function testAnEncodedSlashDoesNotSplitAValueIntoTwoSegments(): void + { + $decider = new ApiDecider(new Container()); + $decider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id}/{part}/detail'), self::echoPathHandler(['id', 'part']), new NoAuthorization()); + $request = new Request('Api:Api:default', 'GET', ['version' => '1', 'package' => 'users', 'apiAction' => 'a', 'params' => 'b/detail']); + + $this->assertSame(404, self::presenter($decider, '/api/v1/users/a%2fb/detail')->run($request)->getCode()); + $this->assertSame(['id' => 'a', 'part' => 'b'], self::payload(self::presenter($decider, '/api/v1/users/a/b/detail')->run($request))); + } + public function testGetApiKeepsItsFourArgumentContract(): void { $decider = new ApiDecider(new Container()); @@ -99,8 +135,9 @@ public function testGetApiKeepsItsFourArgumentContract(): void $this->assertInstanceOf(AlwaysOkHandler::class, $decider->getApi('GET', '1', 'users', 'list')->getHandler()); $this->assertInstanceOf(DefaultHandler::class, $decider->getApi('GET', '1', 'users', '42')->getHandler()); - $this->assertNull($decider->matchPath('GET', '1', 'users', '42', null)); - $this->assertNull($decider->matchPath('GET', '1', 'users', '42', '/api/v1/users/42')); + $this->assertNull($decider->matchPath('GET', '1', 'users', '42')); + $this->assertNull($decider->matchPath('GET', '1', 'users', '42', '')); + $this->assertInstanceOf(UserDetailHandler::class, $decider->matchPath('GET', '1', 'users', '42', 'detail')?->getHandler()); } public function testASubclassCanKeepOverridingTheFourArgumentGetApi(): void @@ -119,10 +156,12 @@ public function testOverlappingTemplatesAreReported(): void { $decider = new ApiDecider(new Container()); $decider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id}'), new UserDetailHandler(), new NoAuthorization()); - $decider->addApi(new EndpointIdentifier('GET', 1, 'users', '{slug}'), new UserDetailHandler(), new NoAuthorization()); + $decider->addApi(new EndpointIdentifier('POST', 1, 'users', '{slug}'), new UserDetailHandler(), new NoAuthorization()); + $decider->addApi(new EndpointIdentifier('GET', 2, 'users', '{slug}'), new UserDetailHandler(), new NoAuthorization()); $this->expectException(\LogicException::class); - self::resolve($decider, 'GET', '1', 'users', '42', '/api/v1/users/42'); + $this->expectExceptionMessage("GET endpoints 'v1/users/{id}' and 'v1/users/{slug}' can match the same request."); + $decider->addApi(new EndpointIdentifier('GET', 1, 'users', '{slug}'), new UserDetailHandler(), new NoAuthorization()); } public function testOptionsOnATemplateUsesThePreflightHandler(): void @@ -131,7 +170,7 @@ public function testOptionsOnATemplateUsesThePreflightHandler(): void $decider->enableGlobalPreflight(); $decider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), new UserDetailHandler(), new NoAuthorization()); - $api = self::resolve($decider, 'OPTIONS', '1', 'users', '42', '/api/v1/users/42/detail'); + $api = self::resolve($decider, 'OPTIONS', '1', 'users', '42', 'detail'); $this->assertInstanceOf(CorsPreflightHandler::class, $api->getHandler()); } @@ -141,15 +180,15 @@ public function testMatchPathNormalisesTheMethodAndAnEmptyAction(): void $decider->enableGlobalPreflight(); $decider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), new UserDetailHandler(), new NoAuthorization()); - $preflight = $decider->matchPath('options', '1', 'users', '', '/api/v1/users/42/detail'); + $preflight = $decider->matchPath('options', '1', 'users', '', '42/detail'); $this->assertInstanceOf(CorsPreflightHandler::class, $preflight?->getHandler()); $this->assertSame('OPTIONS', $preflight->getEndpoint()->getMethod()); $this->assertNull($preflight->getEndpoint()->getApiAction()); - $named = $decider->matchPath('OPTIONS', '1', 'users', '42', '/api/v1/users/42/detail'); + $named = $decider->matchPath('OPTIONS', '1', 'users', '42', 'detail'); $this->assertSame('42', $named?->getEndpoint()->getApiAction()); - $matched = $decider->matchPath('get', '1', 'users', '42', '/api/v1/users/42/detail'); + $matched = $decider->matchPath('get', '1', 'users', '42', 'detail'); $this->assertInstanceOf(UserDetailHandler::class, $matched?->getHandler()); } @@ -170,11 +209,11 @@ public function testStaticLinkIsUnchanged(): void $this->assertStringContainsString('/api/v1/users/{id}', $placeholder); } - private static function resolve(ApiDecider $decider, string $method, string $version, string $package, string $apiAction, string $path): Api + private static function resolve(ApiDecider $decider, string $method, string $version, string $package, string $apiAction, ?string $params): Api { $api = $decider->getApi($method, $version, $package, $apiAction); - return $api->getHandler() instanceof DefaultHandler ? ($decider->matchPath($method, $version, $package, $apiAction, $path) ?? $api) : $api; + return $api->getHandler() instanceof DefaultHandler ? ($decider->matchPath($method, $version, $package, $apiAction, $params) ?? $api) : $api; } public function testPathCaptureDoesNotLeakIntoTheNextEndpoint(): void @@ -185,7 +224,7 @@ public function testPathCaptureDoesNotLeakIntoTheNextEndpoint(): void $decider->addApi(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), new UserDetailHandler(), new NoAuthorization()); $decider->addApi(new EndpointIdentifier('GET', 2, 'users', '{id}/detail'), new UserDetailHandler(), new NoAuthorization()); - $matched = self::resolve($decider, 'GET', '1', 'users', '42', '/api/v1/users/42/detail'); + $matched = self::resolve($decider, 'GET', '1', 'users', '42', 'detail'); $id = null; foreach ($matched->getHandler()->params() as $param) { if ($param->getKey() === 'id') { @@ -194,7 +233,7 @@ public function testPathCaptureDoesNotLeakIntoTheNextEndpoint(): void } $this->assertSame(42, $id); - $static = self::resolve($decider, 'GET', '1', 'users', 'list', '/api/v1/users/list'); + $static = self::resolve($decider, 'GET', '1', 'users', 'list', null); $this->assertInstanceOf(AlwaysOkHandler::class, $static->getHandler()); foreach (new UserDetailHandler()->params() as $param) { if ($param->getKey() === 'id') { @@ -202,15 +241,69 @@ public function testPathCaptureDoesNotLeakIntoTheNextEndpoint(): void } } - $post = self::resolve($decider, 'POST', '1', 'users', '42', '/api/v1/users/42/detail'); + $post = self::resolve($decider, 'POST', '1', 'users', '42', 'detail'); $this->assertInstanceOf(DefaultHandler::class, $post->getHandler()); - $withPreflight = self::resolve($decider, 'GET', '1', 'users', '7', '/api/v1/users/7/detail'); + $withPreflight = self::resolve($decider, 'GET', '1', 'users', '7', 'detail'); $this->assertInstanceOf(UserDetailHandler::class, $withPreflight->getHandler()); - $otherVersion = self::resolve($decider, 'GET', '1', 'users', '7', '/api/v2/users/7/detail'); + $otherVersion = self::resolve($decider, 'GET', '3', 'users', '7', 'detail'); $this->assertInstanceOf(DefaultHandler::class, $otherVersion->getHandler()); $decider->addApi(new EndpointIdentifier('GET', 1, 'users', 'detail'), new UserDetailHandler(), new NoAuthorization()); $this->expectException(\LogicException::class); $decider->getApi('GET', '1', 'users', 'detail'); } + + /** + * @param list $names + */ + private static function echoPathHandler(array $names = ['id']): AlwaysOkHandler + { + return new class ($names) extends AlwaysOkHandler { + /** @param list $names */ + public function __construct(private readonly array $names) + { + parent::__construct(); + } + + public function params(): array + { + return array_map(static fn (string $name): PathInputParam => new PathInputParam($name), $this->names); + } + + public function handle(array $params): ResponseInterface + { + return new JsonApiResponse(200, $params); + } + }; + } + + private static function presenter(ApiDecider $decider, ?string $path = null): ApiPresenter + { + $presenter = new ApiPresenter(); + $presenter->apiDecider = $decider; + $presenter->response = new HttpResponse(); + $presenter->outputConfigurator = new DebuggerConfigurator(); + $presenter->errorHandler = new DefaultErrorHandler($presenter->outputConfigurator); + $presenter->context = new class ($path) extends Container { + public function __construct(private readonly ?string $path) + { + parent::__construct(); + } + + public function getByType(string $type, bool $throw = true): ?object + { + return $type === IRequest::class && $this->path !== null ? new HttpRequest(new UrlScript('https://example.com' . $this->path)) : null; + } + }; + + return $presenter; + } + + /** + * @return mixed + */ + private static function payload(\Nette\Application\Response $response): mixed + { + return $response instanceof JsonApiResponse ? $response->getPayload() : null; + } }