Skip to content

Commit

Permalink
Add a handy CallbackReader to read from Closure
Browse files Browse the repository at this point in the history
  • Loading branch information
yann-eugone committed Mar 11, 2024
1 parent 12de1d5 commit d73b4e7
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/batch/docs/domain/item-job/item-reader.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ It can be any class implementing [ItemReaderInterface](../../../src/Job/Item/Ite
read from multiple item reader, one after the other.
- [StaticIterableReader](../../../src/Job/Item/Reader/StaticIterableReader.php):
read from an iterable you provide during construction.
- [CallbackReader](../../../src/Job/Item/Reader/CallbackReader.php):
read from a `Closure` you provide during construction.

**Item readers from bridges:**
- [FlatFileReader (`openspout/openspout`)](https://github.com/yokai-php/batch-openspout/blob/0.x/src/Reader/FlatFileReader.php):
Expand Down
23 changes: 23 additions & 0 deletions src/batch/src/Job/Item/Reader/CallbackReader.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

declare(strict_types=1);

namespace Yokai\Batch\Job\Item\Reader;

use Yokai\Batch\Job\Item\ItemReaderInterface;

final class CallbackReader implements ItemReaderInterface
{
public function __construct(
/**
* @var \Closure(): iterable<mixed>
*/
private readonly \Closure $callback,
) {
}

public function read(): iterable
{
return ($this->callback)();
}
}
44 changes: 44 additions & 0 deletions src/batch/tests/Job/Item/Reader/CallbackReaderTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

declare(strict_types=1);

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

use PHPUnit\Framework\TestCase;
use Yokai\Batch\Job\Item\Reader\CallbackReader;

class CallbackReaderTest extends TestCase
{
/**
* @dataProvider provider
*/
public function test(array $expected, \Closure $closure): void
{
$items = [];
foreach ((new CallbackReader($closure))->read() as $item) {
$items[] = $item;
}

self::assertSame($expected, $items);
}

public static function provider(): \Generator
{
yield 'array' => [
[1, 2, 3],
fn() => [1, 2, 3],
];
yield 'iterator' => [
[1, 2, 3],
fn() => new \ArrayIterator([1, 2, 3]),
];
yield 'generator' => [
[1, 2, 3],
function () {
yield 1;
yield 2;
yield 3;
},
];
}
}

0 comments on commit d73b4e7

Please sign in to comment.