Skip to content

Commit

Permalink
Fix: Chain transformers using generators in the middle (#25)
Browse files Browse the repository at this point in the history
  • Loading branch information
bpolaszek authored Nov 10, 2023
1 parent 954c2fa commit 643db21
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
20 changes: 15 additions & 5 deletions src/Transformer/ChainTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
namespace BenTools\ETL\Transformer;

use BenTools\ETL\EtlState;
use BenTools\ETL\Internal\TransformResult;
use Generator;

final readonly class ChainTransformer implements TransformerInterface
{
Expand All @@ -32,13 +32,23 @@ public function with(TransformerInterface|callable $transformer): self
return new self(...[...$this->transformers, $transformer]);
}

public function transform(mixed $item, EtlState $state): mixed
public function transform(mixed $item, EtlState $state): Generator
{
$item = $this->doTransform($item, $state);

if ($item instanceof Generator) {
yield from $item;
} else {
yield $item;
}
}

public function doTransform(mixed $item, EtlState $state): mixed
{
$output = $item;
foreach ($this->transformers as $transformer) {
$output = TransformResult::create($transformer->transform($output, $state))->value;
$item = $items = $transformer->transform($item, $state);
}

return $output;
return $item;
}
}
4 changes: 3 additions & 1 deletion tests/Unit/Transformer/ChainTransformerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ function (string $item): Generator {
yield strtoupper($item);
},
))
->with(fn (Generator $items): array => [...$items])
->with(function (array $items): array {
$items[] = 'hey';

Expand Down Expand Up @@ -52,12 +53,13 @@ function (string $item): Generator {
yield $item;
yield strtoupper($item);
},
fn (Generator $items): array => [...$items],
function (array $items): array {
$items[] = 'hey';

return $items;
},
fn (array $items): string => implode('-', $items)
fn (array $items) => yield implode('-', $items)
);

// When
Expand Down

0 comments on commit 643db21

Please sign in to comment.