JsonRequestModifier   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 3
dl 0
loc 54
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A modify() 0 14 4
A supports() 0 12 4
1
<?php
2
3
declare (strict_types=1);
4
5
namespace Oxidmod\RestBundle\Request\Modifier;
6
7
use Symfony\Component\HttpFoundation\Request;
8
9
/**
10
 * Decode json-request body
11
 */
12
class JsonRequestModifier implements RequestModifierInterface
13
{
14
    /**
15
     * @var array
16
     */
17
    private $supportedTypes;
18
19
    /**
20
     * @param array $supportedTypes
21
     */
22
    public function __construct(
23
        array $supportedTypes = [
24
            'json',
25
            'application/vnd.api+json',
26
        ]
27
    ) {
28
        $this->supportedTypes = $supportedTypes;
29
    }
30
31
    /**
32
     * {@inheritdoc}
33
     */
34
    public function modify(Request $request)
35
    {
36
        if (!$this->supports($request)) {
37
            return;
38
        }
39
40
        $decodedRequestBody = json_decode($request->getContent(), true);
41
42
        if (!is_array($decodedRequestBody) || json_last_error() !== JSON_ERROR_NONE) {
43
            return;
44
        }
45
46
        $request->request->replace($decodedRequestBody);
47
    }
48
49
    /**
50
     * @param Request $request
51
     * @return bool
52
     */
53
    private function supports(Request $request): bool
54
    {
55
        $contentType = $request->headers->get('Content-Type');
56
57
        foreach ($this->supportedTypes as $supportedType) {
58
            if ($supportedType === $contentType || $supportedType === $request->getContentType()) {
59
                return true;
60
            }
61
        }
62
63
        return false;
64
    }
65
}
66