HttpQueryBuilder::sanitizeParam()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 5
cts 5
cp 1
rs 9.9332
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This software may be modified and distributed under the terms
7
 * of the MIT license. See the LICENSE file for details.
8
 */
9
10
namespace Shapin\Stripe;
11
12
/**
13
 * @internal this class should not be used outside of the API Client, it is not part of the BC promise
14
 */
15
final class HttpQueryBuilder
16
{
17 11
    public function build(array $params): string
18
    {
19 11
        if (0 === \count($params)) {
20 2
            return '';
21
        }
22
23 9
        $parts = $this->getParts($params);
24
25 9
        $resolvedParams = [];
26 9
        foreach ($parts as $key => $value) {
27 9
            $resolvedParams[] = "$key=$value";
28
        }
29
30 9
        if (0 === \count($resolvedParams)) {
31
            return '';
32
        }
33
34 9
        return implode('&', $resolvedParams);
35
    }
36
37 9
    private function getParts(array $params, string $prefix = null): array
38
    {
39 9
        $parts = [];
40 9
        foreach ($params as $key => $value) {
41 9
            if (\is_array($value)) {
42 3
                $newPrefix = null === $prefix ? $key : $prefix.'['.$key.']';
43 3
                $subParts = $this->getParts($value, $newPrefix);
44
45 3
                $parts += $subParts;
46
47 3
                continue;
48
            }
49
50 9
            $param = $this->sanitizeParam($value);
51
52 9
            if (null === $prefix) {
53 7
                $parts[$key] = $param;
54
            } else {
55 2
                $parts[$prefix.'['.$key.']'] = $param;
56
            }
57
        }
58
59 9
        return $parts;
60
    }
61
62 9
    private function sanitizeParam($param): string
63
    {
64 9
        if (\is_bool($param)) {
65 2
            return $param ? 'true' : 'false';
66
        }
67
68 8
        $param = urlencode((string) $param);
69
70 8
        return $param;
71
    }
72
}
73