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
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
28 changes: 28 additions & 0 deletions src/batch/src/Job/Item/Reader/CallbackReader.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace Yokai\Batch\Job\Item\Reader;

use Yokai\Batch\Job\Item\ItemReaderInterface;

/**
* An {@see ItemReaderInterface} that read from a {@see Closure} provided at construction.
*
* Provided {@see Closure} must accept no argument and must return an iterable of read items.
*/
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;
},
];
}
}