Skip to content

Commit

Permalink
Merge pull request #6 from nyamsprod/dev
Browse files Browse the repository at this point in the history
Adding tones of goodies to Reader
  • Loading branch information
nyamsprod committed Jan 28, 2014
2 parents bb3d71e + 020a790 commit 188bcc5
Show file tree
Hide file tree
Showing 11 changed files with 539 additions and 326 deletions.
52 changes: 32 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,11 +117,11 @@ $csv->setFlags(SplFileObject::READ_AHEAD|SplFileObject::SKIP_EMPTY);
//or

$csv = new Reader(
new SpliFileObject('/path/to/your/csv/file.csv'),
',',
'"',
'\\',
SplFileObject::READ_AHEAD|SplFileObject::SKIP_EMPTY
new SpliFileObject('/path/to/your/csv/file.csv'),
',',
'"',
'\\',
SplFileObject::READ_AHEAD|SplFileObject::SKIP_EMPTY
);

```
Expand All @@ -145,6 +145,14 @@ $row = $csv[5]; //accessing the 6th row;
```
**The `Bakame\Csv\Reader` can not modify the CSV content so if you try to set/delete/update a row you'll get a `RuntimeException` exception!**

The `Bakame\Csv\Reader` also implements the `IteratorAggregate` interface so you can easily iterate over your csv as follow:

```php
foreach ($csv as $row) {
//do something meaningfull here!!
}
```

Extracting data is also made easy using the following methods:

#### fetchAll
Expand Down Expand Up @@ -194,14 +202,18 @@ $data = $csv->fetchCol(2);

```

**The methods listed above (`fetchAll`, `fetchAssoc`, `fetchCol`) can all take a optional `callable` argument to further manipulate each row before being returned.**
The methods listed above (`fetchAll`, `fetchAssoc`, `fetchCol`) can all take a optional `callable` argument to further manipulate each row before being returned.
This callable function can take three parameters at most:
* the current inner iterator item
* the current inner iterator key
* and current inner iterator

### Filtering the data

In order to filter the CSV data you can modify the `fetch*` methods output by specifying filtering options using the following methods:

* the `setFilter`method specifies an optional `callable` function to filter the CSV data. This function takes three parameters at most (see [CallbackFilterIterator][] for more informations)
* the `setSortBy`method specifies an optional `callable` function to sort the CSV data. The function takes two parameters which will be filled by pairs of rows.
* the `setSortBy`method specifies an optional `callable` function to sort the CSV data. The function takes two parameters which will be filled by pairs of rows. **Beware when using this filter that you will be using `iterator_to_array` which could lead to performance penalty if you have a heavy CSV file to sort**
* the `setOffset` method specifies an optional offset for the return results.
* the `setLimit` method specifies an optional maximum rows count for the return results.

Expand All @@ -212,21 +224,21 @@ Here's an example:
```php
function filterByEmail($row)
{
return filer_var($row[2], FILTER_VALIDATE_EMAIL);
return filer_var($row[2], FILTER_VALIDATE_EMAIL);
}

function sortByLastName($rowA, $rowB)
{
return strcmp($rowB[1], $rowA[1]);
return strcmp($rowB[1], $rowA[1]);
}

