JsonToFormDecoder   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
lcom 0
cbo 0
dl 0
loc 37
ccs 14
cts 14
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A xWwwFormEncodedLike() 0 18 5
A decode() 0 9 2
1
<?php
2
3
/*
4
 * This file is part of the FOSRestBundle package.
5
 *
6
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace FOS\RestBundle\Decoder;
13
14
/**
15
 * Decodes JSON data and make it compliant with application/x-www-form-encoded style.
16
 *
17
 * @author Kévin Dunglas <[email protected]>
18
 */
19
final class JsonToFormDecoder implements DecoderInterface
20
{
21
    /**
22
     * Makes data decoded from JSON application/x-www-form-encoded compliant.
23
     */
24 1
    private function xWwwFormEncodedLike(array &$data): void
25
    {
26 1
        foreach ($data as $key => &$value) {
27 1
            if (is_array($value)) {
28
                // Encode recursively
29 1
                $this->xWwwFormEncodedLike($value);
30 1
            } elseif (false === $value) {
31
                // Checkbox-like behavior removes false data but PATCH HTTP method with just checkboxes does not work
32
                // To fix this issue we prefer transform false data to null
33
                // See https://github.com/FriendsOfSymfony/FOSRestBundle/pull/883
34 1
                $value = null;
35 1
            } elseif (!is_string($value)) {
36
                // Convert everything to string
37
                // true values will be converted to '1', this is the default checkbox behavior
38 1
                $value = strval($value);
39
            }
40
        }
41 1
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46 2
    public function decode(string $data)
47
    {
48 2
        $decodedData = @json_decode($data, true);
49 2
        if (is_array($decodedData)) {
50 1
            $this->xWwwFormEncodedLike($decodedData);
51
        }
52
53 2
        return $decodedData;
54
    }
55
}
56