-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add a handy CallbackReader to read from Closure
- Loading branch information
1 parent
12de1d5
commit d73b4e7
Showing
3 changed files
with
69 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
}, | ||
]; | ||
} | ||
} |