|
1
|
|
|
<?php |
|
2
|
|
|
namespace Shlinkio\Shlink\Rest\Middleware; |
|
3
|
|
|
|
|
4
|
|
|
use Psr\Http\Message\ResponseInterface as Response; |
|
5
|
|
|
use Psr\Http\Message\ServerRequestInterface as Request; |
|
6
|
|
|
use Zend\Stratigility\MiddlewareInterface; |
|
7
|
|
|
|
|
8
|
|
|
class BodyParserMiddleware implements MiddlewareInterface |
|
9
|
|
|
{ |
|
10
|
|
|
/** |
|
11
|
|
|
* Process an incoming request and/or response. |
|
12
|
|
|
* |
|
13
|
|
|
* Accepts a server-side request and a response instance, and does |
|
14
|
|
|
* something with them. |
|
15
|
|
|
* |
|
16
|
|
|
* If the response is not complete and/or further processing would not |
|
17
|
|
|
* interfere with the work done in the middleware, or if the middleware |
|
18
|
|
|
* wants to delegate to another process, it can use the `$out` callable |
|
19
|
|
|
* if present. |
|
20
|
|
|
* |
|
21
|
|
|
* If the middleware does not return a value, execution of the current |
|
22
|
|
|
* request is considered complete, and the response instance provided will |
|
23
|
|
|
* be considered the response to return. |
|
24
|
|
|
* |
|
25
|
|
|
* Alternately, the middleware may return a response instance. |
|
26
|
|
|
* |
|
27
|
|
|
* Often, middleware will `return $out();`, with the assumption that a |
|
28
|
|
|
* later middleware will return a response. |
|
29
|
|
|
* |
|
30
|
|
|
* @param Request $request |
|
31
|
|
|
* @param Response $response |
|
32
|
|
|
* @param null|callable $out |
|
33
|
|
|
* @return null|Response |
|
34
|
|
|
*/ |
|
35
|
|
|
public function __invoke(Request $request, Response $response, callable $out = null) |
|
36
|
|
|
{ |
|
37
|
|
|
$method = $request->getMethod(); |
|
38
|
|
|
if (! in_array($method, ['PUT', 'PATCH'])) { |
|
39
|
|
|
return $out($request, $response); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
$contentType = $request->getHeaderLine('Content-type'); |
|
43
|
|
|
$rawBody = (string) $request->getBody(); |
|
44
|
|
|
if (in_array($contentType, ['application/json', 'text/json', 'application/x-json'])) { |
|
45
|
|
|
return $out($request->withParsedBody(json_decode($rawBody, true)), $response); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
$parsedBody = []; |
|
49
|
|
|
parse_str($rawBody, $parsedBody); |
|
50
|
|
|
return $out($request->withParsedBody($parsedBody), $response); |
|
51
|
|
|
} |
|
52
|
|
|
} |
|
53
|
|
|
|