Completed
Push — develop ( 9bc436...6029a0 )
by Jens
11:57
created

Manager   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 167
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Test Coverage

Coverage 100%

Importance

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

11 Methods

Rating   Name   Duplication   Size   Complexity  
A getCacheAdapter() 0 4 1
A __construct() 0 6 1
A setCacheAdapter() 0 6 1
A getCacheAdapterFactory() 0 7 2
A getToken() 0 11 3
A refreshToken() 0 12 2
A getCacheToken() 0 4 1
A getCacheKey() 0 9 2
A getBearerToken() 0 20 2
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\Error\ApiException;
10
use GuzzleHttp\Psr7\Request;
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\Client\HttpMethod;
16
use Commercetools\Core\Error\InvalidClientCredentialsException;
17
use Commercetools\Core\Error\Message;
18
19
/**
20
 * @package Commercetools\Core\OAuth
21
 * @internal
22
 */
23
class Manager extends AbstractHttpClient
24
{
25
    const TOKEN_CACHE_KEY = 'commercetools-io-access-token';
26
27
    const ACCESS_TOKEN = 'access_token';
28
    const EXPIRES_IN = 'expires_in';
29
    const ERROR = 'error';
30
    const SCOPE = 'scope';
31
    const ERROR_DESCRIPTION = 'error_description';
32
33
    /**
34
     * @var array
35
     */
36
    protected $cacheKeys;
37
38
    /**
39
     * @var CacheAdapterInterface
40
     */
41
    protected $cacheAdapter;
42
43
    /**
44
     * @var CacheAdapterFactory
45
     */
46
    protected $cacheAdapterFactory;
47
48 297
    public function __construct($config, $cache = null)
49
    {
50 297
        parent::__construct($config);
51 297
        $this->cacheKeys = [];
52 297
        $this->setCacheAdapter($cache);
53 297
    }
54
55
    /**
56
     * @return CacheAdapterFactory
57
     */
58 297
    public function getCacheAdapterFactory()
59
    {
60 297
        if (is_null($this->cacheAdapterFactory)) {
61 297
            $this->cacheAdapterFactory = new CacheAdapterFactory();
62
        }
63 297
        return $this->cacheAdapterFactory;
64
    }
65
66
    /**
67
     * @param $cache
68
     * @return $this
69
     */
70 297
    public function setCacheAdapter($cache)
71
    {
72 297
        $this->cacheAdapter = $this->getCacheAdapterFactory()->get($cache);
73
74 297
        return $this;
75
    }
76
77
    /**
78
     * @return CacheAdapterInterface
79
     */
80 270
    public function getCacheAdapter()
81
    {
82 270
        return $this->cacheAdapter;
83
    }
84
85
    /**
86
     * @param string $scope
87
     * @return Token
88
     * @throws InvalidClientCredentialsException
89
     */
90 270
    public function getToken($scope = null)
91
    {
92 270
        if (is_null($scope)) {
93 270
            $scope = $this->getConfig()->getScope();
94
        }
95 270
        if ($token = $this->getCacheToken($scope)) {
96 269
            return new Token($token, null, $scope);
97
        }
98
99 6
        return $this->refreshToken($scope);
100
    }
101
102
    /**
103
     * @param string $scope
104
     * @return Token
105
     * @throws InvalidClientCredentialsException
106
     */
107 7
    public function refreshToken($scope = null)
108
    {
109 7
        if (is_null($scope)) {
110 1
            $scope = $this->getConfig()->getScope();
111
        }
112 7
        $token = $this->getBearerToken($scope);
113
        // ensure token to be invalidated in cache before TTL
114 6
        $ttl = max(1, floor($token->getTtl()/2));
115 6
        $this->getCacheAdapter()->store($this->getCacheKey($scope), $token->getToken(), $ttl);
116
117 6
        return $token;
118
    }
119
120 270
    protected function getCacheToken($scope)
121
    {
122 270
        return $this->getCacheAdapter()->fetch($this->getCacheKey($scope));
123
    }
124
125
    /**
126
     * @param $scope
127
     * @return string
128
     */
129 270
    protected function getCacheKey($scope)
130
    {
131 270
        if (!isset($this->cacheKeys[$scope])) {
132 270
            $this->cacheKeys[$scope] = static::TOKEN_CACHE_KEY . '-' .
133 270
                sha1($scope);
134
        }
135
136 270
        return $this->cacheKeys[$scope];
137
    }
138
139
    /**
140
     * @param string $scope
141
     * @return Token
142
     * @throws ApiException
143
     * @throws \Commercetools\Core\Error\BadGatewayException
144
     * @throws \Commercetools\Core\Error\GatewayTimeoutException
145
     * @throws \Commercetools\Core\Error\ServiceUnavailableException
146
     */
147 7
    protected function getBearerToken($scope)
148
    {
149
        $data = [
150 7
            'grant_type' => 'client_credentials',
151 7
            'scope' => $scope
152
        ];
153
154
        try {
155 7
            $response = $this->execute($data);
156 1
        } catch (ApiException $exception) {
157 1
            throw ApiException::create($exception->getRequest(), $exception->getResponse());
158
        }
159
160 6
        $result = json_decode($response->getBody(), true);
161
162 6
        $token = new Token($result[static::ACCESS_TOKEN], $result[static::EXPIRES_IN], $result[static::SCOPE]);
163 6
        $token->setValidTo(new \DateTime('now +' . $result[static::EXPIRES_IN] . ' seconds'));
164
165 6
        return $token;
166
    }
167
168
    /**
169
     * @param $data
170
     * @return ResponseInterface
171
     */
172 7
    public function execute($data)
173
    {
174 7
        return $this->getHttpClient()->authenticate(
175 7
            $this->getConfig()->getOauthUrl(),
176 7
            $this->getConfig()->getClientId(),
177 7
            $this->getConfig()->getClientSecret(),
178
            $data
179
        );
180
    }
181
182
    /**
183
     * @return string
184
     */
185 271
    protected function getBaseUrl()
186
    {
187 271
        return $this->getConfig()->getOauthUrl();
188
    }
189
}
190