Completed
Push — master ( 809938...77bf81 )
by Olivier
03:49
created

HttpQueryBuilder::getParts()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 24
ccs 13
cts 13
cp 1
rs 9.2248
c 0
b 0
f 0
cc 5
nc 5
nop 2
crap 5
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
use Http\Discovery\MessageFactoryDiscovery;
13
use Http\Message\MultipartStream\MultipartStreamBuilder;
14
use Http\Message\RequestFactory;
15
use Psr\Http\Message\RequestInterface;
16
17
/**
18
 * @internal this class should not be used outside of the API Client, it is not part of the BC promise
19
 */
20
final class HttpQueryBuilder
21
{
22 32
    public function build(array $params): string
23
    {
24 32
        if (0 === \count($params)) {
25 27
            return '';
26
        }
27
28 5
        $parts = $this->getParts($params);
29
30 5
        $resolvedParams = [];
31 5
        foreach ($parts as $key => $value) {
32 5
            $resolvedParams[] = "$key=$value";
33
        }
34
35 5
        if (0 === count($resolvedParams)) {
36
            return '';
37
        }
38
39 5
        return implode('&', $resolvedParams);
40
    }
41
42 5
    private function getParts(array $params, string $prefix = null): array
43
    {
44 5
        $parts = [];
45 5
        foreach ($params as $key => $value) {
46 5
            if (is_array($value)) {
47 2
                $newPrefix = null === $prefix ? $key : $prefix.'['.$key.']';
48 2
                $subParts = $this->getParts($value, $newPrefix);
49
50 2
                $parts += $subParts;
51
52 2
                continue;
53
            }
54
55 5
            $param = $this->sanitizeParam($value);
56
57 5
            if (null === $prefix) {
58 3
                $parts[$key] = $param;
59
            } else {
60 2
                $parts[$prefix.'['.$key.']'] = $param;
61
            }
62
        }
63
64 5
        return $parts;
65
    }
66
67 5
    private function sanitizeParam($param): string
68
    {
69 5
        if (is_bool($param)) {
70 2
            return $param ? 'true' : 'false';
71
        }
72
73 4
        return (string) $param;
74
    }
75
}
76