Completed
Push — develop ( 10a3f8...fe23c8 )
by Jens
10:24
created

Manager   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 191
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 2
Metric Value
wmc 21
c 3
b 0
f 2
lcom 1
cbo 8
dl 0
loc 191
ccs 51
cts 51
cp 1
rs 10

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A getCacheAdapterFactory() 0 7 2
A setCacheAdapter() 0 6 1
A getCacheAdapter() 0 4 1
A getToken() 0 9 2
B refreshToken() 0 29 4
A getCacheToken() 0 4 1
A getCacheKey() 0 21 4
A getBearerToken() 0 18 3
A execute() 0 9 1
A getBaseUrl() 0 4 1
1
<?php
2
/**
3
 * @author @jayS-de <[email protected]>
4
 * @created: 22.01.15, 12:34
5
 */
6
7
namespace Commercetools\Core\Client\OAuth;
8
9
use Commercetools\Core\Config;
10
use Commercetools\Core\Error\ApiException;
11
use Psr\Http\Message\ResponseInterface;
12
use Commercetools\Core\AbstractHttpClient;
13
use Commercetools\Core\Cache\CacheAdapterFactory;
14
use Commercetools\Core\Cache\CacheAdapterInterface;
15
use Commercetools\Core\Error\InvalidClientCredentialsException;
16
17
/**
18
 * @package Commercetools\Core\OAuth
19
 * @internal
20
 */
