Completed
Push — master ( 48cf76...5a3c62 )
by Dominik
06:34 queued 01:19
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 18
cts 18
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 1
    public function __construct(
24
        string $numericPrefix = '',
25
        string $argSeperator = '&'
26
    ) {
27 1
        $this->numericPrefix = $numericPrefix;
28 1
        $this->argSeperator = $argSeperator;
29 1
    }
30
31
    /**
32
     * @param array $data
33
     *
34
     * @return string
35
     */
36 1
    public function transform(array $data): string
37
    {
38 1
        $query = $this->buildQuery($data);
39
40 1
        return $query;
41
    }
42
43
    /**
44
     * @param array  $data
45
     * @param string $path
46
     *
47
     * @return string
48
     */
49 1
    private function buildQuery(array $data, string $path = ''): string
50
    {
51 1
        $query = '';
52 1
        foreach ($data as $key => $value) {
53 1
            $subPathKey = !is_int($key) ? $key : $this->numericPrefix.$key;
54 1
            $subPath = '' !== $path ? $path.'['.$subPathKey.']' : $subPathKey;
55
56 1
            if (is_array($value)) {
57 1
                $query .= $this->buildQuery($value, $subPath);
58
            } else {
59 1
                $query .= $subPath.'='.urlencode((string) $value);
60
            }
61
62 1
            $query .= $this->argSeperator;
63
        }
64
65 1
        $query = substr($query, 0, -strlen($this->argSeperator));
66
67 1
        return $query;
68
    }
69
}
70