/
GroupToArrayTransformer.php
46 lines (35 loc) · 1.1 KB
/
GroupToArrayTransformer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php
declare(strict_types=1);
namespace Flow\ETL\Transformer;
use Flow\ETL\Row\Entry;
use Flow\ETL\{FlowContext, Row, Rows, Transformer};
final class GroupToArrayTransformer implements Transformer
{
public function __construct(private readonly string $groupByEntry, private readonly string $newEntryName)
{
}
public function transform(Rows $rows, FlowContext $context) : Rows
{
/** @var array<array-key, array<mixed>> $entries */
$entries = [];
foreach ($rows as $row) {
$groupValue = $row->get($this->groupByEntry)->toString();
if (!\array_key_exists($groupValue, $entries)) {
$entries[$groupValue] = [];
}
$entries[$groupValue][] = $row->toArray();
}
$rows = new Rows();
foreach ($entries as $entry) {
$rows = $rows->add(
Row::create(
new Entry\ArrayEntry(
$this->newEntryName,
$entry
)
)
);
}
return $rows;
}
}