|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Alchemy\RestBundle\EventListener; |
|
4
|
|
|
|
|
5
|
|
|
use Alchemy\Rest\Request\ContentTypeMatcher; |
|
6
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
|
7
|
|
|
use Symfony\Component\HttpFoundation\Request; |
|
8
|
|
|
use Symfony\Component\HttpKernel\Event\GetResponseEvent; |
|
9
|
|
|
use Symfony\Component\HttpKernel\KernelEvents; |
|
10
|
|
|
|
|
11
|
|
|
class DecodeJsonBodyRequestListener implements EventSubscriberInterface |
|
12
|
|
|
{ |
|
13
|
|
|
/** |
|
14
|
|
|
* @var ContentTypeMatcher |
|
15
|
|
|
*/ |
|
16
|
|
|
private $contentTypeMatcher; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* @var string[] |
|
20
|
|
|
*/ |
|
21
|
|
|
private $contentTypes; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* @param ContentTypeMatcher $contentTypeMatcher |
|
25
|
|
|
* @param null|string[] $contentTypes |
|
26
|
|
|
*/ |
|
27
|
8 |
|
public function __construct(ContentTypeMatcher $contentTypeMatcher, array $contentTypes = null) |
|
28
|
|
|
{ |
|
29
|
8 |
|
$this->contentTypeMatcher = $contentTypeMatcher; |
|
30
|
8 |
|
$this->contentTypes = $contentTypes ?: array('application/json'); |
|
31
|
8 |
|
} |
|
32
|
|
|
|
|
33
|
8 |
|
public function onKernelRequest(GetResponseEvent $event) |
|
34
|
|
|
{ |
|
35
|
8 |
|
$request = $event->getRequest(); |
|
36
|
8 |
|
$restAttributes = $request->attributes->get('_rest', []); |
|
37
|
|
|
|
|
38
|
8 |
|
if (! isset($restAttributes['decode_request']) || ! $restAttributes['decode_request']) { |
|
39
|
2 |
|
return; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
6 |
|
$this->decodeBody($request); |
|
43
|
6 |
|
} |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* @param Request $request |
|
47
|
|
|
*/ |
|
48
|
6 |
|
public function decodeBody(Request $request) |
|
49
|
|
|
{ |
|
50
|
6 |
|
$acceptHeader = $request->headers->get('Content-Type', '*/*'); |
|
51
|
|
|
|
|
52
|
6 |
|
if (!$this->contentTypeMatcher->matches($acceptHeader, $this->contentTypes)) { |
|
|
|
|
|
|
53
|
2 |
|
return; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
4 |
|
$jsonBody = $request->getContent(false); |
|
57
|
4 |
|
$decodedBody = json_decode($jsonBody, true); |
|
58
|
|
|
|
|
59
|
4 |
|
if (! is_array($decodedBody)) { |
|
60
|
2 |
|
$decodedBody = array(); |
|
61
|
2 |
|
} |
|
62
|
|
|
|
|
63
|
4 |
|
$request->request->replace($decodedBody); |
|
64
|
4 |
|
} |
|
65
|
|
|
|
|
66
|
2 |
|
public static function getSubscribedEvents() |
|
67
|
|
|
{ |
|
68
|
2 |
|
return array(KernelEvents::REQUEST => array('onKernelRequest', -2048)); |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|
If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:
If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.