diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e903e4..9bef553 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,12 @@ See [GitHub releases](https://github.com/mll-lab/php-utils/releases). ## Unreleased +## v1.10.0 + +### Added + +- Allow custom line separator in `CSVArray::toCSV()` + ## v1.9.0 ### Added diff --git a/src/CSVArray.php b/src/CSVArray.php index da49df6..fe7fc7f 100644 --- a/src/CSVArray.php +++ b/src/CSVArray.php @@ -51,26 +51,23 @@ public static function toArray(string $csv, string $delimiter = ';', string $enc } /** @param array> $data */ - public static function toCSV(array $data, string $delimiter = ';'): string + public static function toCSV(array $data, string $delimiter = ';', string $lineSeparator = "\r\n"): string { if ($data === []) { throw new \Exception('Array is empty'); } // Use the keys of the array as the headers of the CSV - $headerLine = Arr::first($data); - if (! is_array($headerLine)) { + $headerItem = Arr::first($data); + if (! is_array($headerItem)) { throw new \Exception('Missing column headers.'); } + $headerKeys = array_keys($headerItem); - $content = str_putcsv( - array_keys($headerLine), - $delimiter - ) - . "\r\n"; + $content = str_putcsv($headerKeys, $delimiter) . $lineSeparator; foreach ($data as $line) { - $content .= str_putcsv($line, $delimiter) . "\r\n"; + $content .= str_putcsv($line, $delimiter) . $lineSeparator; } return $content; diff --git a/tests/CSVArrayTest.php b/tests/CSVArrayTest.php index 1a70e34..87500f9 100644 --- a/tests/CSVArrayTest.php +++ b/tests/CSVArrayTest.php @@ -69,6 +69,27 @@ public function testEscapesDelimiter(): void ); } + public function testUnixLike(): void + { + self::assertSame( + << 1, + 'bar' => 2, + ], + ], + ',', + "\n" + ) + ); + } + public function testPrimitives(): void { self::assertSame(