Skip to content
This repository was archived by the owner on Jul 4, 2020. It is now read-only.

Commit cff9880

Browse files
committed
Add basic csv output
1 parent 5d6cf5f commit cff9880

File tree

3 files changed

+56
-1
lines changed

3 files changed

+56
-1
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<?php namespace SoapBox\Formatter;
2+
3+
use Illuminate\Support\Arr;
4+
5+
class ArrayHelpers {
6+
7+
public static function isAssociative($array) {
8+
return array_keys($array) !== range(0, count($array) - 1);
9+
}
10+
11+
public static function dotKeys(array $data) {
12+
return array_keys(Arr::dot($data));
13+
}
14+
15+
public static function dot(array $data) {
16+
return Arr::dot($data);
17+
}
18+
19+
}

src/SoapBox/Formatter/Parsers/Parser.php

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
use Spyc;
44
use Str;
5+
use SoapBox\Formatter\ArrayHelpers;
56

67
/**
78
* Parser Interface
@@ -111,9 +112,39 @@ public function toXml() {
111112
return $this->xmlify($this->toArray());
112113
}
113114

115+
private function csvify($data) {
116+
$results = [];
117+
foreach ($data as $row) {
118+
$results[] = array_values(ArrayHelpers::dot($row));
119+
}
120+
return $results;
121+
}
122+
114123
/**
115124
* Return a csv representation of the data stored in the parser
116125
*
117-
* @return string An xml string representing the encapsulated data
126+
* @return string An csv string representing the encapsulated data
118127
*/
128+
public function toCsv() {
129+
$data = $this->toArray();
130+
131+
if (ArrayHelpers::isAssociative($data) || !is_array($data[0])) {
132+
$data = [$data];
133+
}
134+
135+
$result = [];
136+
137+
$result[] = ArrayHelpers::dotKeys($data[0]);
138+
139+
foreach ($data as $row) {
140+
$result[] = array_values(ArrayHelpers::dot($row));
141+
}
142+
143+
$output = '';
144+
foreach ($result as $row) {
145+
$output .= implode(',', $row) . "\r\n";
146+
}
147+
148+
return $output;
149+
}
119150
}

tests/unit/Parsers/ArrayParserTest.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,4 +49,9 @@ public function testtoJsonReturnsJsonRepresentationOfNamedArray() {
4949
$parser = new ArrayParser(['foo' => 'bar']);
5050
$this->assertEquals($expected, $parser->toJson());
5151
}
52+
53+
public function testFunTimes() {
54+
$parser = new ArrayParser([[0,1,2], [2,3,4]]);
55+
var_dump($parser->toCsv());
56+
}
5257
}

0 commit comments

Comments
 (0)