HttpQueryBuilder   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 96.43%

Importance

Changes 0
Metric Value
wmc 12
lcom 0
cbo 0
dl 0
loc 58
ccs 27
cts 28
cp 0.9643
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A build() 0 19 4
A getParts() 0 24 5
A sanitizeParam() 0 10 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