encodeProperty steps to describe how each field is computed from source data.
Creates a Closure that builds a fresh record (array or object) from a source value by applying a series of encodeProperty() steps.
/**
* @param array<string,mixed>|ArrayObject<string,mixed>|object $dataType
* @return Closure(Closure ...):(array|object)
*/
GeneralFunctions\recordEncoder($dataType): ClosurerecordEncoder is the scaffold; encodeProperty is the brick. Each brick pairs one output key with a callable that produces its value from the source. The scaffold collects the bricks, applies each one to the input, and returns a fresh record.
This pattern separates what the output record is from how each field is computed:
recordEncoder instead of [].The record passed to recordEncoder determines the output kind:
recordEncoder([]) — output is a fresh array.recordEncoder(new \stdClass) — output is an object (properties set via setProperty).recordEncoder(new MyDto) — output is your DTO with each field assigned as a public property.Each field callable is just a plain callable — use anything that takes the source record and returns a value:
getProperty / pluckProperty for simple and nested lookups.compose for multi-step transforms.ifElse with always for conditionals.See Transforming complex objects for a step-by-step build that turns raw API records into view models using recordEncoder alongside encodeProperty, pluckProperty, propertyEquals, ifElse, and always.
This can be used to create a simple closure which can be used as a regular function.
$toViewModel = GeneralFunctions\recordEncoder([])(
GeneralFunctions\encodeProperty('id', GeneralFunctions\getProperty('id')),
GeneralFunctions\encodeProperty('title', fn($u) => strtoupper($u['name'])),
GeneralFunctions\encodeProperty('admin', GeneralFunctions\propertyEquals('role', 'admin'))
);
print_r($toViewModel(['id' => 1, 'name' => 'Ada', 'role' => 'admin']));
// ['id' => 1, 'title' => 'ADA', 'admin' => true]