Search by

msstc4symfony / dto-generator-bridge-runtime

maxim.shamaev@gmail.com

Runtime of msstc4symfony/dto-generator-bridge: the Serializer normalizer and attribute the generated DTOs use in a Symfony application.

Package info

github.com/msstc4symfony/dto-generator-bridge-runtime

pkg:composer/msstc4symfony/dto-generator-bridge-runtime

Statistics

Installs: 6

Dependents: 1

Suggesters: 0

Stars: 0

Open Issues: 0

v1.4.0 2026-10-28 15:53 UTC

This package is auto-updated.

Last update: 2026-12-04 06:06:50 UTC


README

Build Status PHP Version Symfony Versions License: MIT

What DTOs generated by msstc4php/dto-generator with msstc4symfony/dto-generator-bridge need at runtime in a Symfony application: the normalizer that carries undeclared properties (additionalProperties: spread) through Symfony Serializer, the one that reads and writes collection objects (dto.collections), a bundle that registers them, and the Validator constraints for the JSON Schema keywords Symfony has none for (dependentRequired, propertyNames, contains, patternProperties, if/then/else, not, oneOf; the bridge writes dependentSchemas as IfThenElse with Present).

The generator and the bridge write code; they belong in require-dev. The DTOs they write are committed, and this package is all of them that production needs.

Requirements

Package Normalizer Constraints
1.0 PHP 8.0+, Serializer 5.4, 6.4, 7.x, 8.x —
1.1 PHP 8.0+, Serializer 5.4, 6.4, 7.x, 8.x PHP 7.4+, Validator 5.4, 6.4, 7.x, 8.x

On PHP 7.4 the package installs beside the bridge, which runs inside the generator, and its bundle registers nothing; the constraints work there.

Installation

composer require msstc4symfony/dto-generator-bridge-runtime
composer require --dev msstc4symfony/dto-generator-bridge

Register the bundles: the runtime in every environment, the bridge's bundle (the dto-generator:generate command) where it is installed:

// config/bundles.php
return [
    // ...
    Msstc4Symfony\DtoGeneratorBridge\Runtime\Bundle\DtoGeneratorRuntimeBundle::class => ['all' => true],
    Msstc4Symfony\DtoGeneratorBridge\Bundle\DtoGeneratorBundle::class => ['dev' => true, 'test' => true],
];

Both bundles register the same normalizer service, so enabling them together is fine.

Undeclared properties

With the bridge's

extensionConfig:
  symfony:
    additionalProperties: spread

a schema with properties and an additionalProperties schema gets a property $additionalProperties marked with #[\Msstc4Symfony\DtoGeneratorBridge\Runtime\AdditionalProperties], and AdditionalPropertiesNormalizer spreads it over the keys of its object:

{"name": "Rex", "colour": "brown", "age": 3}

reads into name: "Rex" and additionalProperties: {"colour": "brown", "age": 3} (each value typed by the additionalProperties schema, nested DTOs included), and writes back the same JSON.

  • With the bundle the normalizer is in the application's default serializer as soon as framework.serializer is enabled, with its object normalizer and name converter (not when framework.property_access is off, which drops the object normalizer). It is registered at the default priority 0, ahead of Symfony's object, date, array and other built-in normalizers (negative priorities; only the unwrapping denormalizer of UNWRAP_PATH runs earlier); a normalizer of yours for the same DTOs needs a higher priority to win. A named serializer (framework.serializer.named_serializers, Symfony 7.2) does not get it: register one by hand with that serializer's object normalizer.

  • Without the bundle, wrap the object normalizer and pass it the same metadata factory and name converter:

    $names = new MetadataAwareNameConverter($classMetadataFactory);
    $objects = new ObjectNormalizer($classMetadataFactory, $names, null, $propertyTypeExtractor, new ClassDiscriminatorFromClassMetadata($classMetadataFactory));
    $serializer = new Serializer([
        new DateTimeNormalizer(),
        new ArrayDenormalizer(),
        new AdditionalPropertiesNormalizer($objects, $classMetadataFactory, $names),
        $objects,
    ], [new JsonEncoder()]);

    The wrapped normalizer must denormalize too; the Serializer is handed on to it, so it works without being in the chain, but the other DTOs need it there.

  • Declared keys are the class's serialized properties, named by the name converter (SerializedName, a global converter such as camel_case_to_snake_case, inherited properties too), and the type property of a discriminated base class or interface; everything else goes into the map. A map entry named like a declared key throws Symfony\Component\Serializer\Exception\UnexpectedValueException on normalizing. Names are read once per class and format, so a name converter that names by context (such as by groups) is not supported. Of several discriminated ancestors only the one Symfony writes counts: the class's own, else its parent's, else its interfaces' (each with its parents). Reading through another discriminated base keeps its key out of the map, but it is not written back. The type key is found as recent Serializer releases find it: by its converted name, then by the type property itself, then by the default type (7.3). Releases that read the type property only (5.4, 7.0 to 8.0 and some patches of 7.4 and 8.1) do not support a name converter that renames the type property together with a default type.

  • Some Serializer releases (5.4, 7.4.0) take the key type array-key of the generated PHPDoc for a class, so a map of objects (spread or a declared property) cannot be read; maps of scalars work. 6.4 and later 7.4 releases read both.

  • Serialization groups apply as usual: when the groups leave $additionalProperties out, nothing is spread.

  • normalize() returns a PHP array, so two shapes come out as JSON arrays rather than objects: with preserve_empty_objects, an object whose every property is left out ([], not {}), and an object of which only map entries with the keys 0, 1, … remain (["a","b"], not {"0":"a","1":"b"}).

Collection objects

