Test Failed
Push — master ( 8a2b60...8e4848 )
by Dominik
03:00
created

UrlEncodedTypeEncoder   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 45
c 0
b 0
f 0
wmc 6
lcom 0
cbo 0
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getContentType() 0 4 1
A encode() 0 4 1
A buildQuery() 0 16 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chubbyphp\Serialization\Encoder;
6
7
use Chubbyphp\Serialization\SerializerRuntimeException;
8
9
final class UrlEncodedTypeEncoder implements TypeEncoderInterface
10
{
11
    /**
12
     * @return string
13
     */
14
    public function getContentType(): string
15
    {
16
        return 'application/x-www-form-urlencoded';
17
    }
18
19
    /**
20
     * @param array $data
21
     *
22
     * @return string
23
     *
24
     * @throws SerializerRuntimeException
25
     */
26
    public function encode(array $data): string
27
    {
28
        return $this->buildQuery($data);
29
    }
30
31
    /**
32
     * @param array  $data
33
     * @param string $path
34
     *
35
     * @return string
36
     */
37
    private function buildQuery(array $data, string $path = ''): string
38
    {
39
        $query = '';
40
        foreach ($data as $key => $value) {
41
            $subPath = '' !== $path ? $path.'['.$key.']' : $key;
42
            if (is_array($value)) {
43
                $query .= $this->buildQuery($value, $subPath);
44
            } else {
45
                $query .= $subPath.'='.urlencode((string) $value);
46
            }
47
            $query .= '&';
48
        }
49
        $query = substr($query, 0, -strlen('&'));
50
51
        return $query;
52
    }
53
}
54