Skip to content

Add a writer that transform items before delegating to another writer #65

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 31, 2022
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-writer.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ It can be any class implementing [ItemWriterInterface](../../../src/Job/Item/Ite
route writing to different writer based on your logic.
- [SummaryWriter](../../../src/Job/Item/Writer/SummaryWriter.php):
write items to a job summary value.
- [TransformingWriter](../../../src/Job/Item/Writer/TransformingWriter.php):
perform items transformation before delegating to another writer.

**Item writers from bridges:**
- [DoctrineDBALInsertWriter (`doctrine/dbal`)](https://github.com/yokai-php/batch-doctrine-dbal/blob/0.x/src/DoctrineDBALInsertWriter.php):
Expand Down
81 changes: 81 additions & 0 deletions src/batch/src/Job/Item/Writer/TransformingWriter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?php

declare(strict_types=1);

namespace Yokai\Batch\Job\Item\Writer;

use Yokai\Batch\Exception\UnexpectedValueException;
use Yokai\Batch\Job\Item\ElementConfiguratorTrait;
use Yokai\Batch\Job\Item\Exception\SkipItemException;
use Yokai\Batch\Job\Item\FlushableInterface;
use Yokai\Batch\Job\Item\InitializableInterface;
use Yokai\Batch\Job\Item\ItemProcessorInterface;
use Yokai\Batch\Job\Item\ItemWriterInterface;
use Yokai\Batch\Job\JobExecutionAwareInterface;
use Yokai\Batch\Job\JobExecutionAwareTrait;

/**
* This {@see ItemWriterInterface} will transform provided items
* using a {@see ItemProcessorInterface},
* then will delegate writing to another {@see ItemWriterInterface}.
*/
final class TransformingWriter implements
ItemWriterInterface,
JobExecutionAwareInterface,
InitializableInterface,
FlushableInterface
{
use JobExecutionAwareTrait;
use ElementConfiguratorTrait;

public function __construct(
private ItemProcessorInterface $processor,
private ItemWriterInterface $writer,
) {
}

public function write(iterable $items): void
{
$transformedItems = [];

foreach ($items as $index => $item) {
if (!\is_string($index) && !\is_int($index)) {
throw UnexpectedValueException::type('string|int', $index);
}

try {
$transformedItems[] = $this->processor->process($item);
} catch (SkipItemException $exception) {
$this->jobExecution->getLogger()->debug(
\sprintf('Skipping item in writer transformation %s.', $index),
$exception->getContext() + ['item' => $exception->getItem()]
);

$cause = $exception->getCause();
if ($cause) {
$cause->report($this->jobExecution, $index, $exception->getItem());
}

continue;
}
}

if (count($transformedItems) > 0) {
$this->writer->write($transformedItems);
}
}

public function initialize(): void
{
$this->configureElementJobContext($this->processor, $this->jobExecution);
$this->initializeElement($this->processor);
$this->configureElementJobContext($this->writer, $this->jobExecution);
$this->initializeElement($this->writer);
}

public function flush(): void
{
$this->flushElement($this->processor);
$this->flushElement($this->writer);
}
}
84 changes: 84 additions & 0 deletions src/batch/tests/Job/Item/Writer/TransformingWriterTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
<?php

declare(strict_types=1);

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

use PHPUnit\Framework\TestCase;
use Yokai\Batch\Exception\UnexpectedValueException;
use Yokai\Batch\Job\Item\Exception\SkipItemException;
use Yokai\Batch\Job\Item\Processor\CallbackProcessor;
use Yokai\Batch\Job\Item\Processor\NullProcessor;
use Yokai\Batch\Job\Item\Writer\TransformingWriter;
use Yokai\Batch\JobExecution;
use Yokai\Batch\Test\Job\Item\Processor\TestDebugProcessor;
use Yokai\Batch\Test\Job\Item\Writer\InMemoryWriter;
use Yokai\Batch\Test\Job\Item\Writer\TestDebugWriter;

class TransformingWriterTest extends TestCase
{
public function test(): void
{
$writer = new TransformingWriter(
$debugProcessor = new TestDebugProcessor(new CallbackProcessor(fn ($string) => \strtoupper($string))),
$debugWriter = new TestDebugWriter($innerWriter = new InMemoryWriter())
);

$writer->setJobExecution(JobExecution::createRoot('123', 'test.transforming_writer'));
$writer->initialize();
$writer->write(['one', 'two', 'three']);
$writer->flush();

$debugProcessor->assertWasConfigured();
$debugProcessor->assertWasUsed();
$debugWriter->assertWasConfigured();
$debugWriter->assertWasUsed();
self::assertSame(['ONE', 'TWO', 'THREE'], $innerWriter->getItems());
}

public function testSkipItems(): void
{
$writer = new TransformingWriter(
$debugProcessor = new TestDebugProcessor(
new CallbackProcessor(
fn ($item) => throw SkipItemException::withWarning($item, 'Skipped for test purpose')
)
),
$debugWriter = new TestDebugWriter($innerWriter = new InMemoryWriter())
);

$writer->setJobExecution($execution = JobExecution::createRoot('123', 'test.transforming_writer'));
$writer->initialize();
$writer->write(['one', 'two', 'three']);
$writer->flush();

$debugProcessor->assertWasConfigured();
$debugProcessor->assertWasUsed();
$debugWriter->assertWasConfigured();
$debugWriter->assertWasNotUsed(true, true);
self::assertSame([], $innerWriter->getItems());
self::assertCount(3, $warnings = $execution->getWarnings());
self::assertSame('Skipped for test purpose', $warnings[0]->getMessage());
self::assertSame(['itemIndex' => 0, 'item' => 'one'], $warnings[0]->getContext());
self::assertSame('Skipped for test purpose', $warnings[1]->getMessage());
self::assertSame(['itemIndex' => 1, 'item' => 'two'], $warnings[1]->getContext());
self::assertSame('Skipped for test purpose', $warnings[2]->getMessage());
self::assertSame(['itemIndex' => 2, 'item' => 'three'], $warnings[2]->getContext());
self::assertStringContainsString('Skipping item in writer transformation 0.', (string)$execution->getLogs());
self::assertStringContainsString('Skipping item in writer transformation 1.', (string)$execution->getLogs());
self::assertStringContainsString('Skipping item in writer transformation 2.', (string)$execution->getLogs());
}

public function testInvalidIndexType(): void
{
$this->expectException(UnexpectedValueException::class);
$this->expectExceptionMessage('Expecting argument to be string|int, but got null.');

$writer = new TransformingWriter(new NullProcessor(), new InMemoryWriter());
$generator = function () {
yield null => null;
};

$writer->write($generator());
}
}