refactor CSV format class

- add column consistency check
- can force enclosure optionally
This commit is contained in:
Daniel Seifert 2024-05-13 15:28:30 +02:00
parent 760b7b2509
commit 185caeeac3
2 changed files with 40 additions and 7 deletions

View File

@ -16,7 +16,7 @@ declare(strict_types=1);
namespace D3\DataWizard\Application\Model\ExportRenderer;
use D3\DataWizard\Application\Model\Exceptions\RenderException;
use League\Csv\EncloseField;
use League\Csv\ColumnConsistency;
use League\Csv\Exception;
use League\Csv\Writer;
use OxidEsales\Eshop\Core\Config;
@ -24,18 +24,22 @@ use OxidEsales\Eshop\Core\Registry;
class Csv implements RendererInterface
{
public function __construct(protected bool $forceEnclose = false)
{}
/**
* @param $rows
* @param $fieldNames
* @param iterable $rows
* @param iterable $fieldNames
*
* @return string
* @throws RenderException
*/
public function getContent($rows, $fieldNames): string
public function getContent(iterable $rows, iterable $fieldNames): string
{
try {
$csv = $this->getCsv();
$csv->insertOne($fieldNames);
$this->forceEnclose ? $csv->forceEnclosure() : $csv->relaxEnclosure();
$csv->insertOne((array) $fieldNames);
$csv->insertAll($rows);
return (string) $csv;
} catch (Exception $e) {
@ -58,14 +62,14 @@ class Csv implements RendererInterface
{
$csv = Writer::createFromString();
EncloseField::addTo($csv, "\t\x1f");
$sEncloser = $this->d3GetConfig()->getConfigParam('sGiCsvFieldEncloser') ?? '"';
$csv->setEnclosure($sEncloser);
$sDelimiter = $this->d3GetConfig()->getConfigParam('sCSVSign') ?? ';';
$csv->setDelimiter($sDelimiter);
$csv->addValidator(new ColumnConsistency(), 'columns_consistency');
return $csv;
}

View File

@ -17,6 +17,7 @@ namespace D3\DataWizard\tests\unit\Application\Model\ExportRenderer;
use D3\DataWizard\Application\Model\Exceptions\RenderException;
use D3\DataWizard\Application\Model\ExportRenderer\Csv;
use Generator;
use League\Csv\Exception;
use League\Csv\Writer;
use OxidEsales\Eshop\Core\Config;
@ -36,6 +37,34 @@ class CsvTest extends ExportRendererTest
$this->_oModel = oxNew(Csv::class);
}
/**
* @test
*
* @param bool $force
*
* @return void
* @throws ReflectionException
* @covers \D3\DataWizard\Application\Model\ExportRenderer\Csv::__construct
* @dataProvider canForceEncloseDataProvider
*/
public function canForceEnclose(bool $force): void
{
$noForce = oxNew(Csv::class, $force);
$this->assertSame(
$force,
$this->getValue(
$noForce,
'forceEnclose'
)
);
}
public function canForceEncloseDataProvider(): Generator
{
yield 'noForce' => [true];
yield 'force' => [false];
}
/**
* @covers \D3\DataWizard\Application\Model\ExportRenderer\Csv::getContent
* @test