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:
  • $source – iterable<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
 3use RunOpenCode\Component\Dataset\Stream;
 4
 5$dataset = $database->execute('SELECT ...');
 6
 7new Stream($dataset)
 8    ->map(
 9        valueTransform: static function(array $row): Entity {
10            return Entity::fromArray($row);
11        },
12        keyTransform: static function(int $key, array $row): string {
13            return $row['id'];
14        }
15    );