Skip to content

Commit b333150

Browse files
authored
Add a handy CallbackWriter to write with a Closure (#120)
* Add a handy CallbackWriter to write with a Closure * Fixed missing comment on CallbackWriter
1 parent 4be935c commit b333150

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed

src/batch/docs/domain/item-job/item-writer.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ It can be any class implementing [ItemWriterInterface](../../../src/Job/Item/Ite
2727
write items to a job summary value.
2828
- [TransformingWriter](../../../src/Job/Item/Writer/TransformingWriter.php):
2929
perform items transformation before delegating to another writer.
30+
- [CallbackWriter](../../../src/Job/Item/Writer/CallbackWriter.php):
31+
delegate items write operations to a closure passed at construction.
3032

3133
**Item writers from bridges:**
3234
- [DispatchEachItemAsMessageWriter (`symfony/messenger`)](https://github.com/yokai-php/batch-symfony-messenger/blob/0.x/src/Writer/DispatchEachItemAsMessageWriter.php):
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Yokai\Batch\Job\Item\Writer;
6+
7+
use Yokai\Batch\Job\Item\ItemWriterInterface;
8+
9+
/**
10+
* An {@see ItemWriterInterface} that write items with a {@see Closure} provided at construction.
11+
*
12+
* Provided {@see Closure} must accept items to write and must return nothing.
13+
*/
14+
final class CallbackWriter implements ItemWriterInterface
15+
{
16+
public function __construct(
17+
private \Closure $callback,
18+
) {
19+
}
20+
21+
public function write(iterable $items): void
22+
{
23+
($this->callback)($items);
24+
}
25+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Yokai\Batch\Tests\Job\Item\Writer;
6+
7+
use PHPUnit\Framework\TestCase;
8+
use Yokai\Batch\Job\Item\Writer\CallbackWriter;
9+
10+
class CallbackWriterTest extends TestCase
11+
{
12+
public function testWrite(): void
13+
{
14+
$saveditems = [];
15+
$writer = new CallbackWriter(function (array $items) use (&$saveditems) {
16+
$saveditems = [...$saveditems, ...$items];
17+
});
18+
$writer->write([1, 2, 3]);
19+
$writer->write([4, 5, 6]);
20+
21+
self::assertSame([1, 2, 3, 4, 5, 6], $saveditems);
22+
}
23+
}

0 commit comments

Comments
 (0)