Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a handy CallbackWriter to write with a Closure #120

Merged
merged 2 commits into from
Apr 29, 2024
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
2 changes: 2 additions & 0 deletions src/batch/docs/domain/item-job/item-writer.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ It can be any class implementing [ItemWriterInterface](../../../src/Job/Item/Ite
write items to a job summary value.
- [TransformingWriter](../../../src/Job/Item/Writer/TransformingWriter.php):
perform items transformation before delegating to another writer.
- [CallbackWriter](../../../src/Job/Item/Writer/CallbackWriter.php):
delegate items write operations to a closure passed at construction.

**Item writers from bridges:**
- [DispatchEachItemAsMessageWriter (`symfony/messenger`)](https://github.com/yokai-php/batch-symfony-messenger/blob/0.x/src/Writer/DispatchEachItemAsMessageWriter.php):
Expand Down
25 changes: 25 additions & 0 deletions src/batch/src/Job/Item/Writer/CallbackWriter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

declare(strict_types=1);

namespace Yokai\Batch\Job\Item\Writer;

use Yokai\Batch\Job\Item\ItemWriterInterface;

/**
* An {@see ItemWriterInterface} that write items with a {@see Closure} provided at construction.
*
* Provided {@see Closure} must accept items to write and must return nothing.
*/
final class CallbackWriter implements ItemWriterInterface
{
public function __construct(
private \Closure $callback,
) {
}

public function write(iterable $items): void
{
($this->callback)($items);
}
}
23 changes: 23 additions & 0 deletions src/batch/tests/Job/Item/Writer/CallbackWriterTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

declare(strict_types=1);

namespace Yokai\Batch\Tests\Job\Item\Writer;

use PHPUnit\Framework\TestCase;
use Yokai\Batch\Job\Item\Writer\CallbackWriter;

class CallbackWriterTest extends TestCase
{
public function testWrite(): void
{
$saveditems = [];
$writer = new CallbackWriter(function (array $items) use (&$saveditems) {
$saveditems = [...$saveditems, ...$items];
});
$writer->write([1, 2, 3]);
$writer->write([4, 5, 6]);

self::assertSame([1, 2, 3, 4, 5, 6], $saveditems);
}
}
Loading