Skip to content

Releases

Release 2.12

Choose a tag to compare

@igorpocta igorpocta released this 03 Nov 16:15

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 422 Missing discriminator property. application/json request bodies referencing a polymorphic schema with #[Discriminator(mapping: ...)] now get content.application/json.examples – one example per mapping key, in mapping order:
    • key = discriminator value, summary = variant #[Schema(title:)] or schema name, description = variant description
    • value is composed only from what the variant declares: discriminator value (always first), property example, single-value enum, nested $ref objects (max 3 levels, cycles skipped), arrays of $ref objects (one item), first oneOf variant. readOnly / deprecated properties and properties without a value are omitted – nothing is invented.
    • Responses and multipart bodies are not affected.

⚠️ 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

Choose a tag to compare

@igorpocta igorpocta released this 03 Nov 07:54

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: true with 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 (no logDirectory, 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:::2 was accepted and could become the client IP from X-Forwarded-For); trusted-proxy matching canonicalizes IPv6 (2001:DB8::1 = 2001:db8::1) and IPv4-mapped IPv6 (::ffff:10.0.0.1 matches 10.0.0.0/8)
  • ErrorResponseBuilder matches sensitive context keys by whole words (camelCase / snake_case / kebab-case): passwordHash, pinCode, api_key, x-auth-token are still removed, but author, issuingAuthority, shipping, pinned, hashtags validation 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 to PHP_INT_MIN with a 200
  • BasicAuthMiddleware: scheme name is case-insensitive per RFC 7235 (basic works), Basicx <token> is rejected
  • CORS: a request without Origin against an origin whitelist gets no CORS headers (used to send Access-Control-Allow-Origin: * next to Allow-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/anyOf variant restricts its discriminator property to its mapped value(s) (strict validators no longer see ambiguous oneOf); the variant property keeps description / nullable / example / deprecated; numeric-string mapping keys ('1') stay strings for string properties
  • #[QueryParameter(schema: new Schema(...))] is converted fully - items, minItems / maxItems, uniqueItems, description, composition - and format: on the attribute is written to the spec (format: date restricts DateTime parameters to YYYY-MM-DD at runtime too)
  • Explicit parameter type: wins over the schema type for runtime conversion
  • #[SecurityScheme] on a controller is now written to components.securitySchemes (it was silently ignored); config entries with the same name win; flows (oauth2) and openIdConnectUrl are no longer dropped from configured schemes
  • #[Tag(hidden: true)] hides the tag from tags and from operations (the built-in OpenApiController tag no longer leaks)
  • #[Alias] endpoints get a generated operationId instead of copying the explicit one (ids must be unique)
  • #[OpenApiMerge] deep-merges into generated responses / request bodies (adding headers to 200 keeps its description and content)
  • Unused-schema filter follows discriminator.mapping and component names containing - or . (no more dangling $ref)
  • #[Response(ref: SomeInterface::class)] produces a schema; JsonContent(properties: [Property(required: true)]) emits the required list; multipart array properties are type: array, items: string, nullable scalars get nullable: true; exclusiveMinimum / exclusiveMaximum / uniqueItems pass 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; DateTime properties parse the form value; nested object without a configured serializer is a clear RuntimeStateException
  • Mutable \DateTime controller arguments no longer TypeError (createFromInterface)
  • Variadic controller arguments (string ...$tags) no longer 500 on getDefaultValue()
  • ApiTestClient closes its output buffer when the application throws (PHPUnit "risky" tests, shifted buffers)
  • FileResponse sends Content-Length: 0 for empty files
  • ApiExtension compiles without a productionMode parameter (no "Undefined array key" warning)
  • RequestUri::getPath() / getQuery() and ApiRequest::getPath() share one implementation

New (optional)

  • RateLimitMiddleware(..., errorHandler: ErrorHandler) - autowired by the DI extension
  • Sabservis\Api\Utils\JsonDecoder::decode() - 64-bit-safe JSON decoding
  • Router::routeSignature() - route shape used for duplicate detection
  • Schema::addSecurityScheme() / getSecuritySchemes(), Schema::addTag(..., hidden:)

Release 2.10

Choose a tag to compare

@igorpocta igorpocta released this 28 Oct 14:14

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, namespace Pocta\DataMapper unchanged, replace: igorpocta/data-mapper)
  • symfony/cache → ^6.4.40 || ^7.4.12 (CVE-2026-45073, SQL injection in PdoAdapter::doClear())
  • squizlabs/php_codesniffer (dev) → ^4.0.2 (CVE-2026-67434)
  • symfony/lock added 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; inline oneOf/ref and 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, aliases contactList, contactList2 numbered by path). Explicit ids never change.
  • #[MapProperty(name: 'user_name')] is documented as user_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 hit ENAMETOOLONG)
  • Empty CONTENT_LENGTH (nginx fastcgi_params) no longer returns 400
  • ?int $limit without default → null when missing; header/cookie argument attributes are injected; hyphenated path variables {user-id} work
  • CORS: Vary: Origin on every whitelisted response, merged with the app's Vary
  • IpMatcher rejects malformed CIDR prefixes and IPs with a trailing newline
  • ApiApplication without an error handler no longer returns 200 for exceptions

New (optional)

  • Atomic rate limiting: RateLimitMiddleware(..., lockFactory: ...) with symfony/lock
  • Parameter attributes on arguments: get(#[HeaderParameter(name: 'X-API-Key')] string $apiKey)
  • #[Schema(name: '...')] for stable schema names
  • MethodOverrideMiddleware(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 serializer option: DataMapperSerializer(MapperOptions(publicPropertiesOnly: true, symmetricPropertyPaths: true)) - see docs/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

Choose a tag to compare

@igorpocta igorpocta released this 29 Jun 15:41

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

Choose a tag to compare

@igorpocta igorpocta released this 12 Mar 19:37

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

Choose a tag to compare

@igorpocta igorpocta released this 04 Mar 09:14

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á traceId do chybové odpovědi (např. pro korelaci logů)
  • ErrorContextFilter — filtruje context data před odesláním klientovi
  • ErrorResponseTransformer — 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:
    - MyTraceIdProvider

Nová 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: false

Multipart 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 — DateTime se nyní mapuje na string s formátem date-time místo $ref
  • OpenAPI Property na promoted constructor parametrech — atribut #[Property] nyní funguje i na promoted parametrech v konstruktoru
  • JsonSerializable na list response typech — ListResponse a PaginatedListResponse implementují JsonSerializable
  • Přejmenování total → totalCount v 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 ⚠️

  • ErrorResponseBuilder settery přijímají Interface|\Closure místo callable — pokud jste předávali jiný callable typ (pole, stringy), je potřeba přepsat na Closure nebo implementaci rozhraní
  • ListResponse rozdělen na ListResponse (jednoduchý seznam) a PaginatedListResponse (s metadaty)
  • total přejmenováno na totalCount v 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

Choose a tag to compare

@igorpocta igorpocta released this 28 Feb 20:47

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

Choose a tag to compare

@igorpocta igorpocta released this 17 Feb 20:54

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

Choose a tag to compare

@igorpocta igorpocta released this 17 Feb 12:10

#[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

Choose a tag to compare

@igorpocta igorpocta released this 13 Feb 14:07

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