-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
BodyParserMiddleware.php
208 lines (191 loc) · 5.8 KB
/
BodyParserMiddleware.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 3.6.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\Http\Middleware;
use Cake\Http\Exception\BadRequestException;
use Cake\Utility\Exception\XmlException;
use Cake\Utility\Xml;
use Closure;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Parse encoded request body data.
*
* Enables JSON and XML request payloads to be parsed into the request's
* Provides CSRF protection & validation.
*
* You can also add your own request body parsers using the `addParser()` method.
*/
class BodyParserMiddleware implements MiddlewareInterface
{
/**
* Registered Parsers
*
* @var \Closure[]
*/
protected $parsers = [];
/**
* The HTTP methods to parse data on.
*
* @var string[]
*/
protected $methods = ['PUT', 'POST', 'PATCH', 'DELETE'];
/**
* Constructor
*
* ### Options
*
* - `json` Set to false to disable json body parsing.
* - `xml` Set to true to enable XML parsing. Defaults to false, as XML
* handling requires more care than JSON does.
* - `methods` The HTTP methods to parse on. Defaults to PUT, POST, PATCH DELETE.
*
* @param array $options The options to use. See above.
*/
public function __construct(array $options = [])
{
$options += ['json' => true, 'xml' => false, 'methods' => null];
if ($options['json']) {
$this->addParser(
['application/json', 'text/json'],
Closure::fromCallable([$this, 'decodeJson'])
);
}
if ($options['xml']) {
$this->addParser(
['application/xml', 'text/xml'],
Closure::fromCallable([$this, 'decodeXml'])
);
}
if ($options['methods']) {
$this->setMethods($options['methods']);
}
}
/**
* Set the HTTP methods to parse request bodies on.
*
* @param string[] $methods The methods to parse data on.
* @return $this
*/
public function setMethods(array $methods)
{
$this->methods = $methods;
return $this;
}
/**
* Get the HTTP methods to parse request bodies on.
*
* @return string[]
*/
public function getMethods(): array
{
return $this->methods;
}
/**
* Add a parser.
*
* Map a set of content-type header values to be parsed by the $parser.
*
* ### Example
*
* An naive CSV request body parser could be built like so:
*
* ```
* $parser->addParser(['text/csv'], function ($body) {
* return str_getcsv($body);
* });
* ```
*
* @param string[] $types An array of content-type header values to match. eg. application/json
* @param \Closure $parser The parser function. Must return an array of data to be inserted
* into the request.
* @return $this
*/
public function addParser(array $types, Closure $parser)
{
foreach ($types as $type) {
$type = strtolower($type);
$this->parsers[$type] = $parser;
}
return $this;
}
/**
* Get the current parsers
*
* @return \Closure[]
*/
public function getParsers(): array
{
return $this->parsers;
}
/**
* Apply the middleware.
*
* Will modify the request adding a parsed body if the content-type is known.
*
* @param \Psr\Http\Message\ServerRequestInterface $request The request.
* @param \Psr\Http\Server\RequestHandlerInterface $handler The request handler.
* @return \Psr\Http\Message\ResponseInterface A response.
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
if (!in_array($request->getMethod(), $this->methods, true)) {
return $handler->handle($request);
}
[$type] = explode(';', $request->getHeaderLine('Content-Type'));
$type = strtolower($type);
if (!isset($this->parsers[$type])) {
return $handler->handle($request);
}
$parser = $this->parsers[$type];
$result = $parser($request->getBody()->getContents());
if (!is_array($result)) {
throw new BadRequestException();
}
$request = $request->withParsedBody($result);
return $handler->handle($request);
}
/**
* Decode JSON into an array.
*
* @param string $body The request body to decode
* @return mixed
*/
protected function decodeJson(string $body)
{
return json_decode($body, true);
}
/**
* Decode XML into an array.
*
* @param string $body The request body to decode
* @return array
*/
protected function decodeXml(string $body): array
{
try {
$xml = Xml::build($body, ['return' => 'domdocument', 'readFile' => false]);
// We might not get child nodes if there are nested inline entities.
if ((int)$xml->childNodes->length > 0) {
return Xml::toArray($xml);
}
return [];
} catch (XmlException $e) {
return [];
}
}
}