RequestUtil   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Test Coverage

Coverage 58.06%

Importance

Changes 0
Metric Value
eloc 29
dl 0
loc 63
ccs 18
cts 31
cp 0.5806
rs 10
c 0
b 0
f 0
wmc 12

4 Methods

Rating   Name   Duplication   Size   Complexity  
A addHeaders() 0 6 2
A getParams() 0 23 6
A composeUrl() 0 11 3
A addParams() 0 7 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\AuthClient;
6
7
use Psr\Http\Message\RequestInterface;
8
9
use function is_array;
10
11
final class RequestUtil
12
{
13
    /**
14
     * Composes URL from base URL and GET params.
15
     *
16
     * @param string $url base URL.
17
     * @param array $params GET params.
18
     *
19
     * @return string composed URL.
20
     */
21 2
    public static function composeUrl(string $url, array $params = []): string
22
    {
23 2
        if (!empty($params)) {
24 2
            if (strpos($url, '?') === false) {
25 2
                $url .= '?';
26
            } else {
27
                $url .= '&';
28
            }
29 2
            $url .= http_build_query($params, '', '&', PHP_QUERY_RFC3986);
30
        }
31 2
        return $url;
32
    }
33
34
    public static function addParams(RequestInterface $request, array $params): RequestInterface
35
    {
36
        $currentParams = self::getParams($request);
37
        $newParams = array_merge($currentParams, $params);
38
39
        $uri = $request->getUri()->withQuery(http_build_query($newParams, '', '&', PHP_QUERY_RFC3986));
40
        return $request->withUri($uri);
41
    }
42
43 3
    public static function getParams(RequestInterface $request): array
44
    {
45 3
        $queryString = $request->getUri()->getQuery();
46 3
        if ($queryString === '') {
47 1
            return [];
48
        }
49
50 2
        $result = [];
51
52 2
        foreach (explode('&', $queryString) as $pair) {
53 2
            $parts = explode('=', $pair, 2);
54 2
            $key = rawurldecode($parts[0]);
55 2
            $value = isset($parts[1]) ? rawurldecode($parts[1]) : null;
56 2
            if (!isset($result[$key])) {
57 2
                $result[$key] = $value;
58
            } else {
59
                if (!is_array($result[$key])) {
60
                    $result[$key] = [$result[$key]];
61
                }
62
                $result[$key][] = $value;
63
            }
64
        }
65 2
        return $result;
66
    }
67
68
    public static function addHeaders(RequestInterface $request, array $headers): RequestInterface
69
    {
70
        foreach ($headers as $header => $value) {
71
            $request = $request->withHeader($header, $value);
72
        }
73
        return $request;
74
    }
75
}
76