From 47bb35e2e9874dd58cbcc29f06f7554f0c6fceaf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Vanvelthem?= Date: Wed, 13 Mar 2019 14:02:46 +0100 Subject: [PATCH] Preliminary tests for CsvFormatter::encode + minor fix for empty data (#2405) --- .../Framework/File/Formatter/CsvFormatter.php | 3 ++ .../File/Formatter/CsvFormatterTest.php | 47 +++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 tests/unit/Grav/Framework/File/Formatter/CsvFormatterTest.php diff --git a/system/src/Grav/Framework/File/Formatter/CsvFormatter.php b/system/src/Grav/Framework/File/Formatter/CsvFormatter.php index f3b76272f..4f4b6bf0d 100644 --- a/system/src/Grav/Framework/File/Formatter/CsvFormatter.php +++ b/system/src/Grav/Framework/File/Formatter/CsvFormatter.php @@ -43,6 +43,9 @@ class CsvFormatter extends AbstractFormatter */ public function encode($data, $delimiter = null): string { + if (count($data) === 0) { + return ''; + } $delimiter = $delimiter ?? $this->getDelimiter(); $header = array_keys(reset($data)); diff --git a/tests/unit/Grav/Framework/File/Formatter/CsvFormatterTest.php b/tests/unit/Grav/Framework/File/Formatter/CsvFormatterTest.php new file mode 100644 index 000000000..70a8c9e41 --- /dev/null +++ b/tests/unit/Grav/Framework/File/Formatter/CsvFormatterTest.php @@ -0,0 +1,47 @@ + 1, 'col2' => 2, 'col3' => 3], + ['col1' => 'aaa', 'col2' => 'bbb', 'col3' => 'ccc'], + ]; + + $encoded = (new CsvFormatter())->encode($data); + + $lines = array_filter(explode(PHP_EOL, $encoded)); + + self::assertCount(3, $lines); + self::assertEquals('col1,col2,col3', $lines[0]); + + } + + /** + * TBD - If indexes are all numeric, what's the purpose + * of displaying header + */ + public function testEncodeWithIndexColumns() + { + $data = [ + [0 => 1, 1 => 2, 2 => 3], + ]; + + $encoded = (new CsvFormatter())->encode($data); + + $lines = array_filter(explode(PHP_EOL, $encoded)); + + self::assertCount(2, $lines); + self::assertEquals('0,1,2', $lines[0]); + } + + public function testEncodeEmptyData() + { + $encoded = (new CsvFormatter())->encode([]); + self::assertEquals('', $encoded); + } + +}