Completed
Push — master ( 1197be...9384fc )
by Cedric
06:46
created

Qsh::getCorrectPath()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
/**
3
 * This file is part of the adlogix/guzzle-atlassian-connect-middleware package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
9
namespace Adlogix\GuzzleAtlassianConnect\Helpers;
10
11
/**
12
 * Class QSH
13
 * QSH is a Query String Hash requested by Atlassian in the JWT token
14
 * @see     https://developer.atlassian.com/static/connect/docs/latest/concepts/understanding-jwt.html#qsh
15
 * @package Adlogix\GuzzleAtlassianConnect\Helpers
16
 * @author  Cedric Michaux <[email protected]>
17
 */
18
class Qsh
19
{
20
    /**
21
     * @param $method
22
     * @param $url
23
     *
24
     * @return string
25
     */
26
    public static function create($method, $url)
27
    {
28
        $method = strtoupper($method);
29
30
31
        $parts = parse_url($url);
32
        $path = self::getCorrectPath($parts['path']);
33
34
        $canonicalQuery = '';
35
        if (array_key_exists('query', $parts)) {
36
            $canonicalQuery = self::getCanonicalQuery($parts['query']);
37
        }
38
39
        $qshString = $method . '&' . $path . '&' . $canonicalQuery;
40
        $qsh = hash('sha256', $qshString);
41
42
        return $qsh;
43
    }
44
45
    /**
46
     * @param string $query
47
     *
48
     * @return string
49
     */
50
    private static function getCanonicalQuery($query = '')
51
    {
52
        if (!empty($query)) {
53
            $queryParts = explode('&', $query);
54
            $query = '';
55
            $queryArray = [];
56
57
            foreach ($queryParts as $queryPart) {
58
                $pieces = explode('=', $queryPart, 2);
59
60
                $key = rawurlencode($pieces[0]);
61
                $value = rawurlencode($pieces[1]);
62
63
                $queryArray[$key][] = $value;
64
            }
65
66
            ksort($queryArray);
67
68
            foreach ($queryArray as $key => $pieceOfQuery) {
69
                $pieceOfQuery = implode(',', $pieceOfQuery);
70
                $query .= $key . '=' . $pieceOfQuery . '&';
71
            }
72
73
            $query = rtrim($query, '&');
74
        }
75
76
        return $query;
77
    }
78
79
    /**
80
     *
81
     * @param string $path
82
     *
83
     * @return mixed
84
     */
85
    private static function getCorrectPath($path)
86
    {
87
88
        $path = str_replace(' ', '%20', $path);
89
90
        if ('/' !== $path[0]) {
91
            $path = '/'.$path;
92
        }
93
94
        return $path;
95
    }
96
}
97