Skip to content

Release 1.14

Choose a tag to compare

@igorpocta igorpocta released this 28 Oct 08:55

What's Changed

Security Fixes

  • Cyclic object graphs crashed #[Valid] validation — a parent ↔ child cycle (or an object referencing itself)
    with #[Valid] recursed without bound and ended in a fatal "Allowed memory size exhausted" error — a DoS vector
    when validating user-influenced graphs. The validator now skips an object that is already on the current
    recursion path. Objects shared by several branches (acyclic graphs) are still validated on every path.
  • Validation silently skipped after a CircularReferenceException — the exception was thrown after the
    nested denormalizer had pushed its state, so the state was never cleaned up. On a reused Mapper (DI singleton,
    long-running worker) every later call then kept old errors, and a repeated error with the same key
    (e.g. a missing required leaf.n) was no longer reported — the object was returned with an uninitialized
    property. The cycle check now runs before any state is pushed. Self-nested classes are still rejected with
    CircularReferenceException as before.
  • Cache integrity — FileCache and RedisCache accept an optional signingKey: entries are HMAC-signed and
    only unserialized with a valid signature, so write access to the cache storage no longer allows object
    injection. Without a key, behaviour is unchanged. FileCache files now start with <?php exit; ?>, so
    executing a cache file as PHP does nothing; older files are still read.

Bug Fixes

  • #[Valid] was skipped after a failing assert on the same property — with #[Count(min: 5)] #[Valid], a
    failing Count stopped processing, so errors of nested items were never reported, while #[Valid] #[Count]
    reported them (attribute-order dependent). #[Valid] now always runs; still only the first failing assert per
    property is reported, as before.
  • skipNullValues was ignored for elements of an array of objects — #[MapProperty(arrayOf: Foo::class)]
    elements kept their null properties in output, while nested objects dropped them. Without skipNullValues
    output is unchanged.
  • ToIntFilter / ToFloatFilter did not strip non-breaking spaces — the NBSP was written as '\u{00A0}'
    (single quotes = literal text), so "1\u{00A0}000" (common thousands separator, e.g. Czech/French formatting)
    stayed a string. It now converts to 1000, consistent with ToDecimalStringFilter. All other inputs behave as
    before (covered by new characterization tests).
  • FileCache and ArrayCache lost cached null values — after set('k', null), has('k') returned true
    but get('k', $default) returned the default (FileCache also deleted the file). A stored null is now returned.
    Other values, including false, 0 and '', behave as before.
  • Direct Denormalizer use leaked the root payload — the root payload was never released, so a second
    denormalize() call on the same instance passed the first call's payload to HydrationMode::FULL hydrators.
    With a discriminator, the abstract class also stayed in the cycle-detection map.
  • toCsv() normalized the first object twice — once for the header and again for its row, so
    PreNormalizeEvent / PostNormalizeEvent fired twice for it. Each object is now normalized exactly once;
    CSV output is unchanged.
  • Profiler stack leaked on failed operations — denormalize, validation, normalize and a failing
    PreDenormalizeEvent listener left entries on Profiler::getStack(), so it grew with every failed request in a
    long-running worker. Nested operations with the same name (e.g. fromArray() called from a listener) overwrote
    each other's start time, so the outer one was never counted. Metrics of successful operations are unchanged.
  • Debugger opened php://stderr on construction — even when disabled or not in debug mode. The stream is now
    opened on the first debug write; output is unchanged.
  • Filters took effect twice during denormalization — filters ran on the raw input and again on the typed
    value, so non-idempotent filters applied twice: #[HashFilter] hashed twice (password_verify() failed),
    Base64Decode/EncodeFilter decoded/encoded twice, HtmlEntitiesEncodeFilter and UrlEncodeFilter escaped twice,
    SubstringFilter/SliceArrayFilter cut twice, PriceRoundFilter broke negative values. Every filter now takes
    effect once: a filter that changed the raw value does not run again after type conversion; filters without
    effect on the raw value (e.g. AddIntervalFilter on a date string) still run on the typed value. Idempotent
    filters (trim, case, ToIntFilter, ...) give the same results as before. Normalization was not affected.
  • fromCsvFile() silently produced wrong objects for a file starting with a blank line — the blank line was
    taken as the header, the real header row was mapped as data and all objects got default values without any
    error. fromCsv() and fromCsvFile() now share one parser (fromCsv() already skipped blank lines before the
    header); results for all other inputs are unchanged.
  • RedisCache did not work with Predis at all — the client check looked for get()/set() methods, but Predis
    implements commands via __call, so a real Predis\Client was rejected; ping() also ignored Predis' Status
    response. Predis is now recognised by its interface and verified against a real Redis server.
  • InvalidInputException is now a ValidationException (introduced in 1.12 as a plain
    InvalidArgumentException). Code that turns ValidationException into a client-error response - e.g. a request
    body serializer - did not catch it, so a JSON list sent where an object is expected ended in an unhandled
    exception (HTTP 500). It now carries the error under the path '' (whole input) or '[n]' (collection element);
    it is still an InvalidArgumentException and the message is unchanged.
  • Tree structures failed with CircularReferenceException — a class nested in itself, directly
    (?Node $child) or through other classes (client → assignment → client), and even siblings of the same class in
    nested arrays were rejected as a "circular reference", although input arrays are finite trees. They now map at
    any depth. Only a recursive PHP array reference ($a['x'] = &$a) is cut off by a depth limit of 512, reported
    as a validation error (InvalidInputException) instead of endless recursion. Normalization still detects real
    object cycles.
  • throwOnMissingData and runtime setStrictMode() / setThrowOnMissingData() applied to the root object
    only
    — nested objects and arrays of objects kept the values from construction. They now follow the mapper's
    current options. Default options behave as before.

