Skip to content

Releases

Release 1.16

Choose a tag to compare

@igorpocta igorpocta released this 28 Oct 09:13

What's Changed

Package renamed: airora/data-mapper

The library is now published as airora/data-mapper (repository airoracz/data_mapper). The code is identical
to 1.15 and the PHP namespace Pocta\DataMapper is unchanged.

composer remove igorpocta/data-mapper && composer require airora/data-mapper

airora/data-mapper declares replace: igorpocta/data-mapper (same version), so it also satisfies packages that
still require igorpocta/data-mapper - only one copy is installed. igorpocta/data-mapper stays available up to
1.15 and receives no further releases.

Release 1.15

Choose a tag to compare

@igorpocta igorpocta released this 28 Oct 09:07

What's Changed

New Features

  • Partial updates (PATCH): sent vs. not sent — DTOs implementing ProvidedFieldsInterface (use the
    ProvidedFields trait) get the names of the properties present in the input: $dto->isProvided('note') is
    true also when note was sent as null, so "clear the value" can be told apart from "not sent". Tracked by PHP
    property name (renamed keys, paths, promoted constructor parameters), per nested object / array element, and
    extended by merge(). The tracking is excluded from mapping (never serialized, not hydratable, unknown in strict
    mode). Classes not implementing the interface are unaffected.

Bug Fixes

  • A missing nullable property without a default stayed uninitialized — public ?string $note; not present in the
    input was left uninitialized, so the first read failed with Error: must not be accessed before initialization
    (HTTP 500). It is now set to null, like a nullable constructor parameter already was. If such a property carries
    validators, they now validate null instead of reporting "This field is required.".

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 constru...
Read more

Release 1.13

Choose a tag to compare

@igorpocta igorpocta released this 27 Oct 21:55

What's Changed

