BodyParser::csv()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 17
rs 9.4285
c 1
b 0
f 0
cc 3
eloc 9
nc 4
nop 1
1
<?php
2
3
namespace Psr7Middlewares\Transformers;
4
5
use Psr\Http\Message\StreamInterface;
6
use DomainException;
7
8
/**
9
 * Generic resolver to parse the body content.
10
 */
11
class BodyParser extends Resolver
12
{
13
    /** @var mixed[] */
14
    private $options = [
15
        // When true, returned objects will be converted into associative arrays.
16
        'forceArray' => true,
17
    ];
18
19
    /**
20
     * BodyParser constructor.
21
     *
22
     * @param mixed[] $options
23
     */
24
    public function __construct(array $options = [])
25
    {
26
        $this->add('application/json', [$this, 'json']);
27
        $this->add('application/x-www-form-urlencoded', [$this, 'urlencode']);
28
        $this->add('text/csv', [$this, 'csv']);
29
        $this->options = array_merge($this->options, $options);
30
    }
31
32
    /**
33
     * @param string $id
34
     *
35
     * @return callable|null
36
     */
37
    public function resolve($id)
38
    {
39
        foreach ($this->transformers as $contentType => $transformer) {
40
            if (stripos($id, $contentType) === 0) {
41
                return $transformer;
42
            }
43
        }
44
    }
45
46
    /**
47
     * JSON parser.
48
     *
49
     * @param StreamInterface $body
50
     *
51
     * @return array|object Returns an array when $assoc is true, and an object when $assoc is false
52
     */
53
    public function json(StreamInterface $body)
54
    {
55
        $assoc = (bool) $this->options['forceArray'];
56
57
        $string = (string) $body;
58
59
        if ($string === '') {
60
            return [];
61
        }
62
63
        $data = json_decode($string, $assoc);
64
65
        if (json_last_error() !== JSON_ERROR_NONE) {
66
            throw new DomainException(json_last_error_msg());
67
        }
68
69
        return $data ?: [];
70
    }
71
72
    /**
73
     * Parses url-encoded strings.
74
     *
75
     * @param StreamInterface $body
76
     *
77
     * @return array
78
     */
79
    public function urlencode(StreamInterface $body)
80
    {
81
        parse_str((string) $body, $data);
82
83
        return $data ?: [];
84
    }
85
86
    /**
87
     * Parses csv strings.
88
     *
89
     * @param StreamInterface $body
90
     *
91
     * @return array
92
     */
93
    public function csv(StreamInterface $body)
94
    {
95
        if ($body->isSeekable()) {
96
            $body->rewind();
97
        }
98
99
        $stream = $body->detach();
100
        $data = [];
101
102
        while (($row = fgetcsv($stream)) !== false) {
103
            $data[] = $row;
104
        }
105
106
        fclose($stream);
107
108
        return $data;
109
    }
110
}
111