Passed
Push — master ( 793a6d...2461c7 )
by Timo
02:19
created

RequestHelper::_decodeJSON()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 6
ccs 3
cts 4
cp 0.75
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2.0625
1
<?php
2
3
namespace hamburgscleanest\GuzzleAdvancedThrottle\Helpers;
4
5
use Psr\Http\Message\RequestInterface;
6
7
/**
8
 * Class RequestHelper
9
 * @package hamburgscleanest\GuzzleAdvancedThrottle\Helpers
10
 */
11
class RequestHelper
12
{
13
14
    /**
15
     * @param RequestInterface $request
16
     * @return array
17
     */
18 19
    public static function getHostAndPath(RequestInterface $request) : array
19
    {
20 19
        $uri = $request->getUri();
21
22
        return [
23 19
            $uri->getScheme() . '://' . $uri->getHost(),
24 19
            $uri->getPath()
25
        ];
26
    }
27
28
    /**
29
     * @param RequestInterface $request
30
     * @return string
31
     */
32 21
    public static function getStorageKey(RequestInterface $request) : string
33
    {
34 21
        $method = $request->getMethod();
35 21
        if ($method !== 'GET')
36
        {
37 3
            $contentType = $request->getHeader('Content-Type')[0] ?? null;
38 3
            $params = $request->getBody()->getContents();
39
40 3
            return self::_getMethodAndParams(
41 3
                $method,
42 3
                $contentType === 'application/json' ? self::_decodeJSON($params) : $params
43
            );
44
        }
45
46 18
        return self::_getMethodAndParams($method, $request->getUri()->getQuery());
47
    }
48
49
    /**
50
     * @param string $method
51
     * @param string $params
52
     * @return string
53
     */
54 21
    private static function _getMethodAndParams(string $method, string $params) : string
55
    {
56 21
        return $method . '_' . self::_sortParams($params);
57
    }
58
59
    /**
60
     * @param string $params
61
     * @return string
62
     */
63 21
    private static function _sortParams(string $params) : string
64
    {
65 21
        $paramArray = \explode('&', $params);
66 21
        \sort($paramArray);
67
68 21
        return \implode('&', $paramArray);
69
    }
70
71
    /**
72
     * @param string $json
73
     * @return string
74
     */
75 1
    private static function _decodeJSON(string $json) : string
76
    {
77 1
        if(empty($json)) {
78
            return ''; // or also like in your code just return $json
79
        }
80 1
        return http_build_query(\GuzzleHttp\json_decode($json, true), '', '&');
81
    }
82
}