1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Eljam\GuzzleJwt\Manager; |
4
|
|
|
|
5
|
|
|
use Eljam\GuzzleJwt\JwtToken; |
6
|
|
|
use Eljam\GuzzleJwt\Strategy\Auth\AuthStrategyInterface; |
7
|
|
|
use GuzzleHttp\ClientInterface; |
8
|
|
|
use GuzzleHttp\request; |
9
|
|
|
use Symfony\Component\OptionsResolver\OptionsResolver; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* @author Guillaume Cavana <[email protected]> |
13
|
|
|
*/ |
14
|
|
|
class JwtManager |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* $client Guzzle Client. |
18
|
|
|
* |
19
|
|
|
* @var ClientInterface |
20
|
|
|
*/ |
21
|
|
|
protected $client; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* $auth Authentication Strategy. |
25
|
|
|
* |
26
|
|
|
* @var AuthStrategyInterface |
27
|
|
|
*/ |
28
|
|
|
protected $auth; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* $options. |
32
|
|
|
* |
33
|
|
|
* @var array |
34
|
|
|
*/ |
35
|
|
|
protected $options; |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Constructor. |
39
|
|
|
* |
40
|
|
|
* @param ClientInterface $client |
41
|
|
|
* @param AuthStrategyInterface $auth |
42
|
|
|
* @param array $options |
43
|
|
|
*/ |
44
|
|
|
public function __construct( |
45
|
|
|
ClientInterface $client, |
46
|
|
|
AuthStrategyInterface $auth, |
47
|
|
|
array $options = [] |
48
|
|
|
) { |
49
|
|
|
$this->client = $client; |
50
|
|
|
$this->auth = $auth; |
51
|
|
|
|
52
|
|
|
$resolver = new OptionsResolver(); |
53
|
|
|
$resolver->setDefaults([ |
54
|
|
|
'token_url' => '/token', |
55
|
|
|
'timeout' => 1, |
56
|
|
|
'token_key' => 'token', |
57
|
|
|
]); |
58
|
|
|
|
59
|
|
|
$resolver->setRequired(['token_url', 'timeout']); |
60
|
|
|
|
61
|
|
|
$this->options = $resolver->resolve($options); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* getToken. |
66
|
|
|
* |
67
|
|
|
* @return JwtToken |
68
|
|
|
*/ |
69
|
|
|
public function getJwtToken() |
70
|
|
|
{ |
71
|
|
|
$url = $this->options['token_url']; |
72
|
|
|
|
73
|
|
|
$requestOptions = array_merge( |
74
|
|
|
$this->getDefaultHeaders(), |
75
|
|
|
$this->auth->getRequestOptions() |
76
|
|
|
); |
77
|
|
|
|
78
|
|
|
$response = $this->client->request('POST', $url, $requestOptions); |
79
|
|
|
$body = json_decode($response->getBody(), true); |
80
|
|
|
|
81
|
|
|
return new JwtToken($body[$this->options['token_key']]); |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
/** |
85
|
|
|
* getHeaders. Return defaults header. |
86
|
|
|
* |
87
|
|
|
* @return array |
88
|
|
|
*/ |
89
|
|
|
private function getDefaultHeaders() |
90
|
|
|
{ |
91
|
|
|
return [ |
92
|
|
|
\GuzzleHttp\RequestOptions::HEADERS => [ |
93
|
|
|
'timeout' => $this->options['timeout'], |
94
|
|
|
], |
95
|
|
|
]; |
96
|
|
|
} |
97
|
|
|
} |
98
|
|
|
|