Security Fixes

  • #[OutputOnly] / #[Ignore] bypass via constructor — a plain (non-promoted) constructor parameter assigned to
    a property in the constructor body was hydrated from input even when the property carried #[OutputOnly] or
    #[Ignore]:
    class UserDto {
        #[OutputOnly] public string $role;
        public function __construct(public string $name, string $role = 'user') { $this->role = $role; }
    }
    // {"name": "x", "role": "admin"} → $dto->role === 'admin'
    A constructor parameter is now excluded from input when the same-named property carries #[Ignore] or
    #[OutputOnly].
  • PHP 8.4 asymmetric visibility bypassed publicPropertiesOnly — public private(set) and
    public protected(set) properties (including promoted constructor parameters) were hydrated from input, because
    ReflectionProperty::isPublic() reports only read visibility. In public-only mode they are now treated as
    non-public for input (opt-in with #[MapProperty] still works) and remain in output. public readonly properties
    are hydrated as before.
  • publicPropertiesOnly and symmetricPropertyPaths did not apply to nested objects (introduced in 1.12) —
    nested objects and arrays of objects are (de)normalized by type handlers with their own Normalizer /
    shared Denormalizer, which never received the new options. With publicPropertiesOnly: true, private properties
    of nested DTOs still leaked to output and were hydrated from input
    ({"inner": {"secret": "HACKED"}}). Options are now propagated through TypeResolver to all nesting levels,
    including strict-mode unknown-key detection (inner.secret).

Bug Fixes

  • symmetricPropertyPaths silently dropped fields on key collisions — a plain property and a path sharing the
    same output location ($meta and #[MapProperty(path: 'meta.source')]), or two properties with the same path,
    overwrote each other depending on declaration order. Now throws LogicException naming the property and the
    output location (configuration error).
  • Index paths produced JSON objects instead of lists — #[MapProperty(path: 'items[1].name')] normalized to
    {"items": {"1": {...}}}. Missing lower indexes are now filled with null, so the output is a JSON list
    ({"items": [null, {...}]}), also when indexes are written out of order.
  • toCsv() with symmetricPropertyPaths wrote nested arrays into cells (Array to string conversion,
    literal Array). CSV output now always uses flat columns.
  • PropertyPathResolver::set() no longer overwrites an existing scalar when descending into it — throws
    InvalidArgumentException instead.

Behaviour Changes

  • Strict mode accepts #[OutputOnly] keys — they are part of the public contract, so posting a fetched
    resource back (PUT round-trip) no longer fails with Unknown key 'id'. The value is discarded, never hydrated.
    #[Ignore] and non-public keys (in public-only mode) are still reported as unknown. Applies to merge() too.
  • List input to fromArray() is rejected after PreDenormalizeEvent — listeners can now reshape list input
    (e.g. wrap it into an object) before validation, and the rejection dispatches DenormalizationErrorEvent like any
    other mapping error. PreDenormalizeEvent::$data and DenormalizationErrorEvent::$data are documented as
    array<mixed> (input is untrusted).
  • Excluded variadic constructor parameter (#[Ignore] string ...$tags) threw LogicException / received null.
    It now receives no arguments.

Performance

  • Visibility/direction decisions (PropertyVisibilityResolver) are memoized per class member instead of re-reading
    attributes via reflection on every mapping call: ~9 % faster normalization, ~20 % faster denormalization
    (20k objects, public-only + strict mode).
    Remaining overhead: Normalizer / Denormalizer still re-run reflection per object instead of using
    ClassMetadataFactory metadata — candidate for a follow-up refactor.

Release 1.12

Choose a tag to compare

@igorpocta igorpocta released this 27 Oct 21:36
b489242

What's Changed

Security and input-hardening release based on the sabservis/api security audit. All new behaviour that would
change existing output or input handling is opt-in via MapperOptions; defaults stay backward compatible
(except the bug fixes below).

Security Fixes

  • Static properties are never mapped — toArray() / toJson() serialized static properties, and
    fromArray(), fromJson() and merge() overwrote them from input data. A client could change class-level
    state ({"counter": "HACKED"} → Dto::$counter === 'HACKED'), which persists across requests in long-running
    workers (RoadRunner, Swoole). Static properties are now skipped in both directions and reported as unknown keys
    in strict mode. Applies regardless of options.

New Features

  • MapperOptions::$publicPropertiesOnly (default false) — map only public properties. Prevents leaking
    private / protected data (password hashes, tokens) in output and mass assignment of fields outside the public
    contract (role, isAdmin, ownerId) from input.

    • Non-public properties can be opted in explicitly with #[MapProperty] or #[MapDateTimeProperty].
    • Non-promoted constructor parameters are always hydrated.
    • A non-public promoted parameter without opt-in gets its default value (or null); a required one throws
      LogicException (configuration error, not invalid input).
    • Applies to merge() and strict-mode unknown-key detection as well.
  • #[Ignore], #[OutputOnly], #[InputOnly] attributes — per-property control of mapping direction:

    Attribute Output Input
    #[Ignore] skipped skipped
    #[OutputOnly] written skipped (server-controlled fields: id, role)
    #[InputOnly] skipped hydrated (write-only fields: password)

    They always win over #[MapProperty] opt-in. A key skipped on input is reported as unknown in strict mode.

  • MapperOptions::$symmetricPropertyPaths (default false) — properties with #[MapProperty(path: 'address.city')]
    (or MapDateTimeProperty) are normalized back into the same nested structure ({"address": {"city": "..."}})
    instead of a flat key ({"city": "..."}). Output can be fed back to fromArray() and request/response share
    one schema.

  • MapperOptions::$jsonDepth (default 512) — maximum nesting depth for fromJson() and
    fromJsonCollection(). Previously hard-coded to 512. Deeper input throws JsonException; values < 1 throw
    InvalidArgumentException.

  • InvalidInputException (extends InvalidArgumentException) — thrown for input of the wrong shape, so it can
    be told apart from programming errors and mapped to HTTP 400.

  • PropertyPathResolver::set() and PropertyPathResolver::getRootKey() helpers.

Bug Fixes

  • Strict mode rejected the root key of a property path — with #[MapProperty(path: 'address.city')], strict
    mode threw Unknown key 'address' for valid input. The root key of each path is now accepted as known.
  • fromJson() accepted non-object JSON — a JSON list ([1, 2], []) was silently mapped to an object with
    default values. fromJson() now requires a JSON object at the top level and throws InvalidInputException for
    lists, scalars and null (previously a generic InvalidArgumentException for scalars).
  • fromArray() accepted a list — a non-empty list is now rejected with InvalidInputException; an empty array
    is still accepted as an empty object.
  • fromJsonCollection() / fromArrayCollection() crashed with TypeError on a non-object element
    ([{"name": "a"}, 2], HTTP 500). Now throws InvalidInputException with the element index
    (Collection element [1] ...). fromJsonCollection() also rejects a JSON object at the top level.

Backward Compatibility

  • Defaults of all new options keep 1.11 behaviour. Planned for 2.0: publicPropertiesOnly and
    symmetricPropertyPaths default to true.
  • Code catching InvalidArgumentException keeps working — InvalidInputException and ValidationException
    both extend it.
  • Behaviour changes affecting only invalid input: list input to fromJson() / fromArray() is rejected;
    fromArrayCollection() throws InvalidInputException instead of TypeError for non-array elements.
  • PHPDoc of fromArray() / fromArrayCollection() widened to array<mixed> (input may be untrusted).

Recommended Configuration for HTTP APIs

$mapper = new Mapper(new MapperOptions(
    autoValidate: true,
    strictMode: true,
    throwOnMissingData: true,
    publicPropertiesOnly: true,
    symmetricPropertyPaths: true,
    jsonDepth: 64,
));

Do not disable throwOnMissingData for API input — a missing typed property without default would stay
uninitialized and fail on first access (HTTP 500 instead of 422).

Tests

  • StaticPropertyTest (6), PublicPropertiesOnlyTest (16), IgnoreAttributeTest (14), StrictModePathTest (4),
    SymmetricPropertyPathTest (8), InvalidJsonInputTest (19 incl. data sets).
  • BatchProcessingTest::testFromArrayCollectionThrowsOnInvalidItem now expects InvalidInputException.

Documentation

  • docs/configuration.md — new options, Property Visibility, Ignore/OutputOnly/InputOnly, recommended API config.
  • docs/advanced.md — path normalization and strict-mode behaviour.
  • docs/architecture.md — error handling: which exception means 400 vs. 422.

Affected files

  • New: src/PropertyVisibilityResolver.php, src/Attributes/Ignore.php, src/Attributes/OutputOnly.php,
    src/Attributes/InputOnly.php, src/Exceptions/InvalidInputException.php
  • Changed: src/Mapper.php, src/MapperOptions.php, src/Normalizer/Normalizer.php,
    src/Denormalizer/Denormalizer.php, src/PropertyPathResolver.php

Release 1.11

Choose a tag to compare

@igorpocta igorpocta released this 22 Apr 07:49

What's Changed

Bug Fixes

  • Fix TypeError when a parent DTO has an invalid enum and a valid non-nullable typed array on the same level — the shared denormalizer instance (singleton in TypeResolver) reused $this->errors across recursive denormalize() calls. An error from a parent property (e.g. invalid enum value) leaked into nested ObjectType / ArrayType element processing, was re-thrown as a ValidationException, caught as null, and then assigned to a non-nullable property — producing a PHP TypeError (HTTP 500) instead of the expected ValidationException (HTTP 422) with the real field path.

    Concretely: sending {"client": {"entityType": "Legal Entity", "addresses": [...]}} with a bad entityType would fail with Cannot assign null to property ClientSimpleRequest::$addresses of type array instead of a clean validation error on client.entityType.

    The fix isolates errors produced inside each denormalize() invocation from errors inherited from a parent invocation (snapshot + array_diff_key), switches setPropertyValue() from count-based to value-aware error detection (catches same-key overwrites), and adds a defensive guard against assigning null to non-nullable properties.

Tests

  • Add EnumWithArrayErrorIsolationTest with 11 regression cases covering:
    • invalid enum + valid nested array (top-level and nested DTO)
    • valid enum + invalid nested element
    • invalid enum + invalid nested element (both errors surfaced)
    • empty / missing / null nested arrays
    • deep recursion error isolation
    • constructor-based DTO reproduction
    • exact production reproduction via fromJson

Affected files

  • src/Denormalizer/Denormalizer.php — denormalize(), createWithConstructor(), setPropertyValue()

Full Changelog: v1.10...v1.11

Release 1.10

Choose a tag to compare

@igorpocta igorpocta released this 09 Apr 08:13

Features

  • DateTime range validators — new DateTimeGreaterThan, DateTimeLessThan and DateTimeRange validation attributes
  • Null values in normalization — null values are now included in normalization output by default
  • DateTime output format — outputFormat parameter on MapDateTimeProperty for custom DateTime serialization
  • Validator resolver — validatorResolver parameter on Mapper constructor for custom validator instantiation
  • Uninitialized property validation — properties with assert attributes are now validated even when uninitialized

Bug Fixes

  • Reject silently corrected dates in DateTimeType (e.g. 2024-02-30 no longer silently becomes 2024-03-01)
  • Restore pathPrefix correctly in ObjectType and ArrayType instead of resetting to empty string
  • Validate missing required non-constructor properties without MapProperty
  • Propagate nested object denormalization errors correctly
  • Remove deprecated ReflectionProperty::setAccessible() calls

Maintenance

  • Add PHP 8.4 and 8.5 to CI test matrix

Release 1.9

Choose a tag to compare

@igorpocta igorpocta released this 04 Mar 08:11

Bug Fix: Nested validation error paths missing parent prefix

Problem: When a DTO contained a nested object property (e.g. additionalInfo) before an array property (e.g. addresses), validation error paths lost the parent prefix. For example, an invalid address type would report as addresses[0].type instead of the correct client.addresses[0].type.

Root cause: ObjectType and ArrayType reset the denormalizer's pathPrefix to an empty string after processing nested objects, instead of restoring the previous value. This corrupted error paths for any sibling properties processed afterward.

Fix: Both ObjectType and ArrayType now save and restore the previous pathPrefix using a finally block, ensuring parent context is preserved across sibling properties at any nesting depth.

Files changed:

  • src/Types/ObjectType.php
  • src/Types/ArrayType.php
  • tests/PathPrefixRestoreTest.php (7 new tests)

Release 1.8

Choose a tag to compare

@igorpocta igorpocta released this 28 Feb 18:14

Null values included in normalization output by default

Breaking change: Normalizer now includes properties with null values in toArray() / toJson() output by default. Previously, null properties were silently omitted.

Before

{"name": "John"}

After

{"name": "John", "email": null, "address": null}

Opt-out

To preserve the old behavior, use skipNullValues:

$mapper = new Mapper(new MapperOptions(skipNullValues: true));

Nested objects

Nested objects with null properties now correctly serialize as a JSON object, not as an empty array:

// Before: {"address": []}
// After:  {"address": {"street": null, "city": null}}

Changed files

  • Normalizer — shouldIncludeNull() wired to skipNullValues
  • Mapper — passes MapperOptions::skipNullValues to Normalizer and TypeResolver
  • TypeResolver / ObjectType — propagates the setting to nested normalizations

Release 1.7

Choose a tag to compare

@igorpocta igorpocta released this 21 Feb 08:41

PHP 8.5 Compatibility

  • Removed all ReflectionProperty::setAccessible() calls that triggered deprecation warnings on PHP 8.5. The method has no effect since PHP 8.1, which is the minimum required version of this library.
  • CI now tests against PHP 8.1 – 8.5.