21
class Manager extends AbstractHttpClient
22
{
23
    const TOKEN_CACHE_KEY = 'commercetools-io-access-token';
24
25
    const REFRESH_TOKEN = 'refresh_token';
26
    const ACCESS_TOKEN = 'access_token';
27
    const EXPIRES_IN = 'expires_in';
28
    const ERROR = 'error';
29
    const SCOPE = 'scope';
30
    const ERROR_DESCRIPTION = 'error_description';
31
32
    /**
33
     * @var array
34
     */
35
    protected $cacheKeys;
36
37
    /**
38
     * @var CacheAdapterInterface
39
     */
40
    protected $cacheAdapter;
41
42
    /**
43
     * @var CacheAdapterFactory
44
     */
45
    protected $cacheAdapterFactory;
46
47
    public function __construct($config, $cache = null)
48 297
    {
49
        parent::__construct($config);
50 297
        $this->cacheKeys = [];
51 297
        $this->setCacheAdapter($cache);
52 297
    }
53 297
54
    /**
55
     * @return CacheAdapterFactory
56
     */
57
    public function getCacheAdapterFactory()
58 297
    {
59
        if (is_null($this->cacheAdapterFactory)) {
60 297
            $this->cacheAdapterFactory = new CacheAdapterFactory();
61 297
        }
62
        return $this->cacheAdapterFactory;
63 297
    }
64
65
    /**
66
     * @param $cache
67
     * @return $this
68
     */
69
    public function setCacheAdapter($cache)
70 297
    {
71
        $this->cacheAdapter = $this->getCacheAdapterFactory()->get($cache);
72 297
73
        return $this;
74 297
    }
75
76
    /**
77
     * @return CacheAdapterInterface
78
     */
79
    public function getCacheAdapter()
80 270
    {
81
        return $this->cacheAdapter;
82 270
    }
83
84
    /**
85
     * @param string $scope
0 ignored issues
show
Bug introduced by
There is no parameter named $scope. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
86
     * @return Token
87
     * @throws InvalidClientCredentialsException
88
     */
89
    public function getToken()
90 270
    {
91
        $scope = $this->getConfig()->getScope();
92 270
        if ($token = $this->getCacheToken()) {
93 270
            return new Token($token, null, $scope);
94
        }
95 270
96 269
        return $this->refreshToken();
97
    }
98
99 6
    /**
100
     * @return Token
101
     * @throws InvalidClientCredentialsException
102
     */
103
    public function refreshToken()
104
    {
105
        $scope = $this->getConfig()->getScope();
106
        $grantType = $this->getConfig()->getGrantType();
107 7
        $data = [Config::SCOPE => $scope, Config::GRANT_TYPE => $grantType];
108
109 7
        if ($grantType === Config::GRANT_TYPE_PASSWORD) {
110 1
            $user = $this->getConfig()->getUsername();
111
            $password = $this->getConfig()->getPassword();
112 7
            $data[Config::USER_NAME] = $user;
113
            $data[Config::PASSWORD] = $password;
114 6
        } elseif ($grantType === Config::GRANT_TYPE_REFRESH) {
115 6
            $refreshToken = $this->getConfig()->getRefreshToken();
116
            $data[Config::REFRESH_TOKEN] = $refreshToken;
117 6
        }
118
        
119
        $token = $this->getBearerToken($data);
120 270
121
        if ($grantType === Config::GRANT_TYPE_PASSWORD) {
122 270
            $this->getConfig()->setGrantType(Config::GRANT_TYPE_REFRESH);
123
            $this->getConfig()->setRefreshToken($token->getRefreshToken());
124
        }
125
126
        // ensure token to be invalidated in cache before TTL
127
        $ttl = max(1, floor($token->getTtl()/2));
128
        $this->getCacheAdapter()->store($this->getCacheKey(), $token->getToken(), $ttl);
129 270
130
        return $token;
131 270
    }
132 270
133 270
    protected function getCacheToken()
134
    {
135
        return $this->getCacheAdapter()->fetch($this->getCacheKey());
136 270
    }
137
138
    /**
139
     * @return string
140
     */
141
    protected function getCacheKey()
142
    {
143
        $scope = $this->getConfig()->getScope();
144
        $grantType = $this->getConfig()->getGrantType();
145
        $cacheScope = $scope . '-' . $grantType;
146
147 7
        if ($grantType === Config::GRANT_TYPE_PASSWORD) {
148
            $user = $this->getConfig()->getUsername();
149
            $cacheScope .= '-' . $user;
150 7
        } elseif ($grantType === Config::GRANT_TYPE_REFRESH) {
151 7
            $token = $this->getConfig()->getRefreshToken();
152
            $cacheScope .= '-' . $token;
153
        }
154
155 7
        if (!isset($this->cacheKeys[$cacheScope])) {
156 1
            $this->cacheKeys[$cacheScope] = static::TOKEN_CACHE_KEY . '-' .
157 1
                sha1($cacheScope);
158
        }
159
160 6
        return $this->cacheKeys[$cacheScope];
161
    }
162 6
163 6
    /**
164
     * @param array $data
165 6
     * @return Token
166
     * @throws ApiException
167
     * @throws \Commercetools\Core\Error\BadGatewayException
168
     * @throws \Commercetools\Core\Error\GatewayTimeoutException
169
     * @throws \Commercetools\Core\Error\ServiceUnavailableException
170
     */
171
    protected function getBearerToken(array $data)
172 7
    {
173
        try {
174 7
            $response = $this->execute($data);
175 7
        } catch (ApiException $exception) {
176 7
            throw ApiException::create($exception->getRequest(), $exception->getResponse());
177 7
        }
178
179
        $result = json_decode($response->getBody(), true);
180
181
        $token = new Token($result[static::ACCESS_TOKEN], $result[static::EXPIRES_IN], $result[static::SCOPE]);
182
        $token->setValidTo(new \DateTime('now +' . $result[static::EXPIRES_IN] . ' seconds'));
183
        if (isset($result[static::REFRESH_TOKEN])) {
184
            $token->setRefreshToken($result[static::REFRESH_TOKEN]);
185 271
        }
186
187 271
        return $token;
188
    }
189
190
    /**
191
     * @param $data
192
     * @return ResponseInterface
193
     */
194
    public function execute($data)
195
    {
196
        return $this->getHttpClient()->authenticate(
197
            $this->getConfig()->getOauthUrl(),
198
            $this->getConfig()->getClientId(),
199
            $this->getConfig()->getClientSecret(),
200
            $data
201
        );
202
    }
203
204
    /**
205
     * @return string
206
     */
207
    protected function getBaseUrl()
208
    {
209
        return $this->getConfig()->getOauthUrl();
210
    }
211
}
212