-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathOAuth2.php
More file actions
102 lines (84 loc) · 2.3 KB
/
Copy pathOAuth2.php
File metadata and controls
102 lines (84 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php
namespace Cristal\ApiWrapper\Transports;
use Cristal\ApiWrapper\Transports\Transport as TransportCore;
use Curl\Curl;
use League\OAuth2\Client\Provider\AbstractProvider;
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
use Psr\Cache\CacheItemPoolInterface;
class OAuth2 extends TransportCore
{
/**
* @var AbstractProvider
*/
private $provider;
/**
* @var CacheItemPoolInterface
*/
private $cacheResolver;
/**
* @var string
*/
private $cacheKey;
/**
* @var string
*/
private $grant = 'password';
/**
* @var array
*/
private $options = [];
/**
* @var string
*/
private $token;
public function __construct(string $entrypoint, AbstractProvider $provider, Curl $client)
{
$this->provider = $provider;
parent::__construct($entrypoint, $client);
}
public function setCacheResolver(CacheItemPoolInterface $cacheResolver, string $key): OAuth2
{
$this->cacheResolver = $cacheResolver;
$this->cacheKey = $key;
return $this;
}
public function setGrant($grant): OAuth2
{
$this->grant = $grant;
return $this;
}
public function setOptions(array $options): OAuth2
{
$this->options = $options;
return $this;
}
/**
* @param string $endpoint
* @return mixed|null
* @throws IdentityProviderException
*/
public function rawRequest($endpoint, array $data = [], $method = 'get')
{
$this->getClient()->setHeader('Authorization', 'Bearer '.$this->getToken());
return parent::rawRequest($endpoint, $data, $method);
}
/**
* @throws IdentityProviderException
*/
protected function getToken(): string
{
$cacheItem = $this->cacheResolver->getItem($this->cacheKey);
if ($cacheItem->isHit()) {
$token = $cacheItem->get();
} else {
$token = $this->provider->getAccessToken($this->grant, $this->options);
$cacheItem->set($token);
$this->cacheResolver->save($cacheItem);
}
if ($token->hasExpired()) {
$this->cacheResolver->deleteItem($this->cacheKey);
return $this->getToken();
}
return $token->getToken();
}
}