Passed
Push — main ( 633b92...66245a )
by Dimitri
12:27
created

BodyParser::decodeJson()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 6
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 11
rs 10
1
<?php
2
3
/**
4
 * This file is part of Blitz PHP framework.
5
 *
6
 * (c) 2022 Dimitri Sitchet Tomkeu <[email protected]>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11
12
namespace BlitzPHP\Middlewares;
13
14
use BlitzPHP\Exceptions\HttpException;
15
use BlitzPHP\Formatter\Formatter;
16
use Closure;
17
use Psr\Http\Message\ResponseInterface;
18
use Psr\Http\Message\ServerRequestInterface;
19
use Psr\Http\Server\MiddlewareInterface;
20
use Psr\Http\Server\RequestHandlerInterface;
21
22
/**
23
 * BodyParser
24
 *
25
 * Parse encoded request body data.
26
 *
27
 * Enables JSON and XML request payloads to be parsed into the request's
28
 * Provides CSRF protection & validation.
29
 *
30
 * You can also add your own request body parsers usi *
31
 *
32
 * @credit		CakePHP (Cake\Http\Middleware\BodyParserMiddleware - https://cakephp.org)
33
 */
34
class BodyParser implements MiddlewareInterface
35
{
36
    /**
37
     * Registered Parsers
38
     *
39
     * @var Closure[]
40
     */
41
    protected $parsers = [];
42
43
    /**
44
     * The HTTP methods to parse data on.
45
     *
46
     * @var string[]
47
     */
48
    protected $methods = ['PUT', 'POST', 'PATCH', 'DELETE'];
49
50
    /**
51
     * Constructor
52
     *
53
     * ### Options
54
     *
55
     * - `json` Set to false to disable JSON body parsing.
56
     * - `xml` Set to true to enable XML parsing. Defaults to false, as XML
57
     *   handling requires more care than JSON does.
58
     * - `methods` The HTTP methods to parse on. Defaults to PUT, POST, PATCH DELETE.
59
     *
60
     * @param array $options The options to use. See above.
61
     */
62
    public function __construct(array $options = [])
63
    {
64
        $options += ['json' => true, 'xml' => false, 'methods' => null];
65
        if ($options['json']) {
66
            $this->addParser(
67
                ['application/json', 'text/json'],
68
                Closure::fromCallable([$this, 'decodeJson'])
69
            );
70
        }
71
        if ($options['xml']) {
72
            $this->addParser(
73
                ['application/xml', 'text/xml'],
74
                Closure::fromCallable([$this, 'decodeXml'])
75
            );
76
        }
77
        if ($options['methods']) {
78
            $this->setMethods($options['methods']);
79
        }
80
    }
81
82
    /**
83
     * Set the HTTP methods to parse request bodies on.
84
     *
85
     * @param string[] $methods The methods to parse data on.
86
     */
87
    public function setMethods(array $methods): self
88
    {
89
        $this->methods = $methods;
90
91
        return $this;
92
    }
93
94
    /**
95
     * Get the HTTP methods to parse request bodies on.
96
     *
97
     * @return string[]
98
     */
99
    public function getMethods(): array
100
    {
101
        return $this->methods;
102
    }
103
104
    /**
105
     * Add a parser.
106
     *
107
     * Map a set of content-type header values to be parsed by the $parser.
108
     *
109
     * ### Example
110
     *
111
     * An naive CSV request body parser could be built like so:
112
     *
113
     * ```
114
     * $parser->addParser(['text/csv'], function ($body) {
115
     *   return str_getcsv($body);
116
     * });
117
     * ```
118
     *
119
     * @param string[] $types  An array of content-type header values to match. eg. application/json
120
     * @param Closure  $parser The parser function. Must return an array of data to be inserted
121
     *                         into the request.
122
     */
123
    public function addParser(array $types, Closure $parser): self
124
    {
125
        foreach ($types as $type) {
126
            $type                 = strtolower($type);
127
            $this->parsers[$type] = $parser;
128
        }
129
130
        return $this;
131
    }
132
133
    /**
134
     * Get the current parsers
135
     *
136
     * @return Closure[]
137
     */
138
    public function getParsers(): array
139
    {
140
        return $this->parsers;
141
    }
142
143
    /**
144
     * Apply the middleware.
145
     *
146
     * Will modify the request adding a parsed body if the content-type is known.
147
     *
148
     * @param ServerRequestInterface  $request The request.
149
     * @param RequestHandlerInterface $handler The request handler.
150
     *
151
     * @return ResponseInterface A response.
152
     */
153
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
154
    {
155
        if (! in_array($request->getMethod(), $this->methods, true)) {
156
            return $handler->handle($request);
157
        }
158
159
        [$type] = explode(';', $request->getHeaderLine('Content-Type'));
160
        $type   = strtolower($type);
161
        if (! isset($this->parsers[$type])) {
162
            return $handler->handle($request);
163
        }
164
165
        $parser = $this->parsers[$type];
166
        $result = $parser($request->getBody()->getContents());
167
        if (! is_array($result)) {
168
            throw HttpException::badRequest();
169
        }
170
        $request = $request->withParsedBody($result);
171
172
        return $handler->handle($request);
173
    }
174
175
    /**
176
     * Decode JSON into an array.
177
     *
178
     * @param string $body The request body to decode
179
     */
180
    protected function decodeJson(string $body): ?array
181
    {
182
        if ($body === '') {
183
            return [];
184
        }
185
        $decoded = json_decode($body, true);
186
        if (json_last_error() === JSON_ERROR_NONE) {
187
            return (array) $decoded;
188
        }
189
190
        return null;
191
    }
192
193
    /**
194
     * Decode XML into an array.
195
     *
196
     * @param string $body The request body to decode
197
     */
198
    protected function decodeXml(string $body): array
199
    {
200
        return Formatter::type('application/xml')->parse($body);
201
    }
202
}
203