Passed
Push — master ( 78880b...ac7e2f )
by Jens
20:00 queued 13s
created

PasswordFlowTokenProvider::getTokenFor()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 14
c 1
b 0
f 1
dl 0
loc 22
ccs 13
cts 13
cp 1
rs 9.7998
cc 1
nc 1
nop 2
crap 1
1
<?php
2
3
namespace Commercetools\Core\Client\OAuth;
4
5
use GuzzleHttp\Client;
6
7
class PasswordFlowTokenProvider
8
{
9
    const GRANT_TYPE = 'grant_type';
10
    const GRANT_TYPE_PASSWORD = 'password';
11
    const SCOPE = 'scope';
12
    const REFRESH_TOKEN = 'refresh_token';
13
    const ACCESS_TOKEN = 'access_token';
14
    const EXPIRES_IN = 'expires_in';
15
16
    /**
17
     * @var Client
18
     */
19
    private $client;
20
21
    /**
22
     * @var ClientCredentials
23
     */
24
    private $credentials;
25
26
    /**
27
     * @var string
28
     */
29
    private $accessTokenUrl;
30
31
    /**
32
     * @var TokenStorage
33
     */
34
    private $tokenStorage;
35
36
37
    /**
38
     * @param Client $client
39
     * @param $accessTokenUrl
40
     * @param ClientCredentials $credentials
41
     * @param TokenStorage $tokenStorage
42
     */
43 6
    public function __construct(
44
        Client $client,
45
        $accessTokenUrl,
46
        ClientCredentials $credentials,
47
        TokenStorage $tokenStorage
48
    ) {
49 6
        $this->accessTokenUrl = $accessTokenUrl;
50 6
        $this->client = $client;
51 6
        $this->credentials = $credentials;
52 6
        $this->tokenStorage = $tokenStorage;
53 6
    }
54
55
    /**
56
     * @param string $userName
57
     * @param string $password
58
     * @return Token
59
     */
60 6
    public function getTokenFor($userName, $password)
61
    {
62
        $data = [
63 6
            self::GRANT_TYPE => self::GRANT_TYPE_PASSWORD,
64 6
            'username' => $userName,
65 6
            'password' => $password
66
        ];
67
        $options = [
68 6
            'form_params' => $data,
69 6
            'auth' => [$this->credentials->getClientId(), $this->credentials->getClientSecret()]
70
        ];
71
72 6
        $result = $this->client->post($this->accessTokenUrl, $options);
73
74 6
        $body = json_decode((string)$result->getBody(), true);
75 6
        $token = new Token((string)$body[self::ACCESS_TOKEN], (int)$body[self::EXPIRES_IN], $body[self::SCOPE]);
76 6
        $token->setRefreshToken((string)$body[self::REFRESH_TOKEN]);
77
78 6
        $this->tokenStorage->setAccessToken($token->getToken());
79 6
        $this->tokenStorage->setRefreshToken($token->getRefreshToken());
80
81 6
        return $token;
82
    }
83
}
84