Passed
Push — master ( ea520a...3ac64b )
by Bukashk0zzz
03:30 queued 13s
created

QSHGenerator::generate()   B

Complexity

Conditions 4
Paths 2

Size

Total Lines 29
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 20
nc 2
nop 2
dl 0
loc 29
rs 8.5806
c 0
b 0
f 0
1
<?php declare(strict_types = 1);
2
3
namespace AtlassianConnectBundle\Service;
4
5
/**
6
 * Class QSHGenerator
7
 */
8
class QSHGenerator
9
{
10
    /**
11
     * Create Query String Hash
12
     *
13
     * More details:
14
     * https://developer.atlassian.com/static/connect/docs/latest/concepts/understanding-jwt.html#creating-token
15
     *
16
     * @param string $url    URL of the request
17
     * @param string $method HTTP method
18
     *
19
     * @return string
20
     */
21
    public static function generate(string $url, string $method): string
22
    {
23
        $parts = \parse_url($url);
24
25
        // Remove "/wiki" part from the path for the Confluence
26
        // Really, I didn't find this part in the docs, but it works
27
        $path = \str_replace('/wiki', '', $parts['path']);
28
        $canonicalQuery = '';
29
        if (!empty($parts['query'])) {
30
            $query = $parts['query'];
31
            $queryParts = \explode('&', $query);
32
            $queryArray = [];
33
            foreach ($queryParts as $queryPart) {
34
                $pieces = \explode('=', $queryPart);
35
                $key = \array_shift($pieces);
36
                $key = \rawurlencode($key);
37
                $value = \mb_substr($queryPart, \mb_strlen($key) + 1);
38
                $value = \rawurlencode($value);
39
                $queryArray[$key][] = $value;
40
            }
41
            \ksort($queryArray);
42
            foreach ($queryArray as $key => $pieceOfQuery) {
43
                $pieceOfQuery = \implode(',', $pieceOfQuery);
44
                $canonicalQuery .= $key.'='.$pieceOfQuery.'&';
45
            }
46
            $canonicalQuery = \rtrim($canonicalQuery, '&');
47
        }
48
49
        return \hash('sha256', \implode('&', [\mb_strtoupper($method), $path, $canonicalQuery]));
50
    }
51
}
52