Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions src/Builder/BuilderEncoder.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@
use WeakReference;

use function array_key_exists;
use function is_array;
use function is_object;
use function iterator_to_array;

/** @template-implements Encoder<Type|stdClass|array|string|int, Pipeline|StageInterface|ExpressionInterface|QueryInterface> */
final class BuilderEncoder implements Encoder
Expand All @@ -46,11 +48,15 @@ final class BuilderEncoder implements Encoder
/** @var array<class-string, Encoder|null> */
private array $cachedEncoders = [];

/** @param array<class-string, Encoder> $encoders */
public function __construct(array $encoders = [])
/** @param iterable<class-string, Encoder> $encoders */
public function __construct(iterable $encoders = [])
{
$self = WeakReference::create($this);

if (! is_array($encoders)) {
$encoders = iterator_to_array($encoders);
}

$this->encoders = $encoders + [
Pipeline::class => new PipelineEncoder($self),
Variable::class => new VariableEncoder(),
Expand Down
42 changes: 42 additions & 0 deletions tests/Builder/BuilderEncoderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,48 @@ public function encode(mixed $value): mixed
$this->assertSamePipeline($expected, $pipeline, $codec);
}

public function testCustomEncoderIterable(): void
{
$customEncoders = static function (): Generator {
yield FieldPathInterface::class => new class implements Encoder {
use EncodeIfSupported;

public function canEncode(mixed $value): bool
{
return $value instanceof FieldPathInterface;
}

public function encode(mixed $value): mixed
{
return '$prefix.' . $value->name;
}
};
};

$codec = new BuilderEncoder($customEncoders());

$pipeline = new Pipeline(
Stage::project(
threeFavorites: Expression::slice(
Expression::arrayFieldPath('items'),
n: 3,
),
),
);

$expected = [
[
'$project' => [
'threeFavorites' => [
'$slice' => ['$prefix.items', 3],
],
],
],
];

$this->assertSamePipeline($expected, $pipeline, $codec);
}

/** @param list<array<string, mixed>> $expected */
private static function assertSamePipeline(array $expected, Pipeline $pipeline, $codec = new BuilderEncoder()): void
{
Expand Down