Skip to content

Commit

Permalink
Add CsvReader::fetch. Add CsvReader docs to readme.
Browse files Browse the repository at this point in the history
  • Loading branch information
mermshaus committed Sep 7, 2016
1 parent 390b278 commit 4f4cc2e
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 0 deletions.
55 changes: 55 additions & 0 deletions README.md
Expand Up @@ -29,6 +29,61 @@ The following PHP versions are supported:
- HHVM


## Documentation

### Usage

#### CsvReader

~~~ php
use Kaloa\Filesystem\CsvReader;

// General usage. Read all CSV rows from a stream into a numeric array.

$stream = fopen(__DIR__ . '/file.csv');
$csvReader = new CsvReader($stream);
$data = $csvReader->fetchAll();
fclose($stream);

// Read all CSV rows from a stream into an associative array.
// The first row from the input will be used as keys.

$data = $csvReader->fetchAllAssoc();

// If the file doesn't contain a row with keys, keys can be provided
// manually.

$data = $csvReader->fetchAllAssoc(array('id', 'title', 'date_added'));

// There's also a streaming mode available.

while ($row = $csvReader->fetch()) {
// ...
}

// Streaming works with associative arrays, too.

while ($row = $csvReader->fetchAssoc()) {
// ...
}

// Respectively:

while ($row = $csvReader->fetchAssoc(array('id', 'title', 'date_added'))) {
// ...
}

// The reader automatically converts all input data to UTF-8. Differing input
// encodings may be defined in the constructor.

$csvReader = new CsvReader($iso88591stream, 'ISO-8859-1');

// The same goes for non-standard delimiter, enclosure and escape characters.

$csvReader = new CsvReader($stream, 'UTF-8', ':', '|', '%');
~~~


## Testing

(Tools are not included in this package.)
Expand Down
17 changes: 17 additions & 0 deletions src/CsvReader.php
Expand Up @@ -121,6 +121,23 @@ public function fetchAllAssoc(array $keys = array())
return $data;
}

/**
* @return array|bool
*/
public function fetch()
{
$row = $this->getNextRow();

if (false === $row) {
// EOF
return false;
}

$row = $this->negotiateEncoding($row);

return $row;
}

/**
* @param array $keys
* @return array|bool
Expand Down
19 changes: 19 additions & 0 deletions tests/Kaloa/Tests/Filesystem/CsvReaderTest.php
Expand Up @@ -113,6 +113,25 @@ public function testCanReadInStreamingMode()
$expected[] = array('Col a' => 'value 2a', 'Col b' => 'value 2b');

$this->assertSame($expected, $data);

// Test non-associative fetch method

$stream = fopen(__DIR__ . '/csv-files/custom-delimiters.csv', 'rb');
$reader = new CsvReader($stream, 'UTF-8', ':', '|');
$data = array();

while ($row = $reader->fetch()) {
$data[] = $row;
}

fclose($stream);

$expected = array();
$expected[] = array('Col a', 'Col b');
$expected[] = array('value 1a', 'value 1b');
$expected[] = array('value 2a', 'value 2b');

$this->assertSame($expected, $data);
}

/**
Expand Down

0 comments on commit 4f4cc2e

Please sign in to comment.