Passed
Pull Request — master (#120)
by Ralf
10:08
created

CsvHandler   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 20
dl 0
loc 40
rs 10
c 0
b 0
f 0
wmc 7
1
<?php
2
/**
3
 * Mime Type: text/csv
4
 * @author Raja Kapur <[email protected]>
5
 */
6
7
namespace Httpful\Handlers;
8
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
    }
50
}
51