Skip to content

Commit

Permalink
Add a handy CallbackWriter to write with a Closure (#120)
Browse files Browse the repository at this point in the history
* Add a handy CallbackWriter to write with a Closure

* Fixed missing comment on CallbackWriter
  • Loading branch information
yann-eugone authored Apr 29, 2024
1 parent 4be935c commit b333150
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
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);
}
}

0 comments on commit b333150

Please sign in to comment.