msstc4symfony / dto-generator-bridge-runtime
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
Requires
- php: >=7.4
Requires (Dev)
- phpunit/phpunit: ^9.6
Suggests
- symfony/framework-bundle: To register it with DtoGeneratorRuntimeBundle, which needs symfony/http-kernel and symfony/dependency-injection
- symfony/serializer: The normalizer of $additionalProperties is a Serializer normalizer
- symfony/validator: The constraints for dependentRequired, propertyNames, contains, patternProperties, if/then/else, not, oneOf and dependentSchemas are Validator constraints
Provides
None
Conflicts
- symfony/config: <5.4
- symfony/dependency-injection: <5.4
- symfony/framework-bundle: <5.4
- symfony/http-kernel: <5.4
- symfony/serializer: <5.4
- symfony/symfony: *
- symfony/validator: <5.4
Replaces
None
README
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.serializeris enabled, with its object normalizer and name converter (not whenframework.property_accessis 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 ofUNWRAP_PATHruns 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 ascamel_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 throwsSymfony\Component\Serializer\Exception\UnexpectedValueExceptionon 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-keyof 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
$additionalPropertiesout, nothing is spread. -
normalize()returns a PHP array, so two shapes come out as JSON arrays rather than objects: withpreserve_empty_objects, an object whose every property is left out ([], not{}), and an object of which only map entries with the keys0,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 asint,float(an int becomes a float),stringorbool;mixedtakes it as it is. The collection comes from a public staticfromArray()when the class has one, otherwise from a public constructor; either takes the list as its first parameter (untyped,array,iterableormixed, 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 anInvalidArgumentExceptionthe collection throws for its items (as dto-collection's lists do) is aNotNormalizableValueExceptionwith the path (tags[2]), soCOLLECT_DENORMALIZATION_ERRORSreports 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 checksmixeditems itself must refuse them with anInvalidArgumentException: 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 asfloat[]) is anInvalidArgumentException; 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: whencardis set,holderandexpirymust 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 notnull, and an uninitialized one as not set: a DTO cannot tell a missing key fromnull. Each missing property gets one violation at its path:This value should not be null when "card" is set.A malformed map throwsConstraintDefinitionException.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: betweenminandmaxelements 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 anExpressionorCallbackinside sees no object. Too few or too many give one violation on the list (This collection should contain 1 matching element or more., codesContains::TOO_FEW_ERRORandTOO_MANY_ERROR). The nested constraints must be in every group ofContains, or an element would match on part of them;Validcannot 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 throwsConstraintDefinitionException.IfThenElse(if: [...], then: [...], else: [...]), on a property or a class: a value that passes the constraints ofifpasses those ofthen, any other value those ofelse. As withContains,ifis checked on its own: its violations are not reported, and its constraints must be in every group ofIfThenElse, as must those of the branches. Without groups it takes those of its constraints.nullis 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., codeNot::NOT_ALLOWED_ERROR), at the value's path; without constraints every value butnullis. The constraints are checked on their own, asifis, and must be in every group ofNot.nullis not checked.ExactlyOneOf(constraints: [...]), on a property or a class, foroneOf: the value passes exactly one of the constraints, each a member (several constraints of one member go into one, such asSequentially); 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, codeExactlyOneOf::NOT_EXACTLY_ONE_ERROR); for a value that satisfies none, the first message of each member follows ([1] …), unlessincludeInternalMessages: false; as with Symfony'sAtLeastOneOf, 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, asifis, and must be in every group ofExactlyOneOf.nullis not checked. ForanyOf, Symfony'sAtLeastOneOfdoes the same with at least one.Property(name: 'zip', constraints: [...])andPresent(properties: ['zip']), on a class, for the branches of a class'sIfThenElse,NotandExactlyOneOf:Propertychecks the value of a property at its path and skips a missing one, like thepropertieskeyword;Presentreports each missing property at its path (This field is missing., codePresent::MISSING_ERROR), likerequired. Both read properties asDependentRequireddoes, and a property counts as missing when it isnullor 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.