map()

Map operator iterates over given stream source and applies transformation functions on keys/values before yielding.

Operator may be used to transform only keys, or only values, or both.

class RunOpenCode\Component\Dataset\Operator\Map
__construct(iterable<TKey, TValue> $source, ?callable(TValue, TKey=): TModifiedValue $valueTransform = null, ?callable(TKey, TValue=): TModifiedKey $keyTransform = null)
Parameters:
  • $sourceiterable<TKey, TValue> Stream source to iterate over.

  • $valueTransform?callable(TValue, TKey=): TModifiedValue Optional transformation function for transforming values.

  • $keyTransform?callable(TKey, TValue=): TModifiedKey Optional transformation function for transforming keys.

getIterator()
Returns:

\Traversable<TModifiedKey, TModifiedValue> Modified keys and values from the stream source.

Use cases

  • Modify values and/or keys.

  • Index stream records by value.

Example

Transform rows from database into entity objects, collect them into an array indexed by identifier.

 1<?php
 2
 3$dataset = $database->execute('SELECT ...');
 4
 5new Stream($dataset)
 6    ->map(
 7        valueTransform: static function(array $row): Entity {
 8            return Entity::fromArray($row);
 9        },
10        keyTransform: static function(int $key, array $row): string {
11            return $row['id'];
12        }
13    );