With dto.collections in the generator's config, a list property is a collection object (TagList $tags). The bridge writes the property's #[Context] with the key dto_generator_collection, {class: TagList::class, item: Tag::class}, and CollectionNormalizer (registered by the bundle) uses it:

  • Reading: the data must be a list; each item goes through the Serializer as item (a DTO, an enum, a date), or is checked as int, float (an int becomes a float), string or bool; mixed takes it as it is. The collection comes from a public static fromArray() when the class has one, otherwise from a public constructor; either takes the list as its first parameter (untyped, array, iterable or mixed, not variadic), any further ones optional. An abstract class is not built. A map, a scalar, a wrong item, a class built neither way, or an InvalidArgumentException the collection throws for its items (as dto-collection's lists do) is a NotNormalizableValueException with the path (tags[2]), so COLLECT_DENORMALIZATION_ERRORS reports it like any other. A JSON object with the keys "0" … "n-1" decodes to the same PHP array as a list and is read as one. A collection that checks mixed items itself must refuse them with an InvalidArgumentException: any other throwable (TypeError, ValueError) is taken for a bug of the class and passes as it is. An item type the Serializer cannot read (?int, a list of scalars such as float[]) is an InvalidArgumentException; an interface needs a discriminator map, as anywhere in the Serializer.
  • Writing: a public toArray() (an array or anything iterable) when the class has one, otherwise iteration; the items go through the Serializer. An object of a subclass of the context's class is written too.
  • Formats: lists as JSON gives them. XML and CSV give a single item as the item itself and numbers as strings, which the normalizer does not undo.

Without the context key the normalizer leaves an object alone, so other collection-like classes keep their own normalizers.

Constraints

The bridge writes these constraints (use Msstc4Symfony\DtoGeneratorBridge\Runtime\Constraints as RuntimeAssert) for keywords that standard Symfony constraints do not express. They need no bundle: Symfony finds each validator by its class name.

  • DependentRequired(requirements: ['card' => ['holder', 'expiry']]), on a class: when card is set, holder and expiry must be too. Names are PHP property names, read from properties of any visibility, inherited ones included (a private property of the class before one of the same name in a parent). A property counts as set when it is not null, and an uninitialized one as not set: a DTO cannot tell a missing key from null. Each missing property gets one violation at its path: This value should not be null when "card" is set. A malformed map throws ConstraintDefinitionException.
  • Keys(constraints: [...]), on a map (array<string, T>): each key, as a string, passes the nested constraints, reported at [key] with the key as the invalid value — the path of the value's own violations too.
  • Contains(constraints: [...], min: 1, max: null), on a list: between min and max elements pass the nested constraints; without constraints every element matches. Each element is validated on its own, as a root value: its violations do not count against the list, and an Expression or Callback inside sees no object. Too few or too many give one violation on the list (This collection should contain 1 matching element or more., codes Contains::TOO_FEW_ERROR and TOO_MANY_ERROR). The nested constraints must be in every group of Contains, or an element would match on part of them; Valid cannot be nested, as in every composite constraint.
  • PatternProperty(pattern: '/^x-/u', constraints: [...]), on a map, repeatable: the value of each key that matches the PCRE pattern (keys are matched as strings) passes the nested constraints, reported at [key]. An invalid pattern throws ConstraintDefinitionException.
  • IfThenElse(if: [...], then: [...], else: [...]), on a property or a class: a value that passes the constraints of if passes those of then, any other value those of else. As with Contains, if is checked on its own: its violations are not reported, and its constraints must be in every group of IfThenElse, as must those of the branches. Without groups it takes those of its constraints. null is not checked.
  • Not(constraints: [...]), on a property or a class: a value that passes every nested constraint is a violation (This value is not allowed., code Not::NOT_ALLOWED_ERROR), at the value's path; without constraints every value but null is. The constraints are checked on their own, as if is, and must be in every group of Not. null is not checked.
  • ExactlyOneOf(constraints: [...]), on a property or a class, for oneOf: the value passes exactly one of the constraints, each a member (several constraints of one member go into one, such as Sequentially); otherwise one violation at the value's path (This value should satisfy exactly one of the given constraints; it satisfies 2., {{ count }} the number it passes, code ExactlyOneOf::NOT_EXACTLY_ONE_ERROR); for a value that satisfies none, the first message of each member follows ([1] …), unless includeInternalMessages: false; as with Symfony's AtLeastOneOf, they are appended to the translated message, not part of the template. It needs at least one constraint. The members are checked on their own, as if is, and must be in every group of ExactlyOneOf. null is not checked. For anyOf, Symfony's AtLeastOneOf does the same with at least one.
  • Property(name: 'zip', constraints: [...]) and Present(properties: ['zip']), on a class, for the branches of a class's IfThenElse, Not and ExactlyOneOf: Property checks the value of a property at its path and skips a missing one, like the properties keyword; Present reports each missing property at its path (This field is missing., code Present::MISSING_ERROR), like required. Both read properties as DependentRequired does, and a property counts as missing when it is null or uninitialized.

Keys, Contains and PatternProperty take arrays only, DependentRequired, Property and Present objects only; another value gets a Type violation. Keys, Contains, PatternProperty, IfThenElse, Not, ExactlyOneOf and Property are composite constraints: the nested ones take their groups, as in All; like All, they report a nested violation once for each of several groups validated at once (validate($dto, null, ['api', 'Default'])). Error names (getErrorName()) need Symfony 6.1 or later. The messages of DependentRequired, Present, Not and ExactlyOneOf are not in Symfony's translation catalogue; an application that translates them adds them to its own. The constructors take no payload.

Development

make install-ci   # tools and the optional Symfony libraries
make check        # lint, PHPStan, PHP-CS-Fixer, Composer, Rector, deptrac
make test
make infection

Changelog and security

See CHANGELOG.md and SECURITY.md.

License

MIT, see LICENSE.