Repository navigation
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 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 —
Validatorcaches 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 theDateTimeZoneis created
once per type handler. Accepted and rejected values are unchanged (covered by new characterization tests); an
invalid timezone still throws on every call. ClassMetadataFactorymemoizes metadata in-process — withFileCache/RedisCache, every
getMetadata()call read and unserialized the backend entry, i.e. per object infromObject()and per CSV row.
fromCsv()of 2000 rows withFileCache: 55 ms → 9 ms.clearCache()clears the memo as well.- Property paths ~4× faster —
PropertyPathResolverreuses parsed path segments (bounded memo, invalid paths
are not stored and keep throwing). Resolvinguser.addresses[0].street: 4.6 µs → 1.2 µs per field. - Normalization ~3.3× faster —
Normalizerresolves 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 itsusestatement. -
DenormalizationErrorEvent::suppressException()andisExceptionSuppressed()— they never had an effect
(the exception was always re-thrown; returningnullwould breakfromArray()'s return type). Migration: remove
the calls and catch the exception in the caller; the event is still dispatched for logging/monitoring. -
RedisCacheaccepts only real Redis clients — phpredis (Redis) or Predis (Predis\ClientInterface). Before,
any object whose class name containedClientand hadget()/set()was accepted. Migration: pass the
underlying phpredis/Predis client instead of a custom wrapper. -
A
#[Callback]method returning a non-array value now throwsLogicException— a string or bool result was
silently ignored, so a broken validation rule never reported anything. Return an array of errors (or null). -
Custom
messageofRegex,UuidandIbanis returned as written — it was rewritten
(Value→Property 'x',UUID→UUID v4), andUuidignored 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 asfromArray()— it now supports property paths, filters and hydrators,
collects all errors into oneValidationException(instead of throwing a rawInvalidArgumentExceptionon the
first bad value or aTypeErrorfornullin a non-nullable property) and is atomic: on any error the object stays
unchanged. Keys are matched like infromArray(): a property renamed with#[MapProperty(name: ...)]is no
longer also accepted under its PHP name. Modifying an initializedreadonlyproperty is a validation error.
Unchanged on purpose
NotBlankkeeps rejecting0/0.0for numeric properties (applications rely on it for IDs and amounts).- Defaults of
publicPropertiesOnly,symmetricPropertyPathsandparseFormattedNumbersstayfalse- turning
them on changes response shapes / accepted input; opt in explicitly (e.g.MapperOptions::api()).