New Features

  • MapperOptions::$parseFormattedNumbers (default false) — int and float properties accept formatted
    numeric strings sent by frontends: "10 000" / NBSP / narrow NBSP as thousands separators and a single comma as
    the decimal separator ("1 234,50" → 1234.5). Ambiguous input ("1.000,5", "1,2,3") and an int with a
    non-zero fraction ("12,5") are rejected — never truncated silently. Applies to nested objects and
    arrayOf: ArrayElementType::Int/Float elements. Without the option, behaviour is unchanged.
  • Debugger(maxLogEntries: N) — optional cap on in-memory log entries (newest kept) for long-running
    processes. Default null keeps the previous unlimited behaviour.
  • MapperOptions::api() — preset for untrusted HTTP request bodies: auto-validation, strict mode, required data
    enforced, public properties only, symmetric property paths, JSON depth 64. Adjust with with().
  • ValidationException accepts an optional $previous exception and implements JsonSerializable
    (json_encode($e) gives the same structure as toApiResponse()).
  • Psr16Cache — adapter for any PSR-16 cache (Symfony, Laravel, ...); mapper keys are hashed into PSR-16
    safe keys. psr/simple-cache is only suggested - the library keeps zero runtime dependencies.
  • Placeholders in custom validation messages — {{ name }}, {{ value }} and any public validator option
    ({{ min }}, {{ max }}, {{ choices }}, ...). Messages without {{ are unchanged.

Performance

  • RedisCache uses SCAN instead of KEYS for clear(), size() and keys() — KEYS blocks the whole
    Redis server while walking the keyspace. Results are the same (deduplicated); verified against a real Redis
    server with phpredis, including a multi-batch keyspace and foreign keys left untouched.
  • Events are created only when someone listens — fromArray() / toArray() allocated and dispatched
    pre/post/validation events on every call. Without listeners the result is identical, so they are skipped:
    small objects map 13-18 % faster. UnitEnumType resolves cases through a map built once (2.7× faster).
  • Mapping attributes are read in one place — the precedence rules for #[MapProperty] /
    #[MapDateTimeProperty] were copied in Normalizer, Denormalizer (property and parameter variants),
    Mapper::merge() and ClassMetadataFactory, each instantiating the same attribute up to 5×. They now live in
    MappingAttributes (−~740 lines). Side effect: denormalization of an order with 1000 items 52 ms → 34 ms,
    normalization 24 ms → 16 ms. Behaviour is unchanged (the copies were verified identical before merging).
  • Denormalization ~2× faster — Denormalizer caches per-class reflection (constructor, parameters,
    properties, discriminator), attribute-derived field settings and strict-mode known keys, and reuses filter and
    hydrator instances. Filters and hydrators are still instantiated lazily at the same point as before, so a
    misconfigured filter only throws when its value is processed. Only built-in filters are reused; user-defined
    FilterInterface filters are still instantiated on every use (their constructor may depend on time or state). fromArray() of an order with 1000 items:
    105 ms → 51 ms; with strict mode, public-only and validation: 158 ms → 78 ms.
  • Validation ~20 % faster — Validator caches per-class reflection (properties with their attributes, methods
    carrying #[Callback]) and skips properties without attributes. Validator attributes are still instantiated on
    every validation, so time-dependent ones like #[DateTimeLessThan('now')] keep working in long-running processes.
  • DateTime parsing without a format ~4.6× faster — fallback formats that cannot pass the round-trip check are
    skipped up front (e.g. the microsecond ISO format for a value without .), and the DateTimeZone is created
    once per type handler. Accepted and rejected values are unchanged (covered by new characterization tests); an
    invalid timezone still throws on every call.
  • ClassMetadataFactory memoizes metadata in-process — with FileCache / RedisCache, every
    getMetadata() call read and unserialized the backend entry, i.e. per object in fromObject() and per CSV row.
    fromCsv() of 2000 rows with FileCache: 55 ms → 9 ms. clearCache() clears the memo as well.
  • Property paths ~4× faster — PropertyPathResolver reuses parsed path segments (bounded memo, invalid paths
    are not stored and keep throwing). Resolving user.addresses[0].street: 4.6 µs → 1.2 µs per field.
  • Normalization ~3.3× faster — Normalizer resolves each class once into a cached plan (keys, types, formats,
    paths, filter instances, visibility for both public-only settings) instead of re-reading attributes via reflection
    for every object and property. toArray() of an order with 1000 items: 77 ms → 23 ms. Runtime settings
    (public-only, symmetric paths, skip nulls) still apply per call; a misconfigured attribute still throws on every
    call.

Breaking Changes

These change behaviour for code that relied on them. They were verified against the known applications using the
library (none of them uses the affected APIs).

  • #[DiscriminatorProperty] attribute — it was never read by the library (polymorphic mapping is driven only by
    #[DiscriminatorMap(property: ...)]). Migration: delete the attribute and its use statement.

  • DenormalizationErrorEvent::suppressException() and isExceptionSuppressed() — they never had an effect
    (the exception was always re-thrown; returning null would break fromArray()'s return type). Migration: remove
    the calls and catch the exception in the caller; the event is still dispatched for logging/monitoring.

  • RedisCache accepts only real Redis clients — phpredis (Redis) or Predis (Predis\ClientInterface). Before,
    any object whose class name contained Client and had get()/set() was accepted. Migration: pass the
    underlying phpredis/Predis client instead of a custom wrapper.

  • A #[Callback] method returning a non-array value now throws LogicException — a string or bool result was
    silently ignored, so a broken validation rule never reported anything. Return an array of errors (or null).

  • Custom message of Regex, Uuid and Iban is returned as written — it was rewritten
    (Value → Property 'x', UUID → UUID v4), and Uuid ignored it for a version mismatch. Default messages are
    unchanged; use {{ name }} to include the property name in a custom message.

  • merge() follows the same rules as fromArray() — it now supports property paths, filters and hydrators,
    collects all errors into one ValidationException (instead of throwing a raw InvalidArgumentException on the
    first bad value or a TypeError for null in a non-nullable property) and is atomic: on any error the object stays
    unchanged. Keys are matched like in fromArray(): a property renamed with #[MapProperty(name: ...)] is no
    longer also accepted under its PHP name. Modifying an initialized readonly property is a validation error.

Unchanged on purpose

  • NotBlank keeps rejecting 0 / 0.0 for numeric properties (applications rely on it for IDs and amounts).
  • Defaults of publicPropertiesOnly, symmetricPropertyPaths and parseFormattedNumbers stay false - turning
    them on changes response shapes / accepted input; opt in explicitly (e.g. MapperOptions::api()).