Passed
Push — master ( da0795...78880b )
by Jens
14:45 queued 18s
created

CredentialTokenProvider::getToken()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 17
ccs 9
cts 9
cp 1
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 2
1
<?php
2
3
namespace Commercetools\Core\Client\OAuth;
4
5
use GuzzleHttp\Client;
6
7
class CredentialTokenProvider implements TokenProvider
8
{
9
    const GRANT_TYPE = 'grant_type';
10
    const GRANT_TYPE_CLIENT_CREDENTIALS = 'client_credentials';
11
    const SCOPE = 'scope';
12
    const ACCESS_TOKEN = 'access_token';
13
    const EXPIRES_IN = 'expires_in';
14
15
    /**
16
     * @var Client
17
     */
18
    private $client;
19
20
    /**
21
     * @var ClientCredentials
22
     */
23
    private $credentials;
24
25
    /**
26
     * @var string
27
     */
28
    private $accessTokenUrl;
29
30
    /**
31
     * @param Client $client
32
     * @param string $accessTokenUrl
33
     * @param array $credentials
34
     */
35 5
    public function __construct(Client $client, $accessTokenUrl, ClientCredentials $credentials)
36
    {
37 5
        $this->accessTokenUrl = $accessTokenUrl;
38 5
        $this->client = $client;
39 5
        $this->credentials = $credentials;
40 5
    }
41
42
    /**
43
     * @return Token
44
     */
45 2
    public function getToken()
46
    {
47
        $data = [
48 2
            self::GRANT_TYPE => self::GRANT_TYPE_CLIENT_CREDENTIALS
49
        ];
50 2
        if (!empty($this->credentials->getScope())) {
51 2
            $data[self::SCOPE] = $this->credentials->getScope();
52
        }
53
        $options = [
54 2
            'form_params' => $data,
55 2
            'auth' => [$this->credentials->getClientId(), $this->credentials->getClientSecret()]
56
        ];
57
58 2
        $result = $this->client->post($this->accessTokenUrl, $options);
59
60 2
        $body = json_decode((string)$result->getBody(), true);
61 2
        return new Token((string)$body[self::ACCESS_TOKEN], (int)$body[self::EXPIRES_IN], $body[self::SCOPE]);
62
    }
63
}
64