Repository navigation
Releases
Release 2.12
What's Changed
Features
- Named examples for polymorphic request bodies. Swagger UI drops the discriminator property from the "Try it out" sample when the request body root schema is
oneOf+discriminator, so every request from Swagger failed with 422Missing discriminator property.application/jsonrequest bodies referencing a polymorphic schema with#[Discriminator(mapping: ...)]now getcontent.application/json.examples– one example per mapping key, in mapping order:- key = discriminator value,
summary= variant#[Schema(title:)]or schema name,description= variant description valueis composed only from what the variant declares: discriminator value (always first), propertyexample, single-valueenum, nested$refobjects (max 3 levels, cycles skipped), arrays of$refobjects (one item), firstoneOfvariant.readOnly/deprecatedproperties and properties without a value are omitted – nothing is invented.- Responses and multipart bodies are not affected.
- key = discriminator value,
⚠️ Check before upgrading
| Change | What to check |
|---|---|
Hand-written example / examples on #[JsonContent(ref: ...)] in #[RequestBody] were silently dropped; they are now emitted (and suppress generated examples) |
stale hand-written examples now visible in the spec |
Polymorphic request bodies gain examples in the spec |
snapshot tests of the generated spec |
Full Changelog: v2.11...v2.12
Release 2.11
What's Changed
Full code review of the library (10 commits since 2.10, tests 1637 → 1756). Security fixes in file serving, error handling and request parsing; strict input validation where values were silently corrupted; a large OpenAPI correctness pass. Some fixes change behaviour - read "Check before upgrading".
Security
FileResponse::setAllowedDirectories()fails closed: a non-existent directory throws instead of being silently dropped (a typo'd upload dir used to disable the check and serve any file);enforce: truewith an empty list denies everything;fromPath()rejects directories; symlink chains are capped at 32 hops (a symlink cycle used to exhaust memory)SimpleErrorHandler/PsrLogErrorHandler: a Tracy logging failure in production (nologDirectory, PSR-only setups, CLI) no longer turns every 4xx into a 500- Scheme-relative request URIs (
//evil.example/users/1) are routed literally instead of as/users/1(path confusion behind proxies/WAFs) IpMatcher: strict IPv6 validation (1:::2was accepted and could become the client IP fromX-Forwarded-For); trusted-proxy matching canonicalizes IPv6 (2001:DB8::1=2001:db8::1) and IPv4-mapped IPv6 (::ffff:10.0.0.1matches10.0.0.0/8)ErrorResponseBuildermatches sensitive context keys by whole words (camelCase / snake_case / kebab-case):passwordHash,pinCode,api_key,x-auth-tokenare still removed, butauthor,issuingAuthority,shipping,pinned,hashtagsvalidation fields are no longer silently dropped from 422 responses- JSON integer literals beyond 64 bits (
9223372036854775808) are rejected with 400 (JsonDecoder);json_decode()turned them into floats and data-mapper wrapped them toPHP_INT_MINwith a 200 BasicAuthMiddleware: scheme name is case-insensitive per RFC 7235 (basicworks),Basicx <token>is rejected- CORS: a request without
Originagainst an origin whitelist gets no CORS headers (used to sendAccess-Control-Allow-Origin: *next toAllow-Credentials: true)
⚠️ Check before upgrading
| Change | What to check |
|---|---|
Duplicate routes fail the container build (Duplicate route GET /users: A::list() and B::index()); /users/{id} vs /users/{slug} counts as a duplicate, #[Alias] included |
copy-pasted paths across controllers (last/first registered used to win silently) |
DateTimeParser is strict: no constructor fallback ('', now, tomorrow, +1 day, 15 January 2024 → 400/422) and calendar overflow (2024-02-30, 25:00) rejected; added Y-m-d\TH:i (datetime-local) and Y-m-d H:i:s |
query DateTime parameters and multipart DTO date fields relying on loose formats |
RateLimitMiddleware returns 429 as a response (with Retry-After, X-RateLimit-*) when an ErrorHandler is autowired - outer middlewares (CORS, RequestId) now decorate it; without a handler it still throws |
code catching the 429 exception around the chain |
RateLimitMiddleware: an ipLimits entry is counted per IP even for authenticated users (the per-IP allowance was checked against a cross-IP per-user counter) |
per-IP limits for logged-in users |
AuditLogMiddleware priority 500 → 400 (runs outside RateLimit/BasicAuth so 401/429 are audited) |
custom middleware ordered relative to it |
cors.enabled: true CORS is ordered by its priority (200) together with middlewares: entries (was always first) |
RequestIdMiddleware / EnforceHttpsMiddleware now run before CORS preflights |
Query parameter sent as an array (?q[]=x) for a scalar type → 400 (controller used to receive the string "Array") |
clients abusing bracket syntax |
Enum parameters follow the backing type: string-backed '1' now matches case One = '1'; int-backed rejects 1.5, 1e0, ' 1' |
numeric-string enum values |
Multipart DTO scalars are validated: count=abc, 12abc, price=1,5 → 422 (was a lossy cast to 0); empty "" on a non-nullable int/float/bool uses the property default, 422 without one |
HTML forms posting empty numeric fields |
Typed #[HeaderParameter] (DateTime, enum) no longer overwrites the raw header; the typed value is bound to the argument |
code reading the converted value back via getHeader() |
paths is always emitted in the OpenAPI document ({} when empty) |
consumers checking for its absence |
OpenAPI changes (regenerate and diff your spec)
- Required = non-nullable property without a default (union types included); properties with a default are optional and the default is emitted as
default;#[Property(required: true)]forces required on nullable properties; static properties are skipped - Discriminator: each
oneOf/anyOfvariant restricts its discriminator property to its mapped value(s) (strict validators no longer see ambiguousoneOf); the variant property keepsdescription/nullable/example/deprecated; numeric-string mapping keys ('1') stay strings forstringproperties #[QueryParameter(schema: new Schema(...))]is converted fully -items,minItems/maxItems,uniqueItems,description, composition - andformat:on the attribute is written to the spec (format: daterestrictsDateTimeparameters toYYYY-MM-DDat runtime too)- Explicit parameter
type:wins over the schema type for runtime conversion #[SecurityScheme]on a controller is now written tocomponents.securitySchemes(it was silently ignored); config entries with the same name win;flows(oauth2) andopenIdConnectUrlare no longer dropped from configured schemes#[Tag(hidden: true)]hides the tag fromtagsand from operations (the built-inOpenApiControllertag no longer leaks)#[Alias]endpoints get a generatedoperationIdinstead of copying the explicit one (ids must be unique)#[OpenApiMerge]deep-merges into generated responses / request bodies (addingheadersto200keeps its description and content)- Unused-schema filter follows
discriminator.mappingand component names containing-or.(no more dangling$ref) #[Response(ref: SomeInterface::class)]produces a schema;JsonContent(properties: [Property(required: true)])emits therequiredlist; multipartarrayproperties aretype: array, items: string, nullable scalars getnullable: true;exclusiveMinimum/exclusiveMaximum/uniqueItemspass through inline schemas
Fixes
- Multipart DTOs: nested objects sent as form fields (
owner[key]=...) are hydrated (was a TypeError), errors prefixed (owner.personId); promoted constructor defaults are applied;DateTimeproperties parse the form value; nested object without a configured serializer is a clearRuntimeStateException - Mutable
\DateTimecontroller arguments no longer TypeError (createFromInterface) - Variadic controller arguments (
string ...$tags) no longer 500 ongetDefaultValue() ApiTestClientcloses its output buffer when the application throws (PHPUnit "risky" tests, shifted buffers)FileResponsesendsContent-Length: 0for empty filesApiExtensioncompiles without aproductionModeparameter (no "Undefined array key" warning)RequestUri::getPath()/getQuery()andApiRequest::getPath()share one implementation
New (optional)
RateLimitMiddleware(..., errorHandler: ErrorHandler)- autowired by the DI extensionSabservis\Api\Utils\JsonDecoder::decode()- 64-bit-safe JSON decodingRouter::routeSignature()- route shape used for duplicate detectionSchema::addSecurityScheme()/getSecuritySchemes(),Schema::addTag(..., hidden:)
Release 2.10
What's Changed
Quarterly security and correctness audit: 58 commits, tests 1445 → 1637. Some fixes change behaviour - read "Check before upgrading".
Dependencies
igorpocta/data-mapper→airora/data-mapper ^1.16(renamed package, namespacePocta\DataMapperunchanged,replace: igorpocta/data-mapper)symfony/cache→^6.4.40 || ^7.4.12(CVE-2026-45073, SQL injection inPdoAdapter::doClear())squizlabs/php_codesniffer(dev) →^4.0.2(CVE-2026-67434)symfony/lockadded as optional (suggest) for atomic rate limiting
⚠️ Check before upgrading
| Change | What to check |
|---|---|
#[Hidden] endpoints are now routable (hidden only from OpenAPI, as documented) |
any #[Hidden] used as an on/off switch - protect with #[Authorize] or middleware |
#[Authorize] is inherited from parent controllers (AND) |
child controllers may start returning 403 |
Middleware priorities: BasicAuthMiddleware 250 → 460 (after RateLimit), EnforceHttpsMiddleware 499 → 20 |
custom middleware with priority 20-499 |
{class: Foo} middleware without priority uses #[MiddlewarePriority] (was fixed 10); Foo(arg: ...) no longer breaks DI |
ordering of such middleware |
Path parameters are URL-decoded (john%20doe → john doe) |
code decoding path params itself (would double-decode) |
FileResponse::fromResource() rewinds seekable handles and sends the whole file |
code relying on fseek() before fromResource() |
FileResponse adds CSP: sandbox to every type except passive ones (PDF, images except SVG, audio, video, fonts, text, CSV, JSON, archives, office docs) |
inline HTML reports / interactive SVG relying on scripts |
Date-only DateTimeImmutable parameter (2024-05-01) = midnight (was current time) |
date range filters |
ApiResponse::list() always emits a JSON array (was an object for non-sequential keys) |
clients handling the object form |
X-HTTP-Method-Override applies to POST only |
clients overriding GET/PUT (overridableMethods: restores it) |
Client X-Request-ID must match [A-Za-z0-9._:=-]{1,128}, otherwise a new UUID is generated |
proxies sending other characters |
JSON body for DTOs: depth limit 64 (jsonDepth), scalar bodies → 400 (was 500), non-empty JSON list → 422 |
deeply nested payloads (raise DataMapperSerializer(jsonDepth: N)) |
Router basePath strips only on a segment boundary (/apiv2 no longer → /v2); /api/api/... unchanged |
clients calling /apiXXX |
Invalid trustedProxies entries fail DI compilation / RateLimitMiddleware constructor (an empty prefix used to trust all IPs) |
api.trustedProxies, RateLimit trustedProxies |
$_SERVER['HTTPS'] = 'off' is treated as plain HTTP |
IIS / proxies setting HTTPS=off behind TLS |
ApiTestClient passes the query string to controllers |
tests calling URLs with ?query |
OpenAPI changes (regenerate and diff your spec)
- Colliding schema names get a namespace prefix (
OrderItemDto,InvoiceItemDto) instead of overwriting each other; inlineoneOf/refand multipart refs point to the right class; classes referenced only from inline request bodies are registered (no more dangling$ref). Pin a name with#[Schema(name: '...')]. - Colliding generated
operationIds are made unique (adminUserList/frontUserList,pingCheckGet/pingCheckPost, aliasescontactList,contactList2numbered by path). Explicit ids never change. #[MapProperty(name: 'user_name')]is documented asuser_name(matches the wire).- Valid OpenAPI 3.0 for
array(items: {}),mixed({}) and?self($ref). - Parameter attributes without
type:take the type and required-ness from the method signature (#[PathParameter(name: 'id')] int $id=integer; method-level#[QueryParameter(name: 'limit')]+int $limit= required, missing → 400 instead of 500). - Arguments with their own attribute no longer produce a bogus query parameter;
#[Hidden]on a DTO property hides it from the schema. #[OutputOnly]→readOnly,#[InputOnly]→writeOnly,#[Ignore]→ omitted.
Fixes
- Router cache references endpoints by a stable key (adding/moving an endpoint no longer calls the wrong method)
- Multipart:
doc[main]/doc[0][1]no longer fatal; invalid enum value → 422 (was 500); int-backed enums work; empty value for nullable properties →null;#[OutputOnly]/#[Ignore]are not hydrated sanitizeFilename()never cuts a UTF-8 character and limits names to 255 bytes (long non-ASCII names no longer hitENAMETOOLONG)- Empty
CONTENT_LENGTH(nginxfastcgi_params) no longer returns 400 ?int $limitwithout default →nullwhen missing; header/cookie argument attributes are injected; hyphenated path variables{user-id}work- CORS:
Vary: Originon every whitelisted response, merged with the app'sVary IpMatcherrejects malformed CIDR prefixes and IPs with a trailing newlineApiApplicationwithout an error handler no longer returns 200 for exceptions
New (optional)
- Atomic rate limiting:
RateLimitMiddleware(..., lockFactory: ...)withsymfony/lock - Parameter attributes on arguments:
get(#[HeaderParameter(name: 'X-API-Key')] string $apiKey) #[Schema(name: '...')]for stable schema namesMethodOverrideMiddleware(overridableMethods: [...])ApiTestClient::withServerParams(),request(serverParams:)- data-mapper 1.16 direction attributes
#[OutputOnly],#[InputOnly],#[Ignore]in JSON, multipart and OpenAPI - Opt-in DTO hardening via the existing
serializeroption:DataMapperSerializer(MapperOptions(publicPropertiesOnly: true, symmetricPropertyPaths: true))- seedocs/security.md(changes responses, off by default)
Known limitations (unchanged, see docs/security.md)
5xx messages are returned verbatim, LoggingMiddleware logs full URIs, /openapi.json has no access control, 429/413 responses lack CORS headers, multipart still casts invalid scalars ("abc" → 0; planned for the next major).
Full Changelog: v2.9.1...v2.10
Release 2.9.1
What's Changed
Symfony Cache 7 support — widened the symfony/cache constraint to ^6.4 || ^7.0. The library only uses stable cache contracts (Symfony Cache Contracts v3, PSR-6, PSR-16), which are unchanged between 6.4 and 7.x, so no code changes were
required.
Projects on PHP 8.2+ can now run Symfony Cache 7; PHP 8.1 stays on 6.4. CI verifies both versions.
Full Changelog: 2.9.0...2.9.1
Release 2.9
Nested object support in multipart/form-data
MultipartEntityHydrator now supports nested object properties in multipart DTO requests. When a form field contains a JSON string and the target property is a typed object (not a scalar or enum), the hydrator automatically deserializes it using the configured EntitySerializer.
Before: Sending agentOwner={"registrationNumber":"000001"} as a multipart field resulted in a TypeError — the raw string was assigned directly to a typed object property.
After: The JSON string is automatically deserialized into the target DTO class.
class UploadRequest
{
public UploadedFile $file;
public ?AgentOwnerRequest $agentOwner = null; // ← now works from JSON string
}EntitySerializer is injected as an optional dependency — no breaking changes to existing code.
Release 2.8
Nové funkce
ErrorResponseBuilder jako DI služba s autowiring hooky
ErrorResponseBuilder je nyní registrován jako služba v DI kontejneru. Přidány tři nové rozhraní pro customizaci chybových odpovědí:
TraceIdProvider— přidátraceIddo chybové odpovědi (např. pro korelaci logů)ErrorContextFilter— filtruje context data před odesláním klientoviErrorResponseTransformer— modifikuje celou chybovou odpověď před serializací do JSON
Stačí zaregistrovat implementaci rozhraní jako službu v DI kontejneru — framework ji automaticky autowirne do builderu. Žádná další konfigurace není potřeba.
// Příklad: implementace TraceIdProvider
class MyTraceIdProvider implements TraceIdProvider
{
public function get(): ?string
{
return RequestContext::getTraceId();
}
}services:
- MyTraceIdProviderNová konfigurační volba errorResponse.includeContext (bool) umožňuje globálně zapnout/vypnout odesílání context dat v chybových odpovědích.
api:
errorResponse:
includeContext: falseMultipart DTO podpora
Plná podpora pro hydrataci DTO z multipart požadavků. Atribut #[FileUpload] lze nyní použít na properties a parametry. MultipartEntityHydrator automaticky napojí soubory i skalární pole do DTO.
Wrapped list response typ
Nový response typ pro seznamy obalené do data klíče bez metadat. ListResponse a PaginatedListResponse jsou nyní oddělené třídy.
Tag attribute dědičnost
Atribut #[Tag] se nyní dědí z rodičovského controlleru — není potřeba ho opakovat na každém endpointu.
ValidatorResolver pro DI-based validátory
Podpora pro custom constraint validátory řešené přes DI kontejner. Validace request DTO je nyní zapnutá ve výchozím stavu.
Opravy
- DateTime typy v OpenAPI —
DateTimese nyní mapuje nastrings formátemdate-timemísto$ref - OpenAPI Property na promoted constructor parametrech — atribut
#[Property]nyní funguje i na promoted parametrech v konstruktoru - JsonSerializable na list response typech —
ListResponseaPaginatedListResponseimplementujíJsonSerializable - Přejmenování
total→totalCountv paginovaných odpovědích - Detekce konfliktů FileUpload — detekce se nyní provádí před parsováním atributů, čímž se předchází přepsání
Breaking changes ⚠️
ErrorResponseBuildersettery přijímajíInterface|\Closuremístocallable— pokud jste předávali jiný callable typ (pole, stringy), je potřeba přepsat na Closure nebo implementaci rozhraníListResponserozdělen naListResponse(jednoduchý seznam) aPaginatedListResponse(s metadaty)totalpřejmenováno natotalCountv paginovaných odpovědích- Výchozí list response formát změněn na data-wrapped response
- Validace request DTO je nyní zapnutá ve výchozím stavu
Release 2.7
List response refaktoring
Breaking changes
ApiResponse::list() default je nyní data-wrapped
Dříve ApiResponse::list($data) vracelo plain array [...].
Nyní vrací {"data": [...]}.
// DŘÍVE: [{"id": 1}, {"id": 2}]
// NYNÍ: {"data": [{"id": 1}, {"id": 2}]}
return ApiResponse::list($items);Pro zachování starého chování přidej unwrapped: true:
return ApiResponse::list($items, unwrapped: true);
// → [{"id": 1}, {"id": 2}]total přejmenováno na totalCount
V ListMeta, ApiResponse::list(), PaginatedListResponse::create() a OpenAPI schématech.
// DŘÍVE
ApiResponse::list($items, total: 100, limit: 20, offset: 0);
// NYNÍ
ApiResponse::list($items, totalCount: 100, limit: 20, offset: 0);JSON output:
{
"data": [...],
"meta": {"totalCount": 100, "limit": 20, "offset": 0}
}ListResponse rozdělen na dva typy
| Třída | Účel | JSON output |
|---|---|---|
ListResponse |
Plain array (unwrapped) | [...] |
PaginatedListResponse |
Data wrapper / paginace | {"data": [...]} nebo {"data": [...], "meta": {...}} |
Oba implementují JsonSerializable — fungují s jakýmkoli serializerem.
#[OA\Response] atribut
| Zápis | OpenAPI schema | JSON output |
|---|---|---|
#[Response(listRef: Dto::class)] |
{data: [Dto]} |
{"data": [...]} |
#[Response(listRef: Dto::class, unwrapped: true)] |
[Dto] |
[...] |
#[Response(listRef: Dto::class, withMeta: true)] |
{data: [Dto], meta: {...}} |
{"data": [...], "meta": {...}} |
Release 2.6
DateTime, DateTimeImmutable a DateTimeInterface property v DTO se dříve chybně generovaly jako $ref na prázdné schema ({}). Nyní se správně mapují na type: string, format: date-time.
Nově:
- Automatická detekce DateTime typů v DTO properties (včetně nullable)
- Override formátu na date:
#[Property(format: 'date')] - Type shorthand:
#[Property(type: 'date')]se automaticky rozloží na type: string, format: date
class EventDto
{
public DateTimeImmutable $createdAt; // string, date-time
#[Property(format: 'date')]
public DateTimeImmutable $birthDate; // string, date
#[Property(type: 'date')]
public DateTimeImmutable $signedDate; // string, date
}
Release 2.5
#[Tag] atribut se nyní dědí z rodičovských tříd. Pokud child controller nemá vlastní #[Tag], automaticky zdědí tagy z nejbližšího rodiče v hierarchii.
#[Tag(name: 'trades', description: 'Trade operations')]
abstract class BaseTradeController implements Controller {}
// Zdědí tag 'trades' automaticky
final class TradeSubmitController extends BaseTradeController { }
// Vlastní tag kompletně přepíše rodičovský
#[Tag(name: 'special-trades')]
final class SpecialTradeController extends BaseTradeController { }
Chování je konzistentní s existující dědičností #[Authorize] a s pravidlem method vs. controller (vlastní definice vždy přepíše zděděnou).
Release 2.4
Multipart DTO - soubory + formulářová pole v jednom requestu
Nová podpora pro DTO, které kombinují běžné properties a soubory v jednom multipart/form-data požadavku.
Co je nového:
- Atribut #[FileUpload] lze nově použít přímo na DTO properties (nejen na controller metody)
- Automatická detekce multipart DTO v RequestBodyBuilder - pokud DTO obsahuje #[FileUpload] properties, generuje se multipart/form-data schema místo application/json
- MultipartEntityHydrator - nový hydrátor, který z multipart requestu sestaví plně typované DTO (formulářové hodnoty + soubory)
- Napojení do ApiDispatcher - runtime hydratace multipart DTO funguje automaticky bez zásahu uživatele
- Detekce konfliktů - nelze kombinovat #[FileUpload] na metodě a zároveň mít DTO s FileUpload properties
- Podpora v OpenApiGenerator - správné generování OpenAPI spec pro multipart DTO