Skip to main content

SubPropsForClassMapper / SubPropsFromClassMapper

Auto-build a SubPropsMapper from a class's typed properties, instead of declaring each child prop by hand.

  • Mappers::subPropsForClass($class) reflects the class's writable properties and registers a child prop for each, with mappers derived from the property's setter type: scalars → typeNotNull, enums → enum, dates/Url → the matching date/url mapper, unmarshalable value objects → unmarshal. Non-nullable props without a default get a mandatory/mustExistIf rule. Used to unmarshal array data into an object.
  • Mappers::subPropsFromClass($class) reflects the class's readable properties and validates/coerces incoming values against their type constraints. Used when binding from an object (or attrs shaped like one).

Both are applied with logicalRoot() (or logicalProp()).

subPropsForClass is the engine behind ObjectUnmarshalTrait: a value object's unmarshal() pipes subPropsForClass(static::class) (validate/convert each child) into subMergeToObject() (assemble the children into a real object). See UnmarshalMapper and SubMergeMapper.

Example: subPropsForClass​

$targetAttrs = Bind::attrs(['prop' => 'value1', 'nullableProp' => 'value2',
'undefNullableProp' => 'value3', 'mixedProp' => ['value4']])
->logicalRoot(Mappers::subPropsForClass(SimpleBaseRecord::class))
->toArray()->exec()->get();
var_dump($targetAttrs);

Output:

array(4) {
["prop"]=>
string(6) "value1"
["nullableProp"]=>
string(6) "value2"
["undefNullableProp"]=>
string(6) "value3"
["mixedProp"]=>
array(1) {
[0]=>
string(6) "value4"
}
}

Each input value is coerced to its declared property type and written back. Known types are mapped too — a string '2025-08-01 12:00:00' on a \DateTime-typed prop becomes a DateTime instance.

Example: subPropsFromClass​

$targetAttrs = Bind::attrs(['prop' => 'huii', 'nullableProp' => null, 'mixedProp' => []])
->logicalRoot(Mappers::subPropsFromClass(SimpleBaseRecord::class))
->toArray()->exec()->get();
var_dump($targetAttrs);

Output:

array(3) {
["prop"]=>
string(4) "huii"
["nullableProp"]=>
NULL
["mixedProp"]=>
array(0) {
}
}

A value incompatible with a declared type (e.g. a \DateTimeImmutable where a string prop is expected) throws BindMismatchException.