diff --git a/src/Services/Writer.php b/src/Services/Writer.php index f258e71..3be6f4e 100644 --- a/src/Services/Writer.php +++ b/src/Services/Writer.php @@ -92,10 +92,16 @@ protected function iterateRows(object $exportable, foreach ($rows as $index => $row) { $mappedRow = $withMapping ? $exportable->map($row) : $row; - $normalizedRow = $this->normalizeRow($mappedRow); - $formattedRow = $this->applyFormatting($normalizedRow, $formats, $index); - $this->writeRow($formattedRow); + $firstElement = is_array($mappedRow) ? reset($mappedRow) : null; + + if ($withMapping && is_array($firstElement)) { + foreach ($mappedRow as $subRow) { + $this->processAndWriteRow($subRow, $formats, $index); + } + } else { + $this->processAndWriteRow($mappedRow, $formats, $index); + } } } @@ -178,6 +184,20 @@ protected function formatCellValue(mixed $value, return $value; } + /** + * @param mixed $row + * @param array $formats + * @param int $rowIndex + * @return void + * @throws InvalidCellValueException + */ + protected function processAndWriteRow(mixed $row, array $formats, int $rowIndex): void + { + $normalizedRow = $this->normalizeRow($row); + $formattedRow = $this->applyFormatting($normalizedRow, $formats, $rowIndex); + $this->writeRow($formattedRow); + } + /** * @param array $content * @return void diff --git a/tests/Concerns/WithMappingTest.php b/tests/Concerns/WithMappingTest.php index 28eeace..c274040 100644 --- a/tests/Concerns/WithMappingTest.php +++ b/tests/Concerns/WithMappingTest.php @@ -4,6 +4,7 @@ use Vitorccs\LaravelCsv\Tests\Data\Database\Seeders\TestCsvSeeder; use Vitorccs\LaravelCsv\Tests\Data\Exports\WithMappingExport; +use Vitorccs\LaravelCsv\Tests\Data\Exports\WithMappingMultipleRowsExport; use Vitorccs\LaravelCsv\Tests\Data\Imports\WithMappingImport; use Vitorccs\LaravelCsv\Tests\TestCase; @@ -35,4 +36,14 @@ public function test_import_mapping() $this->assertSame($rows, $expected); } + + public function test_export_mapping_multiple_rows() + { + $export = new WithMappingMultipleRowsExport(); + + $export->store($this->filename); + $actual = $this->getFromDisk($this->filename); + + $this->assertSame($export->expected(), $actual); + } } diff --git a/tests/Data/Exports/WithMappingMultipleRowsExport.php b/tests/Data/Exports/WithMappingMultipleRowsExport.php new file mode 100644 index 0000000..e825437 --- /dev/null +++ b/tests/Data/Exports/WithMappingMultipleRowsExport.php @@ -0,0 +1,48 @@ +id, + $row->string . '_first', + ], + [ + $row->id, + $row->string . '_second', + ], + ]; + } + + public function expected(): string + { + return '1,text_1_first' . "\n" . + '1,text_1_second' . "\n" . + '2,text_2_first' . "\n" . + '2,text_2_second' . "\n" . + '3,text_3_first' . "\n" . + '3,text_3_second' . "\n" . + '4,text_4_first' . "\n" . + '4,text_4_second' . "\n" . + '5,text_5_first' . "\n" . + '5,text_5_second' . "\n" . + '6,text_6_first' . "\n" . + '6,text_6_second'; + } +}