summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorIgnace Nyamagana Butera <nyamsprod@gmail.com>2014-01-10 13:42:57 +0100
committerIgnace Nyamagana Butera <nyamsprod@gmail.com>2014-01-10 13:42:57 +0100
commit0f5361ed7e3ac945f17df0d4c511f9bc5cce00e6 (patch)
tree15f1fcba92bfd379f50c150924c24783bcb9dac0
parentc3182d8498838c2e53002a68685ec301a9baa9f1 (diff)
downloadcsv-0f5361ed7e3ac945f17df0d4c511f9bc5cce00e6.zip
csv-0f5361ed7e3ac945f17df0d4c511f9bc5cce00e6.tar.gz
csv-0f5361ed7e3ac945f17df0d4c511f9bc5cce00e6.tar.bz2
Bug fix in the Reader class to allow fetchAssoc to combine array when the number of items does not match
-rw-r--r--src/Bakame/Csv/Reader.php27
-rw-r--r--test/Bakame/Csv/ReaderTest.php12
2 files changed, 36 insertions, 3 deletions
diff --git a/src/Bakame/Csv/Reader.php b/src/Bakame/Csv/Reader.php
index dc7f37b..cc31e78 100644
--- a/src/Bakame/Csv/Reader.php
+++ b/src/Bakame/Csv/Reader.php
@@ -6,7 +6,7 @@
* @copyright 2013 Ignace Nyamagana Butera
* @link https://github.com/nyamsprod/Bakame.csv
* @license http://opensource.org/licenses/MIT
-* @version 3.0.0
+* @version 3.0.1
* @package Bakame.csv
*
* MIT LICENSE
@@ -144,6 +144,27 @@ class Reader implements ReaderInterface
}
/**
+ * Intelligent Array Combine
+ *
+ * @param array $keys
+ * @param array $value
+ *
+ * @return array
+ */
+ private static function combineKeyValue(array $keys, array $value)
+ {
+ $nbKeys = count($keys);
+ $diff = $nbKeys - count($value);
+ if ($diff > 0) {
+ $value = array_merge($value, array_fill(0, $diff, null));
+ } elseif ($diff < 0) {
+ $value = array_slice($value, 0, $nbKeys);
+ }
+
+ return array_combine($keys, $value);
+ }
+
+ /**
* {@inheritdoc}
*/
public function fetchAssoc(array $keys, callable $callable = null)
@@ -153,13 +174,13 @@ class Reader implements ReaderInterface
$this->file->setCsvControl($this->delimiter, $this->enclosure, $this->escape);
if (is_null($callable)) {
foreach ($this->file as $row) {
- $res[] = array_combine($keys, $row);
+ $res[] = self::combineKeyValue($keys, $row);
}
return $res;
}
foreach ($this->file as $row) {
- $res[] = array_combine($keys, $callable($row));
+ $res[] = self::combineKeyValue($keys, $callable($row));
}
return $res;
diff --git a/test/Bakame/Csv/ReaderTest.php b/test/Bakame/Csv/ReaderTest.php
index b061b06..8ccd49f 100644
--- a/test/Bakame/Csv/ReaderTest.php
+++ b/test/Bakame/Csv/ReaderTest.php
@@ -57,6 +57,18 @@ class ReaderTest extends \PHPUnit_Framework_TestCase
foreach ($res as $index => $row) {
$this->assertSame($keys, array_keys($row));
}
+
+ $keys = ['firstname'];
+ $res = $this->reader->fetchAssoc($keys);
+ $this->assertSame([['firstname' => 'foo'], ['firstname' => 'foo']], $res);
+
+ $keys = ['firstname', 'lastname', 'email', 'age'];
+ $res = $this->reader->fetchAssoc($keys);
+ foreach ($res as $index => $row) {
+ $this->assertCount(4, array_values($row));
+ $this->assertNull($row['age']);
+ }
+
}
public function testFetchCol()