Skip to content

Commit

Permalink
Allow custom line separator in CSVArray::toCSV()
Browse files Browse the repository at this point in the history
  • Loading branch information
spawnia committed Jan 25, 2024
1 parent e01de9b commit 3fb4b42
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 9 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 6 additions & 9 deletions src/CSVArray.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,26 +51,23 @@ public static function toArray(string $csv, string $delimiter = ';', string $enc
}

/** @param array<int, array<string, CSVPrimitive>> $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;
Expand Down
21 changes: 21 additions & 0 deletions tests/CSVArrayTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,27 @@ public function testEscapesDelimiter(): void
);
}

public function testUnixLike(): void
{
self::assertSame(
<<<CSV
foo,bar
1,2
CSV,
CSVArray::toCSV(
[
[
'foo' => 1,
'bar' => 2,
],
],
',',
"\n"
)
);
}

public function testPrimitives(): void
{
self::assertSame(
Expand Down

0 comments on commit 3fb4b42

Please sign in to comment.