Passed
Push — main ( 4dc4a3...97513a )
by Stas
14:40 queued 04:40
created

AuthorizationBuilder::buildAuthorizationHeader()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
namespace Huawei\IAP;
4
5
use GuzzleHttp\Client;
6
use Huawei\IAP\Exception\AuthorizationResponseUnexpectedFormatException;
7
use Huawei\IAP\Exception\InvalidAuthorizationResponseException;
8
9
class AuthorizationBuilder
10
{
11
    const AUTHORIZATION_TOKEN_URL = 'https://oauth-login.cloud.huawei.com/oauth2/v2/token';
12
13
    /**
14
     * @return Client
15
     */
16
    protected function getClient()
17
    {
18
        return new Client();
19
    }
20
21
    /**
22
     * @param string $accessToken
23
     *
24
     * @return string
25
     */
26
    public function buildAuthorizationHeader(string $accessToken)
27
    {
28
        return sprintf('Basic %s', base64_encode(sprintf('APPAT:%s', $accessToken)));
29
    }
30
31
    /**
32
     * @param AuthorizationCredentials $credentials
33
     *
34
     * @return string
35
     * @throws \GuzzleHttp\Exception\GuzzleException
36
     * @throws InvalidAuthorizationResponseException
37
     * @throws AuthorizationResponseUnexpectedFormatException
38
     */
39
    public function getAccessToken(AuthorizationCredentials $credentials): string
40
    {
41
        $response = $this->getClient()->request('POST', self::AUTHORIZATION_TOKEN_URL, [
42
            'form_params' => [
43
                'grant_type' => 'client_credentials',
44
                'client_id' => $credentials->getApplicationId(),
45
                'client_secret' => $credentials->getAppKey(),
46
            ]
47
        ]);
48
49
        $body = $response->getBody()->getContents();
50
51
        $json = \json_decode($body, true);
52
53
        if (\json_last_error() !== JSON_ERROR_NONE) {
54
            throw new InvalidAuthorizationResponseException(
55
                \sprintf(
56
                    'Invalid authorization response (%s) from %s',
57
                    \json_last_error_msg(),
58
                    self::AUTHORIZATION_TOKEN_URL
59
                )
60
            );
61
        }
62
63
        $accessToken = $json['access_token'] ?? null;
64
65
        if ($accessToken === null) {
66
            throw new AuthorizationResponseUnexpectedFormatException(
67
                \sprintf(
68
                    'Authorization response unexpected format (%s) from %s',
69
                    \json_last_error_msg(),
70
                    self::AUTHORIZATION_TOKEN_URL
71
                )
72
            );
73
        }
74
75
        return $accessToken;
76
    }
77
}
78