$data = $csv
->setOffset(3)
->setLimit(2)
->setFilter('filterByEmail')
->setSortBy('sortByLastName')
->fetchAssoc(['firstname', 'lastname', 'email'], function ($value) {
return array_map('strtoupper', $value);
->fetchAssoc(['firstname', 'lastname', 'email'], function ($value) {
return array_map('strtoupper', $value);
});
// data length will be equals or lesser that 2 starting from the row index 3.
// will return something like this :
Expand All @@ -239,36 +251,36 @@ $data = $csv
```
**Of note:**

* After `fetch*` method call, the `offset`, `limit` properties as well as the filtering `callable` functions are cleared.
* After a `fetch*` method call, the `offset`, `limit` properties as well as all the `callable` functions are cleared.
* The methods can be call in any sort of order before any `fetch*` method call.

### Manual Filtering

If you want to output differently you data you can use the `query` method. It works like the `fetch*` method but does not take any callable arguments and returns an `Iterator`.
If you want to output differently you data you can use the `query` method. It works like the `fetch*` method but returns an [Iterator][] that you may manipulate as you wish.

[Iterator]: http://php.net/manual/en/class.iterator.php

```php
function filterByEmail($row)
{
return filer_var($row[2], FILTER_VALIDATE_EMAIL);
return filer_var($row[2], FILTER_VALIDATE_EMAIL);
}

function sortByLastName($rowA, $rowB)
{
return strcmp($rowB[1], $rowA[1]);
return strcmp($rowB[1], $rowA[1]);
}

$iterator = $csv
->setFilter('filterByEmail')
->setSortBy('sortByLastName')
->setOffset(3)
->setLimit(2)
->query();
->query(function ($value) {
return array_map('strtoupper', $value);
});
```

The return `$iterator` is a [Iterator][] that you may manipulate as you wish.

[Iterator]: http://php.net/manual/en/class.iterator.php

Testing
-------

Expand Down
32 changes: 17 additions & 15 deletions src/Bakame/Csv/Codec.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
* Bakame.csv - A lightweight CSV Coder/Decoder library
*
* @author Ignace Nyamagana Butera <[email protected]>
* @copyright 2013 Ignace Nyamagana Butera
* @copyright 2014 Ignace Nyamagana Butera
* @link https://github.com/nyamsprod/Bakame.csv
* @license http://opensource.org/licenses/MIT
* @version 3.2.0
* @version 3.3.0
* @package Bakame.csv
*
* MIT LICENSE
Expand Down Expand Up @@ -34,9 +34,9 @@

use SplFileInfo;
use SplFileObject;
use SplTempFileObject;
use Traversable;
use InvalidArgumentException;
use Bakame\Csv\Traits\CsvControls;

/**
* A simple Coder/Decoder to ease CSV management in PHP 5.4+
Expand All @@ -47,7 +47,7 @@
*/
class Codec
{
use CsvControlsTrait;
use CsvControls;

/**
* The constructor
Expand All @@ -69,22 +69,25 @@ public function __construct($delimiter = ',', $enclosure = '"', $escape = "\\",
*
* @param string $str the csv content string
*
* @return \SplTempFileObject
* @return \Bakame\Csv\Reader
*/
public function loadString($str)
{
$file = new SplTempFileObject();
$file->fwrite($str);

return new Reader($file, $this->delimiter, $this->enclosure, $this->escape, $this->flags);
return Reader::createFromString(
$str,
$this->delimiter,
$this->enclosure,
$this->escape,
$this->flags
);
}

/**
* Load a CSV File
*
* @param string $str the file path
*
* @return \SplFileObject
* @return \Bakame\Csv\Reader
*/
public function loadFile($path, $mode = 'r')
{
Expand All @@ -104,15 +107,14 @@ public function loadFile($path, $mode = 'r')
* @param string|\SplFileInfo $path where to save the data (String Path or SplFileInfo Instance)
* @param string $mode specifies the type of access you require to the file
*
* @return \SplFileObject
* @return \Bakame\Csv\Reader
*/
public function save($data, $path, $mode = 'w')
{
$file = $this->create($path, $mode, ['r+', 'w', 'w+', 'x', 'x+', 'a', 'a+', 'c', 'c+']);
$data = $this->formatData($data);
array_walk($data, function ($row) use ($file) {
foreach ($this->formatData($data) as $row) {
$file->fputcsv($row);
});
}

return new Reader($file, $this->delimiter, $this->enclosure, $this->escape, $this->flags);
}
Expand Down Expand Up @@ -156,7 +158,7 @@ private function extractRowData($row)
}, $row);
}

return explode($this->delimiter, (string) $row);
return str_getcsv((string) $row, $this->delimiter, $this->enclosure, $this->escape);
}

/**
Expand Down
Loading

0 comments on commit 188bcc5

Please sign in to comment.