Csv::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 3
1
<?php
2
3
/*
4
 * body-parser (https://github.com/juliangut/body-parser).
5
 * PSR7 body parser middleware.
6
 *
7
 * @license BSD-3-Clause
8
 * @link https://github.com/juliangut/body-parser
9
 * @author Julián Gutiérrez <[email protected]>
10
 */
11
12
namespace Jgut\BodyParser\Decoder;
13
14
use League\Csv\Reader;
15
16
/**
17
 * CSV request decoder.
18
 */
19
class Csv implements Decoder
20
{
21
    use MimeTypeTrait;
22
23
    /**
24
     * Fields delimiter character.
25
     *
26
     * @var string
27
     */
28
    protected $delimiter;
29
30
    /**
31
     * Field enclosure character.
32
     *
33
     * @var string
34
     */
35
    protected $enclosure;
36
37
    /**
38
     * Escape character.
39
     *
40
     * @var string
41
     */
42
    protected $escape;
43
44
    /**
45
     * CSV request decoder constructor.
46
     *
47
     * @param string $delimiter
48
     * @param string $enclosure
49
     * @param string $escape
50
     */
51
    public function __construct($delimiter = ',', $enclosure = '"', $escape = '\\')
52
    {
53
        $this->delimiter = (string) $delimiter;
54
        $this->enclosure = (string) $enclosure;
55
        $this->escape = (string) $escape;
56
57
        $this->addMimeType('text/csv');
58
        $this->addMimeType('application/csv');
59
    }
60
61
    /**
62
     * {@inheritdoc}
63
     *
64
     * @throws \InvalidArgumentException
65
     * @throws \RuntimeException
66
     */
67
    public function decode($rawBody)
68
    {
69
        if (trim($rawBody) === '') {
70
            return;
71
        }
72
73
        $parsedBody = Reader::createFromString($rawBody)
74
            ->setDelimiter($this->delimiter)
75
            ->setEnclosure($this->enclosure)
76
            ->setEscape($this->escape)
77
            ->fetchAll();
78
79
        if (empty($parsedBody)) {
80
            throw new \RuntimeException('CSV request body parsing error: "verify CSV format"');
81
        }
82
83
        return $parsedBody;
84
    }
85
}
86