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..34f19336b 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,8 @@ 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). +* `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`. @@ -59,10 +61,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` 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`. + * 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. * `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/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..cfc8c9c0d 100644 --- a/UPGRADE-4.0.md +++ b/UPGRADE-4.0.md @@ -74,6 +74,16 @@ new BearerTokenAuthorization(new StaticBearerTokenRepository(['token' => '*']), new BearerTokenAuthorization(new StaticTokenRepository(['token' => '*']), $ipDetector); ``` +## 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: + +* `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($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 * Every file declares `strict_types=1`. @@ -125,7 +135,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` 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; @@ -141,6 +151,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..f68722b0b 100644 --- a/composer.json +++ b/composer.json @@ -55,7 +55,11 @@ "autoload-dev": { "psr-4": { "Tomaj\\NetteApi\\Test\\": "tests" - } + }, + "classmap": [ + "tests/Input/Fixtures/Handlers.php", + "tests/Input/Fixtures/Shared.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..c1c7200b3 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,25 @@ 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) | + +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 +83,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/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/examples/typed-input.md b/docs/examples/typed-input.md new file mode 100644 index 000000000..cb8934377 --- /dev/null +++ b/docs/examples/typed-input.md @@ -0,0 +1,66 @@ +--- +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 and header parameters, a multipart body | + +## 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 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 + +<<< @/../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..51c10f25d 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`, 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. ## 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..145232f45 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 | 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 | + +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 ### 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..310068030 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..e6d0547f3 --- /dev/null +++ b/docs/guide/input-styles.md @@ -0,0 +1,450 @@ +--- +title: params() and DTO side by side +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()` 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 + +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 + +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), // always required + 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, max: 50)] 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: + +```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`. `#[Email]` and `#[Length]` are extra checks that the `params()` version does not make. + +### 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. + +### 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..b6040b8a7 100644 --- a/docs/guide/links.md +++ b/docs/guide/links.md @@ -15,7 +15,16 @@ $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()` 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]); +// 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 +``` + +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..78be22b0c 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()` 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 +{ + return [ + new PathInputParam('id', InputType::INTEGER), // always required + 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..1b51894f9 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 (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 | -| 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()` | | @@ -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/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..eb8a9427f --- /dev/null +++ b/docs/guide/typed-input-body.md @@ -0,0 +1,213 @@ +--- +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. 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. + +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 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: + 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} +``` + +## 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`; 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 + +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')]`. 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. 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." +} +``` + +With Problem Details enabled, the 415 uses that format, and its `detail` always names the accepted types. + +### 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 (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`. + +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`. 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 + +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` 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-conversion.md b/docs/guide/typed-input-conversion.md new file mode 100644 index 000000000..7e65c7da8 --- /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 | + +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 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` (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`. + +## 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 (`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. 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 + +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 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 + +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. + +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"] + } +} +``` + +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 + +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`. + +### 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 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 + +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 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 new file mode 100644 index 000000000..d6dd5ab15 --- /dev/null +++ b/docs/guide/typed-input.md @@ -0,0 +1,226 @@ +--- +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 `InputParam` objects, so validation, OpenAPI and the console work as with `params()`. + +## 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 `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 | +| --- | --- | --- | +| `#[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 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). + +### 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 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: + +```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 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 + +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. + +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 + +### 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 + +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 +{ + "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 `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`, 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. + +## OpenAPI and the API 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. + +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} +``` + +JSON schema is generated here only as an OpenAPI output format. Runtime validation uses the recursive DTO mapper and never requires a JSON schema. + +## 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.** 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 f52d297e8..0cd202374 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,23 +40,46 @@ 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`: <<< @/../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; a variant of the typed version is `GreetHandler` in [`examples/attributes`](/examples/attributes). ## Where to go next ## 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..2bccee6f2 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,25 @@ 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 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) | + +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 +83,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/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/examples/typed-input.md b/docs/sk/examples/typed-input.md new file mode 100644 index 000000000..8d6e95a0c --- /dev/null +++ b/docs/sk/examples/typed-input.md @@ -0,0 +1,66 @@ +--- +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` | 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` | parametre cesty a hlavičky, multipart telo | + +## 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 + +## 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 + +<<< @/../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..8e73a892e 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ť. 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á 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()? Á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..63ff350b6 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`, 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). ## 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..2f41c5d75 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 [Typované 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..a668ba340 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 | 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 | + +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 ### 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..f236c7030 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 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`. ::: 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..8e80fe227 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ú 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()`. -```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..3f86bf2e3 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..6a979c4c7 --- /dev/null +++ b/docs/sk/guide/input-styles.md @@ -0,0 +1,450 @@ +--- +title: params() a DTO vedľa seba +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()` 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 + +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 + +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), // vždy povinný + 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 zoznam + +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, max: 50)] 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 zoznamu. 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á: + +```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`. `#[Email]` a `#[Length]` sú kontroly navyše, ktoré verzia s `params()` nerobí. + +### 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. + +### 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 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. +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..aee1a1f8c 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 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 6fe2b8b60..50aff83ff 100644 --- a/docs/sk/guide/links.md +++ b/docs/sk/guide/links.md @@ -15,7 +15,16 @@ $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()` 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]); +// 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 +``` + +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..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. @@ -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..fcf6f312e 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()` 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 +{ + return [ + new PathInputParam('id', InputType::INTEGER), // vždy povinný + 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..981290da0 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}` (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 | -| 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()` | | @@ -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 2223635d8..2df37457b 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 | +| 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 | @@ -104,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 new file mode 100644 index 000000000..64556fe07 --- /dev/null +++ b/docs/sk/guide/typed-input-body.md @@ -0,0 +1,213 @@ +--- +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 typy obsahu + +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 zoznamom + +```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`. 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 typu obsahu, nie od JSON schémy. + +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é 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: + 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} +``` + +## 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`; 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 + +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')]`. 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 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 +{ + "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." +} +``` + +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 + +| 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 (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`. + +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`. 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 + +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` 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-conversion.md b/docs/sk/guide/typed-input-conversion.md new file mode 100644 index 000000000..631e826f7 --- /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ú na 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 | + +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` 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` (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`. + +## 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 (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 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 + +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áť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 + +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. + +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"] + } +} +``` + +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 + +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 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 + +`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 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 | + +```php +final readonly class IssueInput +{ + public function __construct( + #[Body] + #[Cast(DateFormat::class, 'd.m.Y')] + public DateTimeImmutable $issuedOn, + ) { + } +} +``` + +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> + +```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 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 + +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 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 new file mode 100644 index 000000000..0fad1e08b --- /dev/null +++ b/docs/sk/guide/typed-input.md @@ -0,0 +1,226 @@ +--- +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 typy obsahu](/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 objekty `InputParam`, takže validácia, OpenAPI aj konzola fungujú ako pri `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 `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 | +| --- | --- | --- | +| `#[Query]` | query string | `InputParam::TYPE_GET`, OpenAPI `in: query` | +| `#[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 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). + +### 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 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: + +```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()); +``` + +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 + +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. + +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 + +### 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 na stránke [telo, súbory a typy obsahu](/sk/guide/typed-input-body#post-s-vnorenym-dto-a-zoznamom). + +## Chybové odpovede + +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 +{ + "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 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`, 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. + +## OpenAPI a API konzola + +[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. + +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} +``` + +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. + +## Bezpečnostné poznámky + +- **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.** 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 + +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 cde77773a..f5acd18cd 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,23 +40,46 @@ 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 [Typované 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`: <<< @/../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; obdobou typovanej verzie je `GreetHandler` v [`examples/attributes`](/sk/examples/attributes). ## Kam ďalej ## Č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/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/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..cac82f807 --- /dev/null +++ b/examples/typed-input/e2e.sh @@ -0,0 +1,71 @@ +#!/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 '"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/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..35763dc4c 100644 --- a/src/ApiDecider.php +++ b/src/ApiDecider.php @@ -13,6 +13,11 @@ use Tomaj\NetteApi\Handlers\CorsPreflightHandler; 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; use Tomaj\NetteApi\RateLimit\AutowiredRateLimit; use Tomaj\NetteApi\RateLimit\RateLimiterInterface; use Tomaj\NetteApi\RateLimit\RateLimitInterface; @@ -22,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( @@ -33,6 +41,9 @@ public function __construct( * Get api handler that match input method, version, package and apiAction. * If decider cannot find handler for given handler, returns defaults. * + * 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 * * @return Api @@ -41,6 +52,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 +71,32 @@ 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 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 $params = null): ?Api + { + $method = strtoupper($method); + $apiAction = $apiAction === '' ? null : $apiAction; + $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, $path) !== null) { + 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) { @@ -75,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 { @@ -92,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; } @@ -125,23 +173,74 @@ 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; } - if (str_starts_with($handler, '@')) { - /** - * @var ApiHandlerInterface $apiHandler - */ - $apiHandler = $this->container->getByName(substr($handler, 1)); - return $apiHandler; + $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 array{0: ApiHolder, 1: array}|null + */ + private function matchTemplate(string $method, string $version, string $path): ?array + { + foreach ($this->apis as $api) { + $identifier = $api->getEndpoint(); + if (($method !== '' && $method !== $identifier->getMethod()) || $identifier->getVersion() !== $version || !str_contains($identifier->getUrl(), '{')) { + continue; + } + // 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) { + return [$api, $captured]; + } + } + + return null; + } + + /** + * 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): bool + { + if ($handler instanceof TypedHandler) { + // 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 ($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); + return true; } } 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..62217b0bb 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 => serialized DTO metadata, unserialized on first use */ + 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,61 @@ 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' => $metadata, 'files' => $files] = DtoCompiler::compileWithFiles($class); + EndpointTemplate::assert($url, $metadata->pathNames(), sprintf('%s (%s)', $class, $endpoint->source)); + $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); + } + } + + 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/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/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..aba11d641 --- /dev/null +++ b/src/Input/Body.php @@ -0,0 +1,28 @@ + $examples named examples, the same pairs as InputParam::addExample() + */ + public function __construct( + public ?string $name = null, + public ?string $description = null, + public array $examples = [], + ) { + } + + #[\Override] + public function source(): Source + { + return Source::Body; + } +} 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..46fb4cfdf --- /dev/null +++ b/src/Input/DtoCompiler.php @@ -0,0 +1,1218 @@ +> a class of each file the metadata is read from, keyed by the file */ + private array $files = []; + + /** @var list */ + private array $stack = []; + + 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 and of the classes whose constants they read, 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); + $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($files)]; + } + + 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); + 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; + $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); + } + + /** @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)) { + $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 = []; + $headers = []; + foreach ($properties as $property) { + $field = $this->property($property, $reflection, $root); + // 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, + $taken, + $field->property, + $field->externalName, + )); + } + $names[$field->externalName] = $field->property; + if ($header !== null) { + $headers[$header] = $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); + } + + $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; + 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['type']), + )); + } + $listItem = $list['name']; + $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); + } + + 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); + if ($list !== null) { + $default = $this->listDefault($class, $name, $default, $list); + } + + return new Field( + property: $name, + externalName: $external, + source: $source['source'], + typeName: $typeName, + nullable: $nullable, + hasDefault: $hasDefault, + default: $default, + description: $source['attribute']->description, + examples: $this->examples($source['attribute'], $class, $name), + listItem: $listItem, + enumClass: $enum['class'] ?? null, + enumInt: $enum['int'] ?? false, + enumValues: $enum['values'] ?? [], + constraints: $constraints, + 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: SourceAttribute} + */ + private function source(\ReflectionProperty $property, \ReflectionClass $dto, bool $root): array + { + $found = []; + foreach ($property->getAttributes(SourceAttribute::class, \ReflectionAttribute::IS_INSTANCEOF) as $attribute) { + try { + $found[] = $attribute->newInstance(); + } catch (\Throwable $exception) { + $this->fail(sprintf( + '%s::$%s attribute %s is invalid: %s.', + $dto->getName(), + $property->getName(), + new \ReflectionClass($attribute->getName())->getShortName(), + $exception->getMessage(), + )); + } + } + 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 = $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.', + $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 externalName(SourceAttribute $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(SourceAttribute $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 + { + $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; + $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, + )); + } + + // 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( + '%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. + * 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): ?array + { + $propertyDoc = $property->getDocComment() ?: ''; + $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() ?: '', self::methodScope($constructor)]; + } + $name = $property->getName(); + + foreach (['(?:phpstan|psalm)-param', 'param'] as $tag) { + 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 ['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): Field + { + $itemName = $list['name']; + $builtin = $list['builtin']; + $children = []; + $enum = $builtin ? null : $this->enum($itemName, $class, $property); + if (!$builtin && $enum === null && $itemName !== FileUpload::class && $itemName !== \DateTimeImmutable::class) { + $children = $this->dto($itemName, false); + } + + return new Field( + property: $property, + externalName: $property, + source: $source, + typeName: $itemName, + nullable: false, + hasDefault: false, + default: null, + description: null, + examples: [], + listItem: null, + enumClass: $enum['class'] ?? null, + enumInt: $enum['int'] ?? false, + enumValues: $enum['values'] ?? [], + constraints: [], + casterClass: null, + casterArguments: [], + casterSchema: null, + children: $children, + item: null, + dtoClass: $class, + ); + } + + /** + * @param \ReflectionClass<*> $dto + * @return list + */ + private function constraints(\ReflectionProperty $property, \ReflectionClass $dto, string $typeName): array + { + $instances = []; + foreach ($property->getAttributes(ConstraintInterface::class, \ReflectionAttribute::IS_INSTANCEOF) as $attribute) { + try { + $instance = $attribute->newInstance(); + } catch (\Throwable $exception) { + $this->fail(sprintf( + '%s::$%s constraint %s is invalid: %s.', + $dto->getName(), + $property->getName(), + new \ReflectionClass($attribute->getName())->getShortName(), + $exception->getMessage(), + )); + } + $this->constraintApplies($instance, $typeName, $dto->getName(), $property->getName()); + $this->touch(new \ReflectionClass($instance)); + $instances[] = $instance; + } + + return $instances; + } + + 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): 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; + // 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(), + $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, + )); + } + } + + /** + * 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(); + 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. + * An int in a list default becomes a float, as a request value would. + * + * @param array{name: string, builtin: bool} $list + */ + private function listDefault(string $class, string $property, mixed $default, array $list): mixed + { + 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)); + } + 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, + )); + } + } + + return $listItem === 'float' ? array_map(static fn (mixed $item): mixed => is_int($item) ? (float) $item : $item, $default) : $default; + } + + /** + * @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] = $class; + } + } + + 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..c67717183 --- /dev/null +++ b/src/Input/DtoMapper.php @@ -0,0 +1,382 @@ + */ + 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; + + /** @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 + { + $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[self::REQUEST_ERRORS])) { + $own[self::REQUEST_ERRORS] = $this->errors[self::REQUEST_ERRORS]; + } + + return $own; + } + + private function evaluate(): void + { + if ($this->done) { + return; + } + $this->done = true; + + RequestInput::boot($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']); + 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[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[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; + } + + /** + * @return array{value: mixed, errors: array{}}|array{errors: non-empty-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 = $this->casters[$field] ??= 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) { + return $this->file($field, $raw, $path); + } + if ($field->item instanceof Field) { + return $this->list($field, $field->item, $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{}}|array{errors: non-empty-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']); + 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 ['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{}}|array{errors: non-empty-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'); + } + + // 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); + } + } + + $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']); + continue; + } + $values[] = $result['value']; + } + if ($errors !== []) { + return ['errors' => $errors]; + } + + return ['value' => $values, 'errors' => []]; + } + + /** + * @return array{value: mixed, errors: array{}}|array{errors: non-empty-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) { + // 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' => []]; + } + + if (is_array($raw) && is_array($raw['name'] ?? null)) { + return $this->fail($path, 'Value must be a file upload'); + } + + return ['value' => FileUpload::fromFile(is_array($raw) ? $raw : []), 'errors' => []]; + } + + /** + * @param array $file + * @return array> + */ + private static function fileList(array $file): array + { + if (!is_array($file['name'] ?? null)) { + return [$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; + } + + 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 $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{errors: non-empty-array>} + */ + private function fail(string $path, string $message): array + { + ++$this->errorCount; + + return ['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): void + { + 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..e29df1ef2 --- /dev/null +++ b/src/Input/DtoMetadata.php @@ -0,0 +1,82 @@ + $fields root properties, in constructor order + * @param list $contentTypes + */ + public function __construct( + public string $handler, + public string $class, + public array $fields, + public array $contentTypes, + public bool $bodyRequired, + public bool $readsBody, + public ?string $firstBody, + ) { + } + + /** + * @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 + { + 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 ($fields as $field) { + $arguments[$field->property] = $value($field); + } + + return new $class(...$arguments); + } + + /** + * @return list + */ + public function pathNames(): array + { + $names = []; + foreach ($this->fields as $field) { + if ($field->source === Source::Path) { + $names[] = $field->externalName; + } + } + + return $names; + } +} diff --git a/src/Input/DtoMetadataRegistry.php b/src/Input/DtoMetadataRegistry.php new file mode 100644 index 000000000..7e86555b6 --- /dev/null +++ b/src/Input/DtoMetadataRegistry.php @@ -0,0 +1,59 @@ + serialized DtoMetadata from the container, keyed by the handler */ + private static array $installed = []; + + /** @var array */ + private static array $metadata = []; + + /** + * @param array $serialized serialize() of each handler's DtoMetadata + */ + public static function install(array $serialized): void + { + self::$installed = $serialized; + self::$metadata = []; + } + + /** + * @param class-string $handler + */ + public static function forHandler(string $handler): DtoMetadata + { + if (isset(self::$metadata[$handler])) { + return self::$metadata[$handler]; + } + if (!isset(self::$installed[$handler])) { + return self::$metadata[$handler] = DtoCompiler::compile($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::$metadata[$handler] = $metadata; + } + + /** + * @internal + */ + public static function reset(): void + { + self::$installed = []; + self::$metadata = []; + } +} diff --git a/src/Input/EndpointTemplate.php b/src/Input/EndpointTemplate.php new file mode 100644 index 000000000..20b796fb1 --- /dev/null +++ b/src/Input/EndpointTemplate.php @@ -0,0 +1,221 @@ + + */ + public static function placeholders(string $url): array + { + $names = []; + foreach (self::segments($url) as $segment) { + $name = self::placeholderName($segment); + if ($name !== null) { + $names[] = $name; + } + } + + 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), + 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 are paths after the version, such as users/{id}/detail and users/42/detail; $path is already decoded by the router. + * + * @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) { + $value = $actual[$index]; + $name = self::placeholderName($segment); + if ($name !== null) { + if ($value === '') { + return null; + } + $captured[$name] = $value; + continue; + } + if ($segment !== $value) { + return null; + } + } + + return $captured; + } + + /** + * 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 fill(string $template, array $values): array + { + $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 rawurlencode($value); + }, $template); + + 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)); + 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, '{') && 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, + $segment, + trim($url, '/'), + )); + } + } + } + + /** + * 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]; + if (self::placeholderName($segment) === null && self::placeholderName($other) === null && $segment !== $other) { + return false; + } + } + + 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 + */ + 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..755595e73 --- /dev/null +++ b/src/Input/Field.php @@ -0,0 +1,58 @@ + $examples + * @param list $enumValues + * @param list $constraints + * @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 $nullable, + public bool $hasDefault, + public mixed $default, + public ?string $description, + public array $examples, + public ?string $listItem, + public ?string $enumClass, + public bool $enumInt, + public array $enumValues, + public array $constraints, + 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 readsBody(): bool + { + return $this->source === Source::Body || $this->source === Source::File; + } +} diff --git a/src/Input/File.php b/src/Input/File.php new file mode 100644 index 000000000..39559e4c0 --- /dev/null +++ b/src/Input/File.php @@ -0,0 +1,28 @@ + $examples named examples, the same pairs as InputParam::addExample() + */ + public function __construct( + public ?string $name = null, + public ?string $description = null, + public array $examples = [], + ) { + } + + #[\Override] + public function source(): Source + { + return Source::File; + } +} 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..c773897c6 --- /dev/null +++ b/src/Input/Header.php @@ -0,0 +1,29 @@ + $examples named examples, the same pairs as InputParam::addExample() + */ + public function __construct( + public ?string $name = null, + public ?string $description = null, + public array $examples = [], + ) { + } + + #[\Override] + public function source(): Source + { + return Source::Header; + } +} 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 = [], + ) { + } + + #[\Override] + public function source(): Source + { + return Source::Path; + } +} diff --git a/src/Input/Query.php b/src/Input/Query.php new file mode 100644 index 000000000..0a849fa41 --- /dev/null +++ b/src/Input/Query.php @@ -0,0 +1,28 @@ + $examples named examples, the same pairs as InputParam::addExample() + */ + public function __construct( + public ?string $name = null, + public ?string $description = null, + public array $examples = [], + ) { + } + + #[\Override] + public function source(): Source + { + return Source::Query; + } +} diff --git a/src/Input/RequestInput.php b/src/Input/RequestInput.php new file mode 100644 index 000000000..ea4c858b8 --- /dev/null +++ b/src/Input/RequestInput.php @@ -0,0 +1,339 @@ + */ + 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; + + /** @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 = []; + self::$body = []; + self::$files = []; + self::$failure = null; + self::$mediaType = null; + self::$plain = null; + } + + /** + * Replaces php://input, null reads it again. Used by tests; a real request leaves this unset. + * + * @internal + */ + public static function setRawBody(?string $raw): void + { + self::$rawOverride = $raw; + self::$plain = null; + } + + /** + * @param list $consumes + */ + public static function boot(array $consumes, bool $bodyRequired, bool $readsBody): void + { + self::$query = $_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 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. + */ + 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 = HeaderBag::get('Content-Type'); + $type = MediaTypes::normalize($header); + 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; + } + + throw $type === '' ? UnsupportedMediaTypeException::missing($consumes) : 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; + } + + // 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 = $_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; + // 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 (self::$mediaType === MediaTypes::MULTIPART || (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 = $parsed; + 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'); + } + + /** + * @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; + } + + 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..bfffbe728 --- /dev/null +++ b/src/Input/ScalarCoercer.php @@ -0,0 +1,176 @@ +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..c948fd8fb --- /dev/null +++ b/src/Input/SchemaBuilder.php @@ -0,0 +1,156 @@ +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)]; + } + + // 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) { + 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 @@ + */ + public array $examples { get; } + + public function source(): Source; +} diff --git a/src/Input/Split.php b/src/Input/Split.php new file mode 100644 index 000000000..4ea4d26ea --- /dev/null +++ b/src/Input/Split.php @@ -0,0 +1,40 @@ +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..856527356 --- /dev/null +++ b/src/Input/TypeName.php @@ -0,0 +1,169 @@ + $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; + } + + /** + * 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. + * + * @param \ReflectionClass<*> $scope + * @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 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())); + } + + /** + * 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 = self::tokens($code); + $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 && $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); + } + } + + 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..f8ea5908d --- /dev/null +++ b/src/Input/UnsupportedMediaTypeException.php @@ -0,0 +1,29 @@ + $accepted + */ + public static function missing(array $accepted): self + { + return new self('Content-Type is missing. Use one of: ' . implode(', ', $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) . '.', + ); + } +} diff --git a/src/Link/ApiLink.php b/src/Link/ApiLink.php index 6d52a3390..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 */ @@ -20,16 +25,58 @@ public function __construct(private readonly LinkGenerator $linkGenerator) /** * Create link to specified api endpoint * + * 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 */ 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) ?: ''; } + + /** + * 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 + { + $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' => 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 have and as path segments, for example '/api/v/[/]'.", + $endpoint->getMethod(), + $endpoint->getUrl(), + )); + } + + return substr_replace($link, $path, $position, strlen($standIn)); + } } diff --git a/src/Misc/ConsoleRequest.php b/src/Misc/ConsoleRequest.php index d370f27da..fbfee27e5 100644 --- a/src/Misc/ConsoleRequest.php +++ b/src/Misc/ConsoleRequest.php @@ -7,8 +7,11 @@ 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; +use Tomaj\NetteApi\Params\MappedInputParam; use Tomaj\NetteApi\Params\ParamInterface; final readonly class ConsoleRequest @@ -27,7 +30,7 @@ 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); $postFields = array_merge($postFields, $additionalValues['postFields'] ?? []); $getFields = array_merge($getFields, $additionalValues['getFields'] ?? []); @@ -39,8 +42,21 @@ 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 !== []) { + } + 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 = []; 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,95 @@ 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; + } + + /** + * 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 +367,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..dad2a4d2c 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; /** @@ -28,7 +30,30 @@ public function build(ApiHandlerInterface $handler, SchemaRegistry $schemaRegist $filesInBody = false; $requestBodyExample = []; $result = []; + $typedProperties = []; + $typedRequired = []; + $typedTypes = []; + $typedFiles = []; foreach ($handler->params() as $param) { + // 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(); + } + $typedProperties[$param->getKey()] = $schema; + if ($param->getType() === InputParam::TYPE_FILE) { + $typedFiles[] = $param->getKey(); + } + if ($param->isRequired()) { + $typedRequired[] = $param->getKey(); + } + if ($param->getContentTypes() !== []) { + $typedTypes = $param->getContentTypes(); + } + continue; + } if ($param instanceof JsonInputParam) { $schema = TypeHelper::toArray(json_decode($param->getSchema(), true)); if (!empty($examples = $param->getExamples())) { @@ -70,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()) { @@ -145,6 +146,207 @@ public function build(ApiHandlerInterface $handler, SchemaRegistry $schemaRegist ]; } + if ($typedProperties !== []) { + $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]; + } + // 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; files are sent only as multipart, so a body with files keeps it + if (!$this->formDescribable($typedProperties)) { + $describable = array_diff($advertised, $typedFiles === [] ? [MediaTypes::FORM, MediaTypes::MULTIPART] : [MediaTypes::FORM]); + $advertised = $describable !== [] ? $describable : $advertised; + } + foreach ($advertised as $contentType) { + // 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; + } + // every required property is listed: a required file means only multipart is advertised, and multipart lists files + 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; + 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)) { + $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 + { + 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/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..58c339e92 --- /dev/null +++ b/src/Params/BodyInputParam.php @@ -0,0 +1,49 @@ +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()); + } + + #[\Override] + public function validate(): ValidationResultInterface + { + $failure = $this->body()['failure']; + if ($failure !== null) { + return new ValidationResult(ValidationResult::STATUS_ERROR, [$failure]); + } + + return parent::validate(); + } + + /** + * @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 new file mode 100644 index 000000000..308431360 --- /dev/null +++ b/src/Params/HeaderBag.php @@ -0,0 +1,68 @@ +|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()); + } + + public static function get(string $name): ?string + { + $value = self::all()[strtolower($name)] ?? null; + return is_string($value) ? $value : null; + } + + /** + * @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) { + 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..3a54410fe --- /dev/null +++ b/src/Params/MappedInputParam.php @@ -0,0 +1,99 @@ +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)); + } + // 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) { + $this->setMulti(); + } + if ($field->readsBody()) { + $this->setContentTypes($metadata->contentTypes); + } + } + + /** + * 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 parent::getOpenApiSchema() ?? SchemaBuilder::build($this->field, $this->field->readsBody()); + } + + #[\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..3114866f9 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->getErrors() 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..480ca02df 100644 --- a/src/Presenters/ApiPresenter.php +++ b/src/Presenters/ApiPresenter.php @@ -9,14 +9,17 @@ 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; 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; @@ -34,6 +37,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 +295,8 @@ private function logMasking(): LogMasking #[\Override] public function run(Request $request): IResponse { + RequestInput::reset(); + PathValues::reset(); $start = microtime(true); $this->sendCorsHeaders(); @@ -315,8 +323,16 @@ 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 + // 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 (Throwable $throwable) { + $paramsProcessor = $throwable; + } $authResponse = $this->checkAuth($authorization, $params); if ($authResponse !== null) { @@ -335,6 +351,15 @@ public function run(Request $request): IResponse return $rateLimitResponse; } + 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; + } + if ($paramsProcessor->isError()) { $response = $this->errorHandler->handleInputParams($paramsProcessor->getErrors()); $this->response->setCode($response->getCode()); @@ -371,32 +396,69 @@ 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')); + $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 = $params !== null && $params !== ''; + if ($extraSegments) { + $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->matchPath($method, $version, $package, $apiAction, $params) ?? $api; + } + + return $api; + } + + private function matchPath(string $method, string $version, string $package, ?string $apiAction, ?string $params): ?Api + { + // 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 $this->apiDecider->matchPath($method, $version, $package, $apiAction, $params); } /** 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..cda6a09ad --- /dev/null +++ b/src/Validation/Pattern.php @@ -0,0 +1,88 @@ +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; + } + + /** + * 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/'; + } + + #[\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..b08e3c930 --- /dev/null +++ b/src/Validation/Range.php @@ -0,0 +1,64 @@ + $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)].'); + } + 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..92d236ba9 --- /dev/null +++ b/src/ValidationResult/FieldErrors.php @@ -0,0 +1,33 @@ +> $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; + } +} diff --git a/tests/ApiDeciderTest.php b/tests/ApiDeciderTest.php index 0fe9a5a19..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,6 +35,87 @@ public function testDefaultHandlerWithNoRegisteredHandlers(): void $this->assertInstanceOf(DefaultHandler::class, $result->getHandler()); } + public function testThePathParamsOfAHandlerAreCheckedOnce(): 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($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 testAMalformedTemplateIsRefusedWhenItIsAdded(): void + { + $apiDecider = new ApiDecider($this->container); + + $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 { $apiDecider = new ApiDecider($this->container); 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); + } + + 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->assertContains(ScheduleHandler::class, self::installedHandlers()); + $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->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(); + } + $this->assertContains('v1/people/', $urls); + $this->assertContains('v1/orders/', $urls); + + DtoMetadataRegistry::reset(); + $empty = ContainerFactory::create("api:\n endpoints: []\n"); + $empty->initialize(); + $this->assertSame([], self::installedHandlers()); + + $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->assertContains(ListUsersHandler::class, self::installedHandlers()); + } + + 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->assertContains(ListUsersHandler::class, self::installedHandlers()); + $this->assertContains(NoteHandler::class, self::installedHandlers()); + $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); + } + + /** + * @return list + */ + private static function installedHandlers(): array + { + return array_keys((array) new \ReflectionProperty(DtoMetadataRegistry::class, 'installed')->getValue()); + } +} + +#[\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/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/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 new file mode 100644 index 000000000..2ec5a700d --- /dev/null +++ b/tests/Input/BodyParsingTest.php @@ -0,0 +1,340 @@ +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 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 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 + { + 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 new file mode 100644 index 000000000..cf5ba7cdc --- /dev/null +++ b/tests/Input/CasterTest.php @@ -0,0 +1,384 @@ +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(''); + } + + 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->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 { + 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, []); + } +} + +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/ConstraintTest.php b/tests/Input/ConstraintTest.php new file mode 100644 index 000000000..9df7ed031 --- /dev/null +++ b/tests/Input/ConstraintTest.php @@ -0,0 +1,192 @@ +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 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); + $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'); + } + + 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/DtoAttributeTest.php b/tests/Input/DtoAttributeTest.php new file mode 100644 index 000000000..f04ace643 --- /dev/null +++ b/tests/Input/DtoAttributeTest.php @@ -0,0 +1,752 @@ +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); + $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 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'); + } + + 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 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 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 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 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 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, []); + } +} diff --git a/tests/Input/DtoCompilerTest.php b/tests/Input/DtoCompilerTest.php new file mode 100644 index 000000000..fe7ba1778 --- /dev/null +++ b/tests/Input/DtoCompilerTest.php @@ -0,0 +1,761 @@ + + */ + 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'); + } + + 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 +{ +} + +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, []); + } +} + +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 new file mode 100644 index 000000000..e603ab20c --- /dev/null +++ b/tests/Input/DtoHandlerTest.php @@ -0,0 +1,727 @@ + */ + 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 = []; + $_SERVER['REQUEST_METHOD'] = 'GET'; + unset($_SERVER['CONTENT_TYPE'], $_SERVER['HTTP_X_REQUEST_ID']); + RequestInput::reset(); + PathValues::reset(); + DtoMetadataRegistry::reset(); + } + + public function testQueryDefaultsEnumAndStrictInteger(): void + { + $_GET = ['status' => '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()); + } + + 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::setRawBody(null); + $_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()); + } + + 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 +{ + 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..0153884b8 --- /dev/null +++ b/tests/Input/DtoMetadataTest.php @@ -0,0 +1,117 @@ + $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', '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 + { + $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->assertSame('from-install', DtoMetadataRegistry::forHandler(ListUsersHandler::class)->firstBody); + $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..0b4f9eeb1 --- /dev/null +++ b/tests/Input/DtoPhpDocTest.php @@ -0,0 +1,193 @@ +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), + ); + } + + 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}> + */ + 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..81278f505 --- /dev/null +++ b/tests/Input/DtoPropertyTypeTest.php @@ -0,0 +1,838 @@ + + */ + 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']; + 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')]"]; + } + + /** + * @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, []); + } +} + +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 new file mode 100644 index 000000000..5dc8a1e20 --- /dev/null +++ b/tests/Input/EndpointTemplateTest.php @@ -0,0 +1,136 @@ +assertSame(['id' => '42'], EndpointTemplate::match('v1/users/{id}/detail', 'v1/users/42/detail')); + $this->assertNull(EndpointTemplate::match('v1/users/{id}/detail', 'v1/users/42')); + $this->assertNull(EndpointTemplate::match('v1/users/{id}', 'v1/orders/42')); + $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 ')); + } + + public function testThePathIsComparedAsTheRouterDecodedIt(): void + { + $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 + { + 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}']]); + } + + public function testEndpointMessagesUseTheRealUrl(): void + { + 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 new file mode 100644 index 000000000..3cd77921b --- /dev/null +++ b/tests/Input/EscapeTest.php @@ -0,0 +1,244 @@ +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 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 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..1e4cc9cdf --- /dev/null +++ b/tests/Input/FileUploadTest.php @@ -0,0 +1,422 @@ + */ + 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 = []; + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_SERVER['CONTENT_TYPE'] = 'multipart/form-data; boundary=x'; + RequestInput::reset(); + PathValues::reset(); + } + + public function testDefaultMediaTypesWithAFileAreJsonAndMultipart(): void + { + // a required file cannot be sent as JSON, so only multipart is advertised for it + $this->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 testListLeavesOutTheInputsTheClientLeftEmpty(): void + { + $_POST = ['issuedOn' => '24.12.2026', 'copies' => '1']; + $_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']); + } + + /** + * @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()); + } + + 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/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..488f8ba18 --- /dev/null +++ b/tests/Input/Fixtures/Dependency/DependencyInput.php @@ -0,0 +1,16 @@ + $levels */ + public function __construct( + #[Body] #[Cast(DependencyCaster::class)] public string $name, + #[Body] public DependencyEnum $kind, + #[Body] public array $levels, + #[Body] #[DependencyConstraint] public string $note = '', + #[Body] #[Length(max: DependencyLimits::TITLE)] public string $title = DependencyDefaults::TITLE, + ) { + } +} 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 @@ + + */ + #[\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/SecondScope.php b/tests/Input/Fixtures/SecondScope.php new file mode 100644 index 000000000..bb7a9f38c --- /dev/null +++ b/tests/Input/Fixtures/SecondScope.php @@ -0,0 +1,18 @@ + $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 @@ + $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 new file mode 100644 index 000000000..c2cc5fcef --- /dev/null +++ b/tests/Input/Fixtures/create-order-export.json @@ -0,0 +1,276 @@ +{ + "@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": { + "enum": "Tomaj\\NetteApi\\Input\\Source", + "value": "body" + }, + "typeName": "string", + "nullable": false, + "hasDefault": false, + "default": null, + "description": null, + "examples": [], + "listItem": null, + "enumClass": null, + "enumInt": false, + "enumValues": [], + "constraints": [ + { + "@class": "Tomaj\\NetteApi\\Validation\\Email" + } + ], + "casterClass": null, + "casterArguments": [], + "casterSchema": null, + "children": [], + "item": null, + "dtoClass": "Tomaj\\NetteApi\\Test\\Input\\Fixtures\\CreateOrderInput" + }, + { + "@class": "Tomaj\\NetteApi\\Input\\Field", + "property": "address", + "externalName": "address", + "source": { + "enum": "Tomaj\\NetteApi\\Input\\Source", + "value": "body" + }, + "typeName": "Tomaj\\NetteApi\\Test\\Input\\Fixtures\\AddressInput", + "nullable": false, + "hasDefault": false, + "default": null, + "description": null, + "examples": [], + "listItem": null, + "enumClass": null, + "enumInt": false, + "enumValues": [], + "constraints": [], + "casterClass": null, + "casterArguments": [], + "casterSchema": null, + "children": [ + { + "@class": "Tomaj\\NetteApi\\Input\\Field", + "property": "street", + "externalName": "street", + "source": { + "enum": "Tomaj\\NetteApi\\Input\\Source", + "value": "body" + }, + "typeName": "string", + "nullable": false, + "hasDefault": false, + "default": null, + "description": null, + "examples": [], + "listItem": null, + "enumClass": null, + "enumInt": false, + "enumValues": [], + "constraints": [ + { + "@class": "Tomaj\\NetteApi\\Validation\\Length", + "min": 1, + "max": 120 + } + ], + "casterClass": null, + "casterArguments": [], + "casterSchema": null, + "children": [], + "item": null, + "dtoClass": "Tomaj\\NetteApi\\Test\\Input\\Fixtures\\AddressInput" + }, + { + "@class": "Tomaj\\NetteApi\\Input\\Field", + "property": "postalCode", + "externalName": "postalCode", + "source": { + "enum": "Tomaj\\NetteApi\\Input\\Source", + "value": "body" + }, + "typeName": "string", + "nullable": false, + "hasDefault": false, + "default": null, + "description": null, + "examples": [], + "listItem": null, + "enumClass": null, + "enumInt": false, + "enumValues": [], + "constraints": [ + { + "@class": "Tomaj\\NetteApi\\Validation\\Pattern", + "pattern": "/^[0-9]{5}$/" + } + ], + "casterClass": null, + "casterArguments": [], + "casterSchema": null, + "children": [], + "item": null, + "dtoClass": "Tomaj\\NetteApi\\Test\\Input\\Fixtures\\AddressInput" + } + ], + "item": null, + "dtoClass": "Tomaj\\NetteApi\\Test\\Input\\Fixtures\\CreateOrderInput" + }, + { + "@class": "Tomaj\\NetteApi\\Input\\Field", + "property": "items", + "externalName": "items", + "source": { + "enum": "Tomaj\\NetteApi\\Input\\Source", + "value": "body" + }, + "typeName": "array", + "nullable": false, + "hasDefault": false, + "default": null, + "description": null, + "examples": [], + "listItem": "Tomaj\\NetteApi\\Test\\Input\\Fixtures\\ItemInput", + "enumClass": null, + "enumInt": false, + "enumValues": [], + "constraints": [ + { + "@class": "Tomaj\\NetteApi\\Validation\\Length", + "min": 1, + "max": 50 + } + ], + "casterClass": null, + "casterArguments": [], + "casterSchema": null, + "children": [], + "item": { + "@class": "Tomaj\\NetteApi\\Input\\Field", + "property": "items", + "externalName": "items", + "source": { + "enum": "Tomaj\\NetteApi\\Input\\Source", + "value": "body" + }, + "typeName": "Tomaj\\NetteApi\\Test\\Input\\Fixtures\\ItemInput", + "nullable": false, + "hasDefault": false, + "default": null, + "description": null, + "examples": [], + "listItem": null, + "enumClass": null, + "enumInt": false, + "enumValues": [], + "constraints": [], + "casterClass": null, + "casterArguments": [], + "casterSchema": null, + "children": [ + { + "@class": "Tomaj\\NetteApi\\Input\\Field", + "property": "sku", + "externalName": "sku", + "source": { + "enum": "Tomaj\\NetteApi\\Input\\Source", + "value": "body" + }, + "typeName": "string", + "nullable": false, + "hasDefault": false, + "default": null, + "description": null, + "examples": [], + "listItem": null, + "enumClass": null, + "enumInt": false, + "enumValues": [], + "constraints": [], + "casterClass": null, + "casterArguments": [], + "casterSchema": null, + "children": [], + "item": null, + "dtoClass": "Tomaj\\NetteApi\\Test\\Input\\Fixtures\\ItemInput" + }, + { + "@class": "Tomaj\\NetteApi\\Input\\Field", + "property": "quantity", + "externalName": "quantity", + "source": { + "enum": "Tomaj\\NetteApi\\Input\\Source", + "value": "body" + }, + "typeName": "int", + "nullable": false, + "hasDefault": false, + "default": null, + "description": null, + "examples": [], + "listItem": null, + "enumClass": null, + "enumInt": false, + "enumValues": [], + "constraints": [ + { + "@class": "Tomaj\\NetteApi\\Validation\\Range", + "min": 1, + "max": null + } + ], + "casterClass": null, + "casterArguments": [], + "casterSchema": null, + "children": [], + "item": null, + "dtoClass": "Tomaj\\NetteApi\\Test\\Input\\Fixtures\\ItemInput" + } + ], + "item": null, + "dtoClass": "Tomaj\\NetteApi\\Test\\Input\\Fixtures\\CreateOrderInput" + }, + "dtoClass": "Tomaj\\NetteApi\\Test\\Input\\Fixtures\\CreateOrderInput" + }, + { + "@class": "Tomaj\\NetteApi\\Input\\Field", + "property": "deliveryAt", + "externalName": "deliveryAt", + "source": { + "enum": "Tomaj\\NetteApi\\Input\\Source", + "value": "body" + }, + "typeName": "DateTimeImmutable", + "nullable": true, + "hasDefault": true, + "default": null, + "description": null, + "examples": [], + "listItem": null, + "enumClass": null, + "enumInt": false, + "enumValues": [], + "constraints": [], + "casterClass": null, + "casterArguments": [], + "casterSchema": null, + "children": [], + "item": null, + "dtoClass": "Tomaj\\NetteApi\\Test\\Input\\Fixtures\\CreateOrderInput" + } + ], + "contentTypes": [ + "application/json", + "application/x-www-form-urlencoded" + ], + "bodyRequired": true, + "readsBody": true, + "firstBody": "customerEmail" +} diff --git a/tests/Input/RequestInputTest.php b/tests/Input/RequestInputTest.php new file mode 100644 index 000000000..2b36440e5 --- /dev/null +++ b/tests/Input/RequestInputTest.php @@ -0,0 +1,57 @@ +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([MediaTypes::JSON], true, true); + $this->fail(sprintf('attempt %d accepted text/plain', $attempt)); + } catch (UnsupportedMediaTypeException) { + $this->assertNull(RequestInput::mediaType()); + } + } + } + + public function testEveryReadOfAHandlersParamsSeesTheCurrentRequest(): void + { + $_GET = ['page' => '2']; + $this->assertSame(2, new ParamsProcessor(new ListUsersHandler()->params())->getValues()['page']); + + $_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/Input/ScalarCoercerTest.php b/tests/Input/ScalarCoercerTest.php new file mode 100644 index 000000000..8c899ce5b --- /dev/null +++ b/tests/Input/ScalarCoercerTest.php @@ -0,0 +1,201 @@ +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()); + } + } + + /** + * @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/TraitFixtures/Casters/ItemsCaster.php b/tests/Input/TraitFixtures/Casters/ItemsCaster.php new file mode 100644 index 000000000..38022a0b1 --- /dev/null +++ b/tests/Input/TraitFixtures/Casters/ItemsCaster.php @@ -0,0 +1,13 @@ + + */ + 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 new file mode 100644 index 000000000..2ae998a97 --- /dev/null +++ b/tests/Input/TypeNameTest.php @@ -0,0 +1,172 @@ +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 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 = '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..b0a394e0c --- /dev/null +++ b/tests/Link/ApiLinkTest.php @@ -0,0 +1,86 @@ +link(new EndpointIdentifier('GET', 1, 'users', '{id}/detail'), ['id' => 'a b', 'q' => 1, 'package' => 'ignored']); + + $this->assertSame('https://example.com/api/v1/users/a%20b/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); + } + + /** + * @return \Iterator + */ + public static function valuesThatLeadElsewhere(): \Iterator + { + yield 'empty' => ['']; + yield 'dot' => ['.']; + yield 'dot dot' => ['..']; + yield 'false' => [false]; + yield 'slash' => ['a/b']; + } + + #[DataProvider('valuesThatLeadElsewhere')] + public function testAPathValueThatWouldLeadElsewhereIsRejected(mixed $value): void + { + $endpoint = new EndpointIdentifier('GET', 1, 'users', '{id}/detail'); + $this->expectException(InvalidLinkException::class); + $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 c15e52aa0..e6082e8a9 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,244 @@ 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 2x ', 'limit' => '5', 'X-Request-Id' => "abc\r\nX-Evil: 1"]); + + $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()); + } + + 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 testADotPathValueOrASlashIsNotSentButExplained(): void + { + 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("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()); + } + } + + 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("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()); + $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/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 55996371f..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([ @@ -47,6 +61,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([ @@ -67,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..fcf187583 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,185 @@ 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', 'nullable' => true]])->setContentTypes($types), + new BodyInputParam('address')->setOpenApiSchema($address)->setContentTypes($types), + new BodyInputParam('status')->setOpenApiSchema(['type' => 'string', 'enum' => [null, 'a', 'b'], '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', 'b']], + ], + 'required' => ['tags[]'], + ], + 'encoding' => ['address' => ['style' => 'deepObject', 'explode' => true]], + ], $body['content'][$form], $form); + } + } + + 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']]]]; + $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'])); + $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 + { + $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 new file mode 100644 index 000000000..e3759af90 --- /dev/null +++ b/tests/OpenApi/TypedInputOpenApiTest.php @@ -0,0 +1,328 @@ +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 testNestedBodyWithListOfObjectsIsDocumentedOnlyAsJson(): 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']); + // `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([ + 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); + } + + 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 new file mode 100644 index 000000000..807cb1226 --- /dev/null +++ b/tests/OpenApi/snapshots/typed-create-order.json @@ -0,0 +1,65 @@ +{ + "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" + ] + } + } + } +} 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/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..b935fd5dc --- /dev/null +++ b/tests/Params/PathHeaderBodyParamTest.php @@ -0,0 +1,276 @@ +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 + { + $_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()); + + $_POST = []; + $_SERVER['CONTENT_TYPE'] = 'application/json'; + RequestInput::setRawBody('{"name":"Grace","extra":1}'); + $this->assertSame('Grace', $param->getValue()); + + 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()); + + unset($_SERVER['REQUEST_METHOD']); + $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; + 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'; + $_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 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') + ->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()); + } + + 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/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..62ad5d9e4 --- /dev/null +++ b/tests/Presenters/ApiPresenterUnsupportedMediaTypeTest.php @@ -0,0 +1,234 @@ + */ + 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; + $_POST = []; + $_FILES = []; + RequestInput::setRawBody(null); + RequestInput::reset(); + PathValues::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')); + } + + 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, $presenter->response->getCode()); + $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']); + } + + 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; + } + + 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'; + $_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(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 new file mode 100644 index 000000000..a2b13d389 --- /dev/null +++ b/tests/TypedEndpointMatchTest.php @@ -0,0 +1,309 @@ +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', null); + $this->assertInstanceOf(AlwaysOkHandler::class, $exact->getHandler()); + + $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', null); + $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', 'detail'); + $this->assertSame($handler, $matched->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 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()); + $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')); + $this->assertNull($decider->matchPath('GET', '1', 'users', '42', '')); + $this->assertInstanceOf(UserDetailHandler::class, $decider->matchPath('GET', '1', 'users', '42', 'detail')?->getHandler()); + } + + 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('POST', 1, 'users', '{slug}'), new UserDetailHandler(), new NoAuthorization()); + $decider->addApi(new EndpointIdentifier('GET', 2, 'users', '{slug}'), new UserDetailHandler(), new NoAuthorization()); + + $this->expectException(\LogicException::class); + $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 + { + $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', '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', '', '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', 'detail'); + $this->assertSame('42', $named?->getEndpoint()->getApiAction()); + + $matched = $decider->matchPath('get', '1', '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 $params): Api + { + $api = $decider->getApi($method, $version, $package, $apiAction); + + return $api->getHandler() instanceof DefaultHandler ? ($decider->matchPath($method, $version, $package, $apiAction, $params) ?? $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', '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', null); + $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', 'detail'); + $this->assertInstanceOf(DefaultHandler::class, $post->getHandler()); + $withPreflight = self::resolve($decider, 'GET', '1', 'users', '7', 'detail'); + $this->assertInstanceOf(UserDetailHandler::class, $withPreflight->getHandler()); + $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; + } +} diff --git a/tests/Validation/PatternTest.php b/tests/Validation/PatternTest.php new file mode 100644 index 000000000..ebca714ff --- /dev/null +++ b/tests/Validation/PatternTest.php @@ -0,0 +1,272 @@ +clean(); + } + + protected function tearDown(): void + { + $this->clean(); + } + + 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()); + } + + /** + * @return \Iterator + */ + public static function ecmaCompatiblePatterns(): \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('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 portability(): \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('portability')] + 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(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)); + $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 NameHandler())); + } + + 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 PatternInput +{ + 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 PatternHandler extends TypedHandler +{ + public function handleDto(PatternInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +} + +final readonly class NameInput +{ + public function __construct(#[Query] #[Pattern('/^\p{Lu}[a-z]+$/u')] public string $name) + { + } +} + +final class NameHandler extends TypedHandler +{ + public function handleDto(NameInput $input): ResponseInterface + { + return new JsonApiResponse(200, []); + } +}