| Total Complexity | 7 |
| Total Lines | 40 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 1 | <?php |
||
| 9 | class CsvHandler extends MimeHandlerAdapter |
||
| 10 | { |
||
| 11 | /** |
||
| 12 | * @param string $body |
||
| 13 | * @return mixed |
||
| 14 | */ |
||
| 15 | public function parse($body) |
||
| 16 | { |
||
| 17 | if (empty($body)) |
||
| 18 | return null; |
||
| 19 | |||
| 20 | $parsed = array(); |
||
| 21 | $fp = fopen('data://text/plain;base64,' . base64_encode($body), 'r'); |
||
| 22 | while (($r = fgetcsv($fp)) !== FALSE) { |
||
| 23 | $parsed[] = $r; |
||
| 24 | } |
||
| 25 | |||
| 26 | if (empty($parsed)) |
||
| 27 | throw new \Exception("Unable to parse response as CSV"); |
||
| 28 | return $parsed; |
||
| 29 | } |
||
| 30 | |||
| 31 | /** |
||
| 32 | * @param mixed $payload |
||
| 33 | * @return string |
||
| 34 | */ |
||
| 35 | public function serialize($payload) |
||
| 36 | { |
||
| 37 | $fp = fopen('php://temp/maxmemory:'. (6*1024*1024), 'r+'); |
||
| 38 | $i = 0; |
||
| 39 | foreach ($payload as $fields) { |
||
| 40 | if($i++ == 0) { |
||
| 41 | fputcsv($fp, array_keys($fields)); |
||
| 42 | } |
||
| 43 | fputcsv($fp, $fields); |
||
| 44 | } |
||
| 45 | rewind($fp); |
||
| 46 | $data = stream_get_contents($fp); |
||
| 47 | fclose($fp); |
||
| 48 | return $data; |
||
| 49 | } |
||
| 51 |