recordEncoder. Each encoder step knows which key it writes and how to compute its value from the source data.
Creates a Closure for use inside a recordEncoder() — pairs a property key with a function that produces its value from the input data.
/**
* @param string $key
* @param callable(mixed):mixed $value
* @return Closure(mixed):mixed
*/
GeneralFunctions\encodeProperty(string $key, callable $value): ClosureencodeProperty doesn’t touch any data by itself. It bundles a key with a way to compute its value — nothing more. The bundle is useful only inside recordEncoder, which collects many of these bundles and runs them over a source record to build an output record.
Think of it as declaring one row of a transformation table:
output key | computed from source via
-----------------+---------------------------------------
'id' | getProperty('id')
'displayName' | fn($u) => ucfirst($u['first']) . ' ' . ucfirst($u['last'])
'isAdmin' | propertyEquals('role', 'admin')
'country' | pluckProperty('profile', 'country')Each row is one encodeProperty call. The value callable can be anything — getProperty, pluckProperty, a closure, a composed pipeline from compose, a conditional from ifElse. All that matters is that it takes the source record and returns the value for that output field.
If you just wanted $output['displayName'] = strtoupper($source['name']) you could write exactly that. The separation pays off once you have several fields:
recordEncoder runs them.recordEncoder — the encodeProperty calls don’t change.See Transforming complex objects for the whole pattern — building a view model from a list of API records with encodeProperty for every output field plus recordEncoder to assemble them.
This can be used to create a simple closure which can be used as a regular function.
// One encoder step: the 'displayName' output field is computed from the source by upper-casing its 'name'.
$encodeName = GeneralFunctions\encodeProperty(
'displayName',
fn($src) => strtoupper($src['name'])
);
// On its own encodeProperty does nothing — it records the intent. The work happens inside recordEncoder.
$toViewModel = GeneralFunctions\recordEncoder([])($encodeName);
print_r($toViewModel(['name' => 'Ada'])); // ['displayName' => 'ADA']