Skip to content

Commit

Permalink
work around while waiting for PHP fix for #279
Browse files Browse the repository at this point in the history
  • Loading branch information
nyamsprod committed Feb 5, 2018
1 parent 7645898 commit 92f7d62
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 3 deletions.
17 changes: 15 additions & 2 deletions src/Reader.php
Original file line number Diff line number Diff line change
Expand Up @@ -114,10 +114,23 @@ public function getHeader(): array
*/
protected function setHeader(int $offset): array
{
$header = [];
$this->document->setFlags(SplFileObject::READ_CSV | SplFileObject::READ_AHEAD | SplFileObject::SKIP_EMPTY);
$this->document->setCsvControl($this->delimiter, $this->enclosure, $this->escape);
$this->document->seek($offset);
if (empty($header = $this->document->current())) {
if ($this->document instanceof Stream || PHP_VERSION_ID < 70200) {
$this->document->seek($offset);
$header = $this->document->current();
} else {
$stream->rewind();
while ($offset !== $stream->key() && $stream->valid()) {
$stream->current();
$stream->next();
}

$header = $stream->current();
}

if (empty($header)) {
throw new Exception(sprintf('The header record does not exist or is empty at offset: `%s`', $offset));
}

Expand Down
27 changes: 26 additions & 1 deletion tests/ReaderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -291,12 +291,37 @@ public function appliedFlagsProvider()
/**
* @covers ::setHeader
*/
public function testGetHeaderThrowsException()
public function testGetHeaderThrowsExceptionWithNegativeOffset()
{
$this->expectException(Exception::class);
$this->csv->setHeaderOffset(-3)->getRecords();
}

/**
* @covers ::setHeader
*/
public function testGetHeaderThrowsExceptionWithSplFileObject()
{
$this->expectException(Exception::class);
$this->csv->setHeaderOffset(23)->getRecords();
}

/**
* @covers ::setHeader
*/
public function testGetHeaderThrowsExceptionWithStreamObject()
{
$this->expectException(Exception::class);

$tmp = fopen('php://temp', 'r+');
foreach ($this->expected as $row) {
fputcsv($tmp, $row);
}

$csv = Reader::createFromStream($tmp);
$csv->setHeaderOffset(23)->getRecords();
}

/**
* @covers ::setHeaderOffset
* @covers \League\Csv\is_nullable_int
Expand Down

0 comments on commit 92f7d62

Please sign in to comment.