Skip to content

Commit

Permalink
fix readString for native csv adapter
Browse files Browse the repository at this point in the history
  • Loading branch information
lekoala committed Apr 22, 2024
1 parent ff39376 commit 990a7c3
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 26 deletions.
31 changes: 5 additions & 26 deletions src/Csv/Native.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Generator;
use LeKoala\SpreadCompat\SpreadCompat;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

This comment has been minimized.

Copy link
@nyamsprod

nyamsprod Apr 22, 2024

Contributor

I presume your editor tried to be smarter than it is 😄

use RuntimeException;

/**
Expand All @@ -22,32 +23,10 @@ public function readString(
string $contents,
...$opts
): Generator {
$this->configure(...$opts);
$this->configureSeparator($contents);

// check for bom
if (strncmp($contents, self::BOM, 3) === 0) {
$contents = substr($contents, 3);
}
$separator = $this->getSeparator();

// parse rows and take into account enclosure and escaped parts
// we use $this->eol as a separator as a mean to split lines
/** @var array<string> $data */
$data = str_getcsv($contents, $this->eol, $this->enclosure, $this->escape);

$headers = null;
foreach ($data as $line) {
$row = str_getcsv($line, $separator, $this->enclosure, $this->escape);
if ($this->assoc) {
if ($headers === null) {
$headers = $row;
continue;
}
$row = array_combine($headers, $row);
}
yield $row;
}
$temp = SpreadCompat::getMaxMemTempStream();
fwrite($temp, $contents);
rewind($temp);
return $this->readStream($temp, ...$opts);
}

/**
Expand Down
17 changes: 17 additions & 0 deletions tests/SpreadCompatCsvTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -314,4 +314,21 @@ public function testSpreadsheetCanWriteCsv()
$expected = file_get_contents(__DIR__ . '/data/separator.csv');
$this->assertEquals($expected, $string);
}

public function testLineSplitCsvNative()
{
$document = <<<CSV
Data 2-1,Data 2-2,"Data 2-3
is on multiple lines
you see"
CSV;

$generator = SpreadCompat::readString($document, 'csv', adapter: SpreadCompat::LEAGUE);
$data = iterator_to_array($generator);
$this->assertCount(1, $data, "Should be one line");

$generator = SpreadCompat::readString($document, 'csv', adapter: SpreadCompat::NATIVE);
$data = iterator_to_array($generator);
$this->assertCount(1, $data, "Should be one line");
}
}

0 comments on commit 990a7c3

Please sign in to comment.