|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Onend\PayPal\Common\Auth; |
|
4
|
|
|
|
|
5
|
|
|
class DefaultAccessTokenProvider implements AccessTokenProviderInterface |
|
6
|
|
|
{ |
|
7
|
|
|
/** |
|
8
|
|
|
* @var AccessTokenInterface |
|
9
|
|
|
*/ |
|
10
|
|
|
protected $accessToken; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* @var AccessTokenProviderInterface |
|
14
|
|
|
*/ |
|
15
|
|
|
protected $provider; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* @var AuthClient |
|
19
|
|
|
*/ |
|
20
|
|
|
protected $authClient; |
|
21
|
|
|
|
|
22
|
|
|
// todo suuggests package for cache |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* @param AuthClient $authClient |
|
26
|
|
|
*/ |
|
27
|
|
|
public function __construct(AuthClient $authClient) |
|
28
|
|
|
{ |
|
29
|
|
|
$this->authClient = $authClient; |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* @param AccessTokenProviderInterface $provider |
|
34
|
|
|
*/ |
|
35
|
|
|
public function setProvider(AccessTokenProviderInterface $provider) |
|
36
|
|
|
{ |
|
37
|
|
|
$this->provider = $provider; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
/** |
|
41
|
|
|
* @return AccessTokenInterface |
|
42
|
|
|
*/ |
|
43
|
|
|
public function getAccessToken() |
|
44
|
|
|
{ |
|
45
|
|
|
if ($this->hasProvider()) { |
|
46
|
|
|
if (($token = $this->provider->getAccessToken()) === null) { |
|
47
|
|
|
$token = $this->createNewAccessToken(); |
|
48
|
|
|
$this->provider->setAccessToken($token); |
|
49
|
|
|
} |
|
50
|
|
|
} elseif ($this->accessToken !== null) { |
|
51
|
|
|
$token = $this->accessToken; |
|
52
|
|
|
} else { |
|
53
|
|
|
$this->accessToken = $token = $this->createNewAccessToken(); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
return $token; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
/** |
|
60
|
|
|
* @param AccessTokenInterface $accessToken |
|
61
|
|
|
*/ |
|
62
|
|
|
public function setAccessToken(AccessTokenInterface $accessToken) |
|
63
|
|
|
{ |
|
64
|
|
|
if ($this->hasProvider()) { |
|
65
|
|
|
$this->provider->setAccessToken($accessToken); |
|
66
|
|
|
} else { |
|
67
|
|
|
$this->accessToken = $accessToken; |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
/** |
|
72
|
|
|
* @return bool |
|
73
|
|
|
*/ |
|
74
|
|
|
protected function hasProvider() |
|
75
|
|
|
{ |
|
76
|
|
|
return $this->provider instanceof AccessTokenProviderInterface; |
|
77
|
|
|
} |
|
78
|
|
|
|
|
79
|
|
|
/** |
|
80
|
|
|
* @return AccessToken |
|
81
|
|
|
*/ |
|
82
|
|
|
protected function createNewAccessToken() |
|
83
|
|
|
{ |
|
84
|
|
|
$authResponse = $this->authClient->auth(); |
|
85
|
|
|
$accessToken = new AccessToken(); |
|
86
|
|
|
$accessToken->setToken($authResponse->getAccessToken()); |
|
87
|
|
|
$accessToken->setTokenType($authResponse->getTokenType()); |
|
88
|
|
|
$accessToken->setExpiresIn($authResponse->getExpiresIn()); |
|
89
|
|
|
|
|
90
|
|
|
return $accessToken; |
|
91
|
|
|
} |
|
92
|
|
|
} |
|
93
|
|
|
|