msstc4symfony / dto-generator-bridge
Symfony Validator constraints and Serializer attributes for DTOs generated by msstc4php/dto-generator.
Package info
github.com/msstc4symfony/dto-generator-bridge
pkg:composer/msstc4symfony/dto-generator-bridge
Requires
- php: >=7.4
- msstc4php/dto-generator: ^1.18
- msstc4symfony/dto-generator-bridge-runtime: ^1.4
Requires (Dev)
- phpunit/phpunit: ^9.6
Suggests
- odolbeau/phone-number-bundle: To check phone numbers with libphonenumber: extensionConfig.symfony.formats {phone: strict}
- symfony/framework-bundle: To use DtoGeneratorBundle: the dto-generator:generate command and the warmup check
- symfony/serializer: To (de)serialize the generated DTOs
- symfony/validator: To validate the generated DTOs
Provides
None
Conflicts
Replaces
None
README
Symfony Validator constraints and Symfony Serializer attributes for the DTOs that
msstc4php/dto-generator generates from OpenAPI 3.1.
The generator turns schemas into typed PHP classes; this extension reads the same schemas and adds what Symfony needs
to validate and (de)serialize them: #[Assert\Length(max: 254)] from maxLength, #[SerializedName('first_name')]
for a renamed property, #[DiscriminatorMap] for a oneOf with a discriminator, and so on. The attributes match the
Symfony versions in your composer.lock.
Features
- Validator constraints from
required, string, number and array keywords,enum,const, formats, nested objects and collection items,prefixItemsandunevaluatedItems, anddependentRequired,propertyNames,contains,patternProperties,if/then/else,not,dependentSchemasand the members of aoneOfof scalars through the runtime's own constraints — the full table. - Serializer attributes for wire names, discriminator maps, date formats, groups and ignored properties — the full table.
- Version-aware output for Symfony 5.4, 6.4, 7.x and 8.x: the right namespaces, arguments and fallbacks for each, and annotations when the DTOs target PHP 7.4 (Symfony 6.4 and older).
- No configuration: the generator discovers the bridge when it is installed;
x-validator-*andx-serializer-*keys fine-tune single properties. - Undeclared properties over the wire: an opt-in normalizer spreads
$additionalPropertiesover the keys of its object and reads undeclared keys back into it — details. It ships in the small runtime package, the only one production needs. - An optional Symfony bundle with a
dto-generator:generateconsole command, a check on cache warmup and the normalizer wired into the application's serializer.
Requirements
- PHP >= 7.4 (the bridge runs inside the generator, which supports PHP 7.4).
msstc4php/dto-generator^1.17 andmsstc4symfony/dto-generator-bridge-runtime^1.4 (both installed with the bridge).- In the application that uses the DTOs:
symfony/validatorand/orsymfony/serializer5.4, 6.4, 7.x or 8.x. By default the bridge writes constraints and attributes only for the components it finds incomposer.lock. - For the bundle:
symfony/framework-bundle5.4, 6.4, 7.x or 8.x.
Installation
composer require --dev msstc4symfony/dto-generator-bridge
This installs the generator and the runtime as well. With additionalProperties: spread, require the runtime for
production too: composer require msstc4symfony/dto-generator-bridge-runtime.
The generator finds the bridge through extra.dto-generator.extensions, so no
configuration is needed: the next vendor/bin/dto-generator generate writes the attributes. See the
generator's README for dto-generator.yaml.
Configuration
dto-generator.yaml:
extensionConfig: symfony: validator: auto # auto | true | false — auto: when composer.lock has symfony/validator serializer: auto # auto | true | false — auto: when composer.lock has symfony/serializer version: auto # auto | '6.4' … — quote it: YAML reads 6.4 as a number groups: [] # validation groups for every constraint, plus Default additionalProperties: ignore # ignore | spread — see "Undeclared properties" formats: true # true | false | [uuid, email] | {phone: false} | {phone: strict} — see "Format checks"
The Symfony version is read per component from the project's composer.lock.
Format checks
Every format in the table below gets its constraint unless formats turns it off: false checks none, a list checks
only the formats it names, and a map turns the formats it names on or off, leaving the others checked:
extensionConfig: symfony: formats: phone: false # any spelling: phone_number, tel… currency: false
A format turned off stays an annotation, as JSON Schema has it; inside not, if and oneOf it leaves the keyword
unchecked, with a warning. An empty formats: [] is an error: it and {} both arrive as one empty array, and the
two would mean the opposite. A format the bridge does not check is an error here, and so are the dates: date,
date-time and date-time-rfc-2822 give the property its DateTimeInterface type, which no setting changes.
phone: strict checks a phone number with PhoneNumber of
odolbeau/phone-number-bundle (libphonenumber) instead of the
Regex, which takes any number as people write it. Without a region the library takes only international numbers
(+15017122661): the bundle's default_region sets one when the bundle is registered. Without the package (3.5 or
newer, whose constraint is an attribute) the Regex stays, with a warning on each property, or child's declaration
of one, that holds the format itself. Only phone takes strict.
x-validator-format: false on a property's schema, or on a child's declaration of an inherited one, leaves its
formats, its items' and subschemas' included, unchecked whatever the config says, and true checks them (each as
strictly as the config sets it); not on a schema its $ref points to, and not on the schema of a class, whose
properties take their own, nor inside a subschema (not, oneOf…), which follows the property's. A format turned off
inside not, if or oneOf leaves that keyword unchecked, with a warning, as the config's switch does.
Validator constraints
From the schema of each property, of the schema its $ref points to, of its allOf branches and of the one member of a
nullable oneOf/anyOf (all apply, as in JSON Schema 2020-12):
| Schema | Constraint |
|---|---|
| required | NotNull |
minLength / maxLength |
Length |
pattern |
Regex (/…/u) |
minimum / maximum / exclusive* |
Range, GreaterThan(OrEqual), LessThan(OrEqual) |
multipleOf |
DivisibleBy |
minItems / maxItems, minProperties / maxProperties |
Count |
uniqueItems |
Unique |
enum |
Choice; on a PHP enum only when it allows fewer cases (one beside a $ref), with the cases |
const |
IdenticalTo, IsNull |
format: email, ip, ipv4, ipv6, hostname, uuid (guid) |
Email(mode: 'html5'), Ip(version: 'all'), Ip(version: '4'), Ip(version: '6'), Hostname(requireTld: false), Uuid (RFC 4122 versions in their canonical form: the nil UUID and {…} fail) |
format: cidr, ipv4-cidr, ipv6-cidr (Linode's ip/netmask, ipv4/prefix_length, ipv6/128) |
Cidr, with the version |
format: ip-or-cidr (Linode's ipv4|ipv6/prefix_length) |
Regex for an address or a range of either version (the prefix optional; IPv6 in its RFC 4291 forms, the groups of one ending in an IPv4 address and holding :: not counted exactly) |
format: ulid, json, color (css-color), iban, isbn, issn, isin |
Ulid, Json, CssColor, Iban, Isbn, Issn, Isin |
format: timezone |
Timezone(zone: \DateTimeZone::ALL_WITH_BC): the names PHP keeps for compatibility (Asia/Calcutta, US/Pacific, GMT) pass too, as far as the timezone database has them (PHP built against the system database on Ubuntu needs tzdata-legacy) |
format: country, language, locale, bic |
Country, Language, Locale, Bic when the project installs symfony/intl, whose data they need (Bic fails without it when the class is loaded); a warning otherwise. They take upper-case codes only: us or a lower-case BIC fail |
format: phone (phone-number, tel…) |
Regex for a number as people write it: digits among spaces (no-break ones too), +, ., /, -, en dashes and parentheses, an extension (x12, ext. 12, ;ext=12); Twilio's (800) 555-1234, +7 (495) 123–45–67 and E.164 alike. It is lenient (unbalanced parentheses pass) and takes no letters (1-800-FLOWERS fails); whether the number exists needs libphonenumber |
format: currency |
Regex for three letters of either case (Stripe writes usd, which Currency rejects) |
format: decimal; int64, integer…; uint64, digits of a string |
Regex for a number (leniently: a sign, leading zeros, a leading or trailing dot, an exponent), an integer, digits; the range of a string's integer is not checked |
format: duration, mac-address, hex-color, http-method, MM/YYYY |
Regex for an ISO 8601 duration (weeks alone, or date and time parts of whole numbers, a fraction only of seconds, no sign), a MAC address (: or - throughout, ., or none), three to eight hex digits with or without #, an RFC 9110 method token in any case, a month and year |
format: int8, int16, int32, uint8, uint16, uint32 / uint64 of an integer |
Range of the type, merged with minimum / maximum / exclusive* / GreaterThanOrEqual(value: 0) |
format: byte |
Regex for base64: the standard alphabet of RFC 4648, padding only at the end |
format: uri |
Regex for an RFC 3986 URI: a scheme and any of its forms (https://…, urn:…, mailto:…) |
format: time |
Regex for an RFC 3339 full-time: 08:30:06Z, 23:59:60.5-08:00 |
| an object or a collection of objects | Valid |
constraints of items / additionalProperties |
All (not on PHP 8.0, whose attributes allow no new) |
contains, minContains / maxContains on a list |
RuntimeAssert\Contains (its nested constraints not on PHP 8.0) |
propertyNames on a map, or on a class with $additionalProperties |
RuntimeAssert\Keys (not on PHP 8.0, as it needs nested ones) |
dependentRequired on a class |
RuntimeAssert\DependentRequired, on the class |
patternProperties on a map, or on a class with $additionalProperties |
RuntimeAssert\PatternProperty for each pattern (its nested constraints not on PHP 8.0) |
patternProperties on a class, for the declared properties whose names match |
the constraints of the pattern's schema, on each of them |
if / then / else on a property or the items of a collection |
RuntimeAssert\IfThenElse (not on PHP 8.0) |
if / then / else on a class |
RuntimeAssert\IfThenElse of Property and Present, on the class (not on PHP 8.0) |
not on a property or the items of a collection |
RuntimeAssert\Not (its nested constraints not on PHP 8.0) |
not on a class |
RuntimeAssert\Not of Property and Present, on the class (its nested constraints not on PHP 8.0) |
dependentSchemas on a class |
RuntimeAssert\IfThenElse with Present of the property in if, or Not of it for false, on the class (not on PHP 8.0) |
anyOf of members the generator types as PHP scalars, without a discriminator |
AtLeastOneOf, each member its Type and its constraints (in Sequentially), when a member has keywords or the property has no union type (PHP 7.4); not on PHP 8.0 |
oneOf of such members |
RuntimeAssert\ExactlyOneOf (runtime 1.3), the same members, also when two members share a type; not on PHP 8.0 |
oneOf beside the properties of a class, without a discriminator, whose members are objects of properties and required |
RuntimeAssert\ExactlyOneOf (runtime 1.3) of each member's Property and Present, on the class; not on PHP 8.0 |
anyOf of such members |
RuntimeAssert\Not of a Not per member (runtime 1.2), as Symfony's AtLeastOneOf takes no class: valid when a member holds; not on PHP 8.0 |
prefixItems on a list |
Collection of the elements by index, extra and missing ones allowed (not on PHP 8.0) |
unevaluatedItems: false on a list |
Count(max: …), the length of the longest prefixItems of its schema |
an unevaluatedItems schema on a list without prefixItems |
All, as items (not on PHP 8.0) |
x-validator-groups: [api] sets the groups of a property instead of groups; Default is added to either, unless
x-validator-groups-exclusive: true. x-validator-skip: true leaves a property alone. On PHP 7.4 the constraints are
annotations, which Symfony Validator 7 no longer reads: the bridge writes none and reports it, as an error under the
default target.strict: true (a warning otherwise). Annotations also need doctrine/annotations in the project; the
bridge warns when it is missing. With target.metadata: none the bridge writes nothing.
Keywords of one kind of value (minLength, minimum, minItems…) are written only for a property of that type; for
a value of several types, a pattern PHP cannot compile or a malformed keyword the bridge warns and writes nothing. The
same holds for the formats: those of integers (int32…) and of strings (email, uuid, byte…) are checked only on
a value of that type, and a value of several types warns about them. Inside not, if and oneOf, a format the
bridge does not check (uri-reference, password, one the generator does not know, or one of numbers such as
unix-time beside an integer) leaves that keyword unchecked, with a warning: JSON Schema reads such a format as
matching any value, so not would reject every one. Elsewhere (anyOf, then, items, propertyNames…) it only
admits more values and is left aside, as at the top. A mixed enum such as [low, 1] gives a Choice with both
values; its property may hold a string or an int, so minLength or minimum beside it get that warning.
The bridge reads a format by the name the generator reads it as (generator 1.16+): dateTime is date-time,
phone_number is phone, GUID is uuid (the generator's docs list the spellings). url reads as uri-reference,
which is not checked: specs write it for relative paths and bare host names too. A format the generator does not know,
and the date formats, which the generator types as dates, get no constraint. Twilio's date-time-rfc-2822 gets a
Serializer Context with that format (D, d M Y H:i:s O) for writing and reading; a date without the day of the week,
which RFC 2822 allows, does not read.
The int32 bounds compete with the schema's: the strictest bound on each side wins, so minimum: 0 gives
Range(min: 0, max: 2147483647), and an exclusive bound gives a pair such as GreaterThanOrEqual(value: -2147483648)
and LessThan(value: 10). int64 needs no constraint (it is PHP's int on 64-bit platforms).
uri and time get a Regex rather than Symfony's Url and Time: Url takes only the schemes it lists, each with
an authority, so urn: and mailto: URIs fail, and Time takes neither fractions of a second nor the offset that
full-time requires. A uri must be absolute: a relative reference such as /pets/1 is a violation
(uri-reference, iri and iri-reference get no constraint). Percent-encoding must be complete (%2 fails), and
non-ASCII characters are rejected; IP literals in brackets are checked for their alphabet only. The pattern repeats a
group only per percent-encoded octet, so a value of any size passes unless it holds more than about 500 000 of them
(a million without PCRE's JIT; pcre.backtrack_limit at its default), which reads as a violation. A time takes a
leap second only as 23:59:60 in UTC (Z, +00:00, -00:00) and at minute 59 with an offset of whole hours; the
hour, and the minute beside an offset such as +05:30, are not checked, since that needs arithmetic, so such values
pass where JSON Schema's test suite expects a failure.
RuntimeAssert is Msstc4Symfony\DtoGeneratorBridge\Runtime\Constraints of
msstc4symfony/dto-generator-bridge-runtime,
which the application needs in production then; without it in composer.lock the bridge warns and writes none of
them. The bridge claims these keywords (unless validator: false) and marks each occurrence it checks or warns
about, such as one in a member of a oneOf/anyOf with several members that is not checked. A union's members go
unchecked, with that warning only for the bridge's own keywords in them, when one is no PHP scalar (an object, an
array, a format the generator maps to a class, x-php-type, an enum), says something in more than one schema (a
keyword beside its $ref, an allOf), holds a union or the bridge's own keywords, when integer and number
members meet (JSON Schema counts 5.0 as an integer, PHP's Type does not), or when the union is written in more
than one place. Annotations (title, example, readOnly…) do not count. The generator still
calls the others unsupported: those written beside a $ref to a class (write them in the class's schema), those of
a property or a class with x-validator-skip, and all of them when the bridge writes no Validator constraints (no
symfony/validator, target.metadata: none). In a schema with x-php-type they are not checked, without a
warning, as in the generator. A minContains or maxContains without contains in the same schema gives a warning:
JSON Schema ignores it there.
They follow JSON Schema with these limits:
- Subschemas (of
contains,propertyNames,patternProperties,if,then,else,not,prefixItems,unevaluatedItems, and of the properties in a class's branches, itsnot, itsdependentSchemasand the members of aoneOf/anyOfbeside its properties) must be flat:type,format,enum,const, the string and number keywords, annotations andx-keys. A$refis followed (with the generator 1.6): the keywords of every schema on the way are checked together, their annotations and metadata (example,readOnly,xml…) aside, as long as each schema is flat and no two of them hold the same keyword; otherwise, or when it does not resolve (the generator warns about that too), the$refcounts as a keyword the bridge cannot check. A branch of a class's condition, itsnotor a schema of itsdependentSchemaswritten as a$refitself is not followed: only the property schemas inside it are.properties,items,allOfand the like, atypenarrower than the value's PHP type (type: integerin a list of strings), a keyword the bridge cannot turn into a constraint (apatternPHP cannot run) or a value that is no string, number, boolean or PHP enum and not of any type (an object, a list) give a warning, and the keyword is not checked, rather than checked in part. A schema of annotations only accepts every value; one whosetypeorenumallowsnullalone getsIsNull. On a PHP enum onlytype,constandenumapply, compared with its cases (on a target without PHP enums the value is its plain string or int, which the other keywords check too). On a value of any type (an untyped property, the values of a map without anadditionalPropertiesschema)typegives aTypeconstraint, and the string and number keywords need exactly onetypeamongstring,integer,numberandboolean, as Symfony would check them on other kinds of values too; aconstorenumwith a whole number needs atypethat admits no float (integer, notnumber), as PHP tells0from0.0. Wherenullis a value (an element, a map value), a schema that rejects it (atype,constorenumwithout it) getsNotNullbeside its constraints, which letnullpass;if,thenandelseare the exception, below. containscounts the elements that pass the constraints of its schema, each checked on its own;minContains(1 by default) andmaxContainsof the same schema bound the count, andminContains: 0alone checks nothing. Eachcontains(inallOfbranches, or behind a$ref) must hold with its own bounds.propertyNameschecks each key of a map, or of$additionalProperties. The names of declared properties are checked while generating, bytype,pattern,minLength,maxLength,constandenum(falserejects every name), whatever the bridge writes for the Validator (also withx-validator-skip,validator: falseor nosymfony/validator), as it is a contradiction in the schema: a name it rejects gives a warning, as that property can never be set. A variant its base lists without a$refback to it is checked against the base'spropertyNamestoo. On a class without$additionalPropertiesit gives a warning (withadditionalProperties: falsenothing is left to check). A violation is reported atlabels[key]with the key as its value, the same path as the violations of the value under that key.- A property several members of an
allOfdeclare gets the constraints of every declaration, as a value must satisfy them all (the generator types it by one); a declaration withx-validator-skipor groups of its own is left out. - A property of the parent declared again in a child's schema, narrowing only its values, stays the parent's (the
generator lets no child narrow its type); the child checks the constraints of its declaration that the parent's
lack with
Property(a missing value passes them), and withPresentthat it is set when the child requires what an ancestor leaves optional, as the generator lists it (ClassModel::requiredInherited(): no declaration admitsnull). A property of any type counts too, so a child that requires it turnsnullaway, as its constructor does, where the class that declares it required takesnull. A requirement an ancestor checks withPresentitself is left to it, unless it skips the validator or checks it in groups of its own. A parent's declaration in groups of its own does not count. dependentRequiredreads a property as present when it is notnull: like the rest of the DTO, it cannot tell a missing key fromnull, so a pair whose first property has a default is not checked (it is always present), with a warning. A name that is not a property of the class gives a warning and leaves its pair out. A class that extends another (allOfwith a$ref) checks pairs with inherited properties too; a pair a parent's schema lists is left to the parent, which Symfony checks on the child as well. Only when the parent is not generated in the same run are its properties unknown: a pair with one of them gives a warning. Each missing property is one violation at its own path.patternPropertieschecks the value under each key a pattern matches: withPatternPropertyon a map and on$additionalProperties, reported atlabels[key]; on a declared property whose wire name matches, the bridge matches it while generating and writes the constraints of the pattern's schema on the property itself, where a missing value (null) passes them. A pattern of a child's schema that matches a property the class inherits is checked on the child withProperty: the property belongs to the parent, which checks only the patterns of the schemas that declare it. A class without$additionalPropertiesof its own gives a warning: the undeclared properties the patterns would check are not kept. Beside anadditionalPropertiesschema it warns too: the generated type gives that schema's type to every undeclared property, including those the patterns match, which JSON Schema exempts from it. A pattern PHP cannot run gives a warning and is left out;additionalProperties: falsestill leaves the keys outside the patterns unchecked.if,thenandelsebecome oneIfThenElseper schema that holdsifwiththenorelse(anifalone, or athenwithoutif, has no effect and is not written). The value matchesifwhen its constraints find nothing.nullis not checked, also where it is a value (a nullable element passes whatever the branches say). On a class, the branches may holdtype: object(always true there),properties(each checked byPropertywith the constraints of its flat schema; a missing property passes, as in JSON Schema) andrequired(Present), by wire names the bridge turns into PHP names. Names that are no property of the class, a property with a default underpropertiesor in therequiredofif(the DTO cannot tell it from a missing one), any other keyword in a branch, or a branch that is no schema (if: falseincluded) give a warning, and the condition is not checked. As withdependentRequired, a condition of a parent's schema is left to the parent, and one in the child's schema may name inherited properties. A class constraint an ancestor's class already writes, the same in the same groups, is left to the ancestor, so a violation is reported once.notbecomesNotof the constraints of its schema: a value they find nothing wrong with is a violation. A schema that checks nothing ({},true, annotations only) leaves no value but a missing one, andnot: falseforbids nothing. As withif,nullis not checked: it stands for a missing value, sonotof a schema that allowsnullalone gives a warning, andnot: {type: [string, 'null']}does not forbidnull. On a class,notholdspropertiesandrequiredas the branches of a condition do, with the same warnings about names, defaults and inherited properties; one of nothing but the object in a parent's schema is left to the parent.dependentSchemasis checked on classes only: for each property it names, the schema (propertiesandrequired, as in a condition) applies when the property is set; afalseschema forbids the property. A name or a property of its schema that is no property of the class, a named property with a default (always set), and a value that is not a class give a warning; a dependency of a parent's schema is left to the parent.oneOfandanyOfbeside a class's properties check their members as conditions do: a property that isnullcounts as missing, as the DTO cannot tell them apart, sopropertieslets it through andrequiredfails on it. AoneOfwhose member restricts a nullable property can thus reject a payload withnullthere that another member accepts. A member naming a property the class lacks or one with a default, or one that checks nothing in aoneOf, gives a warning; ananyOfwith such an empty member always holds and gets no check. A union of a parent's schema is left to the parent.prefixItemschecks each element of the prefix by its index with Symfony'sCollection, which lets shorter and longer lists through; underx-validator-groupseach element's constraints go into anOptionalof those groups, asCollectionwould put them inDefaultonly. The generated type givesitemsto every element, the prefix's too, soprefixItemsbeside anyitemsgives a warning and is not checked. An element's schema is that of a value of any type: its string and number keywords need onetype, and atypewithoutnullgetsNotNull.unevaluatedItemssees what its own schema and the subschemas it reaches (allOf,$ref, the one member of a nullableoneOf/anyOf) evaluate, not a sibling inallOf, as in JSON Schema 2020-12. Anitemsthere, or anunevaluatedItemsthere that is notfalse, evaluates every element, so it has no effect;trueor{}never has. Besidecontains,ifor a union of several values, which evaluate elements too, it gives a warning.falseallows no element beyond the longestprefixItemsthere (Count); a schema checks every element (All) when there is noprefixItems, and gives a warning beside one.unevaluatedPropertiesis not checked: a DTO drops the undeclared properties it would judge, so the generator's warning stays.x-validator-skipandx-validator-groupson a class's schema apply toDependentRequired, to the conditions of the class, itsnot, itsdependentSchemasand theoneOf/anyOfbeside its properties, to theKeysandPatternPropertyof$additionalPropertiesand to the constraints the patterns give declared properties; those on the schema of a property or ofadditionalPropertiesapply to its own constraints only.
format: byte takes the standard alphabet only: base64url (-, _), MIME base64 with line breaks, a trailing newline
and padding inside the string are rejected. The pattern checks the characters and that up to two = only end the
string, not that the length is a multiple of four: QUJ, unpadded base64 and even a lone = or == pass. A pattern
that counts groups of four exhausts PCRE's JIT stack on payloads of about a hundred kilobytes, and Symfony reports the
failed match as a violation; the pattern used is linear and possessive, so it holds payloads of any size.
Serializer attributes
| Schema | Attribute |
|---|---|
a wire name the PHP property does not have (first_name → $firstName) |
SerializedName('first_name') |
| a discriminated base | DiscriminatorMap(typeProperty: …, mapping: […]) on the class; with an OpenAPI 3.2 defaultMapping, also defaultType: … from Symfony 7.3 |
format: date (also of list or map items, or behind a nullable union) |
Context with the Y-m-d date format |
x-serializer-groups: [api] |
Groups(['api']) |
x-serializer-ignore: true |
Ignore |
properties beside an additionalProperties schema |
Ignore on $additionalProperties, with a warning; with additionalProperties: spread, AdditionalProperties instead |
x-serializer-skip: true leaves a property alone. Before Symfony 6.4 the attributes come from
Symfony\Component\Serializer\Annotation, from 6.4 from Symfony\Component\Serializer\Attribute.
Notes:
SerializedNameis written only where the wire name differs from the PHP name. An application with a global name converter (such ascamel_case_to_snake_case) renames the other properties too.x-serializer-ignoreon a required property leaves the constructor without its argument, so denormalizing fails; the bridge warns about it.- The constructor of a discriminated variant checks its discriminator (generator 1.2). Denormalizing through the base
and its
DiscriminatorMapbuilds the class the value selects, and a variant selected by one value takes it as the default when the key is missing.deserialize()ordenormalize()straight into a variant with another class's value throws\InvalidArgumentExceptionfrom the constructor, which Symfony does not turn into a validation error; from Symfony 6.3,#[MapRequestPayload] Cat $catwith"petType": "dog"answers 500. Map the payload to the base (Pet $pet) instead. discriminator.defaultMapping(OpenAPI 3.2, generator 1.11) names a variant whose constructor checks no discriminator. From Symfony 7.3DiscriminatorMaptakes it asdefaultType, by the variant's first value, so a payload without the key builds it; an earlier Serializer gets no default, with a warning. Symfony selects no class for an unmapped value, and normalizing the default variant writes its own value over the one it holds.- Symfony Serializer cannot spread a map over the keys of its object: it would carry
$additionalProperties, the properties a schema does not declare, as one key"additionalProperties". By default the bridge ignores that property, with a warning, so undeclared keys are dropped when reading and not written;additionalProperties: spreadcarries them instead. The validator checks each value withAll/Valid, which covers the values a DTO is built with in code. The bridge'sx-validator-*andx-serializer-*keys for$additionalPropertiesgo on theadditionalPropertiesschema:x-serializer-ignore: truethere confirms the choice without the warning (and keepsIgnoreunderspread), whilex-serializer-skip: truebrings the single key back. date-timegets no format: Symfony's RFC 3339 default fits it. From Serializer 8.1, which deprecates reading other forms such as fractions of a second, the bridge asks for the loose parser instead. A property attribute wins over the context of the call, so adatetime_formatpassed todeserialize()does not apply to those properties;x-serializer-skipturns this off.readOnlyandwriteOnlyhave no single attribute.
Undeclared properties (additionalProperties)
A schema with properties and an additionalProperties schema gets a property $additionalProperties: a map of the
keys the schema does not declare. To carry them through Symfony Serializer, set
extensionConfig: symfony: additionalProperties: spread
The bridge then writes #[\Msstc4Symfony\DtoGeneratorBridge\Runtime\AdditionalProperties] on that property instead of
Ignore, and AdditionalPropertiesNormalizer does the rest at runtime:
{"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.
- The normalizer runs in your application, in every environment. It lives in
msstc4symfony/dto-generator-bridge-runtime, which the bridge requires: install it withcomposer requireand register itsDtoGeneratorRuntimeBundlefor all environments, so the bridge and the generator can stay development dependencies. Without the normalizer the DTOs carry neitherIgnorenor a normalizer, and Symfony writes and reads one literal key"additionalProperties". - It needs PHP 8.0+ and
symfony/serializer5.4, 6.4, 7.x or 8.x; the generated DTOs must use attributes (target.metadata), and a target that writes annotations (PHP 7.4) is an error. - How keys are declared and spread, its priority in the serializer, the setup without a bundle and the limits of some Serializer releases: see the runtime's README.
Read and write models
With the generator's dto.readWriteModels: split (generator 1.3), a schema with readOnly or writeOnly properties
gives two classes, such as AccountRead (responses, no writeOnly properties) and AccountWrite (requests, no
readOnly ones). The bridge treats them as any other class: each gets the constraints and attributes of its own
properties, so a writeOnly password is validated in AccountWrite only, and a discriminated base maps the variants
of its own model. Deserialize a request body into the write model (#[MapRequestPayload] AccountWrite $account) and
serialize the read model in the response.
Collection objects
With the generator's dto.collections (generator 1.18), a list property is a collection object (TagList $tags).
The bridge writes its #[Serializer\Context] with dto_generator_collection: {class, item}, which the runtime's
CollectionNormalizer reads to build the object from the list and to write it back (see
the runtime's README); a date
format of the items goes into the same Context, because Symfony keeps one per property. The list's constraints stay:
minItems/maxItems as Count, uniqueItems as Unique, the items' as All and Valid. Symfony checks them on
an object only when it is Countable (Count), an IteratorAggregate (Unique) and Traversable (All, Valid), as
dto-collection's lists are. contains, prefixItems and unevaluatedItems are checked on arrays only, as before
(with a warning on a collection).
The item type the Serializer reads is the class or enum (an enum below PHP 8.1 as its scalar), the scalar, or
Tag[] for a list or map of classes. Items it cannot type, such as nullable objects (?Tag) or a union, stay as
the data has them, with a warning. CollectionNormalizer needs PHP 8.0 and dto-generator-bridge-runtime 1.4: on an
older target or runtime the bridge warns once, since the Serializer cannot build the collection then. It warns once
for Symfony before 6.2 too: that Serializer gives a constructor argument, which every property of a generated DTO
is, no Context, so ObjectNormalizer makes the collection without its items.
Symfony bundle
The generator needs no bundle. In a Symfony application, DtoGeneratorBundle adds a console command, an optional
check on cache warmup and, on PHP 8.0+, AdditionalPropertiesNormalizer
in the serializer. With the bridge installed as a dev dependency (composer require --dev), register the bundle
for the environments that have it, and the runtime's bundle for all of them when the DTOs use
additionalProperties: spread (both register the same normalizer, so they may run together):
// config/bundles.php return [ // ... Msstc4Symfony\DtoGeneratorBridge\Runtime\Bundle\DtoGeneratorRuntimeBundle::class => ['all' => true], Msstc4Symfony\DtoGeneratorBridge\Bundle\DtoGeneratorBundle::class => ['dev' => true, 'test' => true], ];
The warmup check in production needs the bridge in require and the bundle registered with ['all' => true].
# config/packages/dto_generator.yaml dto_generator: config: '%kernel.project_dir%/dto-generator.yaml' # the default mode: committed # committed: the DTOs live in your sources; build: see "Building the DTOs with the container" check_on_warmup: false # true: warn in the log on cache warmup when the DTOs are out of date
bin/console dto-generator:generate [--config=...] [--check] [--dry-run] [--format=text|json] [--refresh-remote] takes
the same options and gives the same output and exit codes as the generator's own generate command, with the same
process settings: it raises a memory_limit below 1G to 1G (or takes DTO_GENERATOR_MEMORY_LIMIT), moves PHP errors to
stderr when display_errors shows them (On or stdout), and ends a PHP fatal error with exit code 2 (on PHP 7.4,
an error raised inside a function keeps PHP's own 255). A relative config or --config is resolved against the
project directory, not the current one; an empty --config keeps the bundle's. The warmup check never writes files,
never changes the process and never fails the warmup: whatever goes wrong becomes a warning in the log.
The command is meant for a bin/console process of its own. Run inside a long-lived process (CommandTester or
ApplicationTester in a test suite, Messenger's RunCommandMessage, Application::run() from a controller), it leaves
that process with display_errors=stderr (when it showed errors), a memory_limit of at least 1G (or
DTO_GENERATOR_MEMORY_LIMIT, which may also lower it) and a shutdown handler that ends a later fatal error with exit
code 2 (255 on PHP 7.4 for an error inside a function).
DTO_GENERATOR_MEMORY_LIMIT must be a real environment variable of the process (DTO_GENERATOR_MEMORY_LIMIT=2G bin/console dto-generator:generate): Symfony's Dotenv does not call putenv() (since 5.0), so a value in .env does
not reach the generator.
Building the DTOs with the container
The recommended setup commits the generated DTOs: reviews show their changes, IDEs and PHPStan see them, and production
needs neither the generator nor the bridge. When the DTOs should not live in the repository, mode: build generates
them whenever Symfony builds its container (cache:clear, cache:warmup, the first request in dev):
# config/packages/dto_generator.yaml dto_generator: mode: build
- The bridge, and with it the generator, must then be in
requireand its bundle registered for all environments. - Each source's
outputDirmoves to%kernel.build_dir%/dto-generator/, at its path relative to the config's directory (src/Dtobecomesvar/cache/prod/dto-generator/src/Dto); the project's sources are never written. AnoutputDiroutside the config's directory is an error. - The bundle loads the classes from there with an autoloader of its own, so Composer's
--classmap-authoritativedoes not hide them. The generation runs before the container reads controller signatures, so#[MapRequestPayload] Pet $petworks. - The config and the specifications are resources of the container: in
dev, an edit rebuilds the container and the DTOs on the next request. - No network: remote
$refs come from the committedremoteRefs.cacheDir. A container that cannot build cannot runbin/consoleeither, so fill the cache with the generator's own CLI, from the project directory (add--config=for a config other thandto-generator.yaml):vendor/bin/dto-generator generate --output-root=var/cache/dev/dto-generator. It writes the DTOs there too, which thedevcontainer rebuilds anyway; the point is the cache. Indev,bin/console dto-generator:generatewrites into the build directory as well; inprodrun onlycache:clear. - A generation error stops the container build with the generator's diagnostics. Warnings go to the container's
compiler log (
<ContainerClass>Compiler.login the build directory), which Symfony writes only withdebug: trueand not under PHPUnit: aprodbuild records none. - The generation runs on every container build, in the process that builds it: in
devthat may be a web request with itsmemory_limitand time limit, which the generator's CLI would raise. The specifications' resources only decide when the container is rebuilt. - Symfony loads
src/as services before the generation runs, so a class of your own may not extend or implement a generated type (such as a discriminated base); refer to the DTOs, as controllers and services usually do. check_on_warmuphas nothing to compare and is an error together withmode: build.- IDEs and static analysis see the classes only after a local build; point them at the build directory
(PHPStan:
scanDirectories: [var/cache/dev/dto-generator]). Unit tests that do not boot the kernel do not load them either. - The paths of the DTOs stay the same from one deploy to the next: with
opcache.validate_timestamps=0, reload PHP-FPM after a deploy, as for any other code. A long-running worker (FrankenPHP, RoadRunner) keeps the DTOs it loaded until it restarts.
x- keywords
| Key | On | Effect |
|---|---|---|
x-validator-groups: [api] |
property | Validation groups of its constraints instead of groups from the config |
x-validator-groups-exclusive: true |
property | Leaves out the Default group otherwise added |
x-validator-skip: true |
property | No constraints |
x-validator-format: false |
property | Its formats unchecked; true checks them though the config turns them off |
x-serializer-groups: [api] |
property | Groups(['api']) |
x-serializer-ignore: true |
property | Ignore |
x-serializer-skip: true |
property | No serializer attributes |
For $additionalProperties the keys go on the additionalProperties schema. The generator's own keys
(x-php-name, x-php-type, x-php-attributes…) are described in its
documentation.
Development
make install-ci # the CI profile: Symfony components, tools, the generator from GitHub make check make test make infection tests/Integration/Symfony/run-matrix.sh '5.4.*' # one Symfony line in Docker, against a generator checkout (CORE=…)
CI runs the suite on Symfony 5.4, 6.4, 7.4 and 8 (and once with the lowest dependencies), PHPStan on the Symfony-bound code, and a PHP 7.4 job with only the generator installed.
Changelog and security
See CHANGELOG.md and SECURITY.md.
License
MIT, see LICENSE.