Repository navigation
Releases
Release 1.16
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-mapperairora/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
What's Changed
New Features
- Partial updates (PATCH): sent vs. not sent — DTOs implementing
ProvidedFieldsInterface(use the
ProvidedFieldstrait) get the names of the properties present in the input:$dto->isProvided('note')is
truealso whennotewas sent asnull, 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 bymerge(). 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 withError: must not be accessed before initialization
(HTTP 500). It is now set tonull, like a nullable constructor parameter already was. If such a property carries
validators, they now validatenullinstead of reporting "This field is required.".
Release 1.14
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 reusedMapper(DI singleton,
long-running worker) every later call then kept old errors, and a repeated error with the same key
(e.g. a missing requiredleaf.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
CircularReferenceExceptionas before. - Cache integrity —
FileCacheandRedisCacheaccept an optionalsigningKey: 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.FileCachefiles 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
failingCountstopped 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.skipNullValueswas ignored for elements of an array of objects —#[MapProperty(arrayOf: Foo::class)]
elements kept theirnullproperties in output, while nested objects dropped them. WithoutskipNullValues
output is unchanged.ToIntFilter/ToFloatFilterdid 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 to1000, consistent withToDecimalStringFilter. All other inputs behave as
before (covered by new characterization tests).FileCacheandArrayCachelost cachednullvalues — afterset('k', null),has('k')returnedtrue
butget('k', $default)returned the default (FileCachealso deleted the file). A storednullis now returned.
Other values, includingfalse,0and'', behave as before.- Direct
Denormalizeruse 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 toHydrationMode::FULLhydrators.
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/PostNormalizeEventfired twice for it. Each object is now normalized exactly once;
CSV output is unchanged.- Profiler stack leaked on failed operations —
denormalize,validation,normalizeand a failing
PreDenormalizeEventlistener left entries onProfiler::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. Debuggeropenedphp://stderron 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/EncodeFilterdecoded/encoded twice,HtmlEntitiesEncodeFilterandUrlEncodeFilterescaped twice,
SubstringFilter/SliceArrayFiltercut twice,PriceRoundFilterbroke 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.AddIntervalFilteron 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()andfromCsvFile()now share one parser (fromCsv()already skipped blank lines before the
header); results for all other inputs are unchanged.RedisCachedid not work with Predis at all — the client check looked forget()/set()methods, but Predis
implements commands via__call, so a realPredis\Clientwas rejected;ping()also ignored Predis'Status
response. Predis is now recognised by its interface and verified against a real Redis server.InvalidInputExceptionis now aValidationException(introduced in 1.12 as a plain
InvalidArgumentException). Code that turnsValidationExceptioninto 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 anInvalidArgumentExceptionand 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. throwOnMissingDataand runtimesetStrictMode()/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(defaultfalse) —intandfloatproperties 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 anintwith a
non-zero fraction ("12,5") are rejected — never truncated silently. Applies to nested objects and
arrayOf: ArrayElementType::Int/Floatelements. Without the option, behaviour is unchanged.Debugger(maxLogEntries: N)— optional cap on in-memory log entries (newest kept) for long-running
processes. Defaultnullkeeps 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 withwith().ValidationExceptionaccepts an optional$previousexception and implementsJsonSerializable
(json_encode($e)gives the same structure astoApiResponse()).Psr16Cache— adapter for any PSR-16 cache (Symfony, Laravel, ...); mapper keys are hashed into PSR-16
safe keys.psr/simple-cacheis 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
RedisCacheusesSCANinstead ofKEYSforclear(),size()andkeys()—KEYSblocks 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.UnitEnumTyperesolves cases through a map built once (2.7× faster). - Mapping attributes are read in one place — the precedence rules for
#[MapProperty]/
#[MapDateTimeProperty]were copied inNormalizer,Denormalizer(property and parameter variants),
Mapper::merge()andClassMetadataFactory, 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 —
Denormalizercaches 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
FilterInterfacefilters are still instantiated on every use (their constru...
Release 1.13
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]:A constructor parameter is now excluded from input when the same-named property carriesclass UserDto { #[OutputOnly] public string $role; public function __construct(public string $name, string $role = 'user') { $this->role = $role; } } // {"name": "x", "role": "admin"} → $dto->role === 'admin'
#[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 readonlyproperties
are hydrated as before. publicPropertiesOnlyandsymmetricPropertyPathsdid not apply to nested objects (introduced in 1.12) —
nested objects and arrays of objects are (de)normalized by type handlers with their ownNormalizer/
sharedDenormalizer, which never received the new options. WithpublicPropertiesOnly: true, private properties
of nested DTOs still leaked to output and were hydrated from input
({"inner": {"secret": "HACKED"}}). Options are now propagated throughTypeResolverto all nesting levels,
including strict-mode unknown-key detection (inner.secret).
Bug Fixes
symmetricPropertyPathssilently dropped fields on key collisions — a plain property and a path sharing the
same output location ($metaand#[MapProperty(path: 'meta.source')]), or two properties with the same path,
overwrote each other depending on declaration order. Now throwsLogicExceptionnaming 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 withnull, so the output is a JSON list
({"items": [null, {...}]}), also when indexes are written out of order. toCsv()withsymmetricPropertyPathswrote nested arrays into cells (Array to string conversion,
literalArray). CSV output now always uses flat columns.PropertyPathResolver::set()no longer overwrites an existing scalar when descending into it — throws
InvalidArgumentExceptioninstead.
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 withUnknown key 'id'. The value is discarded, never hydrated.
#[Ignore]and non-public keys (in public-only mode) are still reported as unknown. Applies tomerge()too. - List input to
fromArray()is rejected afterPreDenormalizeEvent— listeners can now reshape list input
(e.g. wrap it into an object) before validation, and the rejection dispatchesDenormalizationErrorEventlike any
other mapping error.PreDenormalizeEvent::$dataandDenormalizationErrorEvent::$dataare documented as
array<mixed>(input is untrusted). - Excluded variadic constructor parameter (
#[Ignore] string ...$tags) threwLogicException/ receivednull.
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/Denormalizerstill re-run reflection per object instead of using
ClassMetadataFactorymetadata — candidate for a follow-up refactor.
Release 1.12
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()andmerge()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(defaultfalse) — map only public properties. Prevents leaking
private/protecteddata (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.
- Non-public properties can be opted in explicitly with
-
#[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(defaultfalse) — properties with#[MapProperty(path: 'address.city')]
(orMapDateTimeProperty) are normalized back into the same nested structure ({"address": {"city": "..."}})
instead of a flat key ({"city": "..."}). Output can be fed back tofromArray()and request/response share
one schema. -
MapperOptions::$jsonDepth(default512) — maximum nesting depth forfromJson()and
fromJsonCollection(). Previously hard-coded to 512. Deeper input throwsJsonException; values< 1throw
InvalidArgumentException. -
InvalidInputException(extendsInvalidArgumentException) — thrown for input of the wrong shape, so it can
be told apart from programming errors and mapped to HTTP 400. -
PropertyPathResolver::set()andPropertyPathResolver::getRootKey()helpers.
Bug Fixes
- Strict mode rejected the root key of a property path — with
#[MapProperty(path: 'address.city')], strict
mode threwUnknown 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 throwsInvalidInputExceptionfor
lists, scalars andnull(previously a genericInvalidArgumentExceptionfor scalars).fromArray()accepted a list — a non-empty list is now rejected withInvalidInputException; an empty array
is still accepted as an empty object.fromJsonCollection()/fromArrayCollection()crashed withTypeErroron a non-object element
([{"name": "a"}, 2], HTTP 500). Now throwsInvalidInputExceptionwith 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:
publicPropertiesOnlyand
symmetricPropertyPathsdefault totrue. - Code catching
InvalidArgumentExceptionkeeps working —InvalidInputExceptionandValidationException
both extend it. - Behaviour changes affecting only invalid input: list input to
fromJson()/fromArray()is rejected;
fromArrayCollection()throwsInvalidInputExceptioninstead ofTypeErrorfor non-array elements. - PHPDoc of
fromArray()/fromArrayCollection()widened toarray<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::testFromArrayCollectionThrowsOnInvalidItemnow expectsInvalidInputException.
Documentation
docs/configuration.md— new options, Property Visibility, Ignore/OutputOnly/InputOnly, recommended API config.docs/advanced.md—pathnormalization 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
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->errorsacross recursivedenormalize()calls. An error from a parent property (e.g. invalid enum value) leaked into nestedObjectType/ArrayTypeelement processing, was re-thrown as aValidationException, caught asnull, and then assigned to a non-nullable property — producing a PHPTypeError(HTTP 500) instead of the expectedValidationException(HTTP 422) with the real field path.Concretely: sending
{"client": {"entityType": "Legal Entity", "addresses": [...]}}with a badentityTypewould fail withCannot assign null to property ClientSimpleRequest::$addresses of type arrayinstead of a clean validation error onclient.entityType.The fix isolates errors produced inside each
denormalize()invocation from errors inherited from a parent invocation (snapshot +array_diff_key), switchessetPropertyValue()from count-based to value-aware error detection (catches same-key overwrites), and adds a defensive guard against assigningnullto non-nullable properties.
Tests
- Add
EnumWithArrayErrorIsolationTestwith 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 /
nullnested 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
Features
- DateTime range validators — new
DateTimeGreaterThan,DateTimeLessThanandDateTimeRangevalidation attributes - Null values in normalization — null values are now included in normalization output by default
- DateTime output format —
outputFormatparameter onMapDateTimePropertyfor custom DateTime serialization - Validator resolver —
validatorResolverparameter onMapperconstructor 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-30no longer silently becomes2024-03-01) - Restore
pathPrefixcorrectly inObjectTypeandArrayTypeinstead 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
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.phpsrc/Types/ArrayType.phptests/PathPrefixRestoreTest.php(7 new tests)
Release 1.8
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 toskipNullValuesMapper— passesMapperOptions::skipNullValuesto Normalizer and TypeResolverTypeResolver/ObjectType— propagates the setting to nested normalizations
Release 1.7
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.