Skip to content

Commit f087e97

Browse files
authored
Introduce a reader that read from a value fetched by a parameter accessor (#34)
1 parent 7991a53 commit f087e97

File tree

2 files changed

+82
-0
lines changed

2 files changed

+82
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Yokai\Batch\Job\Item\Reader;
6+
7+
use Yokai\Batch\Job\Item\ItemReaderInterface;
8+
use Yokai\Batch\Job\JobExecutionAwareInterface;
9+
use Yokai\Batch\Job\JobExecutionAwareTrait;
10+
use Yokai\Batch\Job\Parameters\JobParameterAccessorInterface;
11+
12+
/**
13+
* This {@see ItemReaderInterface} uses a {@see JobParameterAccessorInterface} to read data from.
14+
*/
15+
final class ParameterAccessorReader implements ItemReaderInterface, JobExecutionAwareInterface
16+
{
17+
use JobExecutionAwareTrait;
18+
19+
private JobParameterAccessorInterface $data;
20+
21+
public function __construct(JobParameterAccessorInterface $data)
22+
{
23+
$this->data = $data;
24+
}
25+
26+
/**
27+
* @inheritdoc
28+
*/
29+
public function read(): iterable
30+
{
31+
$data = $this->data->get($this->jobExecution);
32+
if (\is_iterable($data)) {
33+
return $data;
34+
}
35+
36+
return [$data];
37+
}
38+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Yokai\Batch\Tests\Job\Item\Reader;
6+
7+
use Generator;
8+
use PHPUnit\Framework\TestCase;
9+
use Yokai\Batch\Job\Item\Reader\ParameterAccessorReader;
10+
use Yokai\Batch\Job\Parameters\JobParameterAccessorInterface;
11+
use Yokai\Batch\Job\Parameters\StaticValueParameterAccessor;
12+
use Yokai\Batch\JobExecution;
13+
14+
class ParameterAccessorReaderTest extends TestCase
15+
{
16+
/**
17+
* @dataProvider provider
18+
*/
19+
public function test(JobParameterAccessorInterface $accessor, array $expected): void
20+
{
21+
$reader = new ParameterAccessorReader($accessor);
22+
$reader->setJobExecution(JobExecution::createRoot('123456', 'testing'));
23+
24+
$actual = [];
25+
foreach ($reader->read() as $idx => $item) {
26+
$actual[$idx] = $item;
27+
}
28+
29+
self::assertSame($expected, $actual);
30+
}
31+
32+
public function provider(): Generator
33+
{
34+
yield 'Read from preserved iterable' => [
35+
new StaticValueParameterAccessor([1 => 'One', 2 => 'Two', 3 => 'Three']),
36+
[1 => 'One', 2 => 'Two', 3 => 'Three']
37+
];
38+
39+
yield 'Read from static' => [
40+
new StaticValueParameterAccessor('Not iterable and converted to array'),
41+
['Not iterable and converted to array']
42+
];
43+
}
44+
}

0 commit comments

Comments
 (0)