diff --git a/Application/Model/ExportRenderer/Csv.php b/Application/Model/ExportRenderer/Csv.php index 04c5ebe..557d05f 100644 --- a/Application/Model/ExportRenderer/Csv.php +++ b/Application/Model/ExportRenderer/Csv.php @@ -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; } diff --git a/tests/unit/Application/Model/ExportRenderer/CsvTest.php b/tests/unit/Application/Model/ExportRenderer/CsvTest.php index b3a509d..437673a 100644 --- a/tests/unit/Application/Model/ExportRenderer/CsvTest.php +++ b/tests/unit/Application/Model/ExportRenderer/CsvTest.php @@ -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