Test Failed
Push — master ( b3e488...48cf76 )
by Dominik
02:02
created

UrlEncodedTransformer   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A transform() 0 6 1
B buildQuery() 0 20 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chubbyphp\Serialization\Transformer;
6
7
final class UrlEncodedTransformer implements TransformerInterface
8
{
9
    /**
10
     * @var string
11
     */
12
    private $numericPrefix;
13
14
    /**
15
     * @var string
16
     */
17
    private $argSeperator;
18
19
    /**
20
     * @param string $numericPrefix
21
     * @param string $argSeperator
22
     */
23
    public function __construct(
24
        string $numericPrefix = '',
25
        string $argSeperator = '&'
26
    ) {
27
        $this->numericPrefix = $numericPrefix;
28
        $this->argSeperator = $argSeperator;
29 1
    }
30
31
    /**
32
     * @param array $data
33
     *
34 1
     * @return string
35 1
     */
36 1
    public function transform(array $data): string
37 1
    {
38
        $query = $this->buildQuery($data);
39
40
        return $query;
41
    }
42
43
    /**
44 1
     * @param array  $data
45
     * @param string $path
46 1
     *
47
     * @return string
48
     */
49
    private function buildQuery(array $data, string $path = ''): string
50
    {
51
        $query = '';
52
        foreach ($data as $key => $value) {
53
            $subPathKey = !is_int($key) ? $key : $this->numericPrefix.$key;
54
            $subPath = '' !== $path ? $path.'['.$subPathKey.']' : $subPathKey;
55
56
            if (is_array($value)) {
57
                $query .= $this->buildQuery($value, $subPath);
58
            } else {
59
                $query .= $subPath.'='.urlencode((string) $value);
60
            }
61
62
            $query .= $this->argSeperator;
63
        }
64
65
        $query = substr($query, 0, -strlen($this->argSeperator));
66
67
        return $query;
68
    }
69
}
70