|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace FAPI\Sylius\Http; |
|
6
|
|
|
|
|
7
|
|
|
use Http\Client\Common\Plugin; |
|
8
|
|
|
use Http\Promise\Promise; |
|
9
|
|
|
use Psr\Http\Message\RequestInterface; |
|
10
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* This will automatically refresh expired access token. |
|
14
|
|
|
* |
|
15
|
|
|
* @author Tobias Nyholm <[email protected]> |
|
16
|
|
|
*/ |
|
17
|
|
|
class AuthenticationPlugin implements Plugin |
|
18
|
|
|
{ |
|
19
|
|
|
/** |
|
20
|
|
|
* @var array |
|
21
|
|
|
*/ |
|
22
|
|
|
private $accessToken; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* @var Authenticator |
|
26
|
|
|
*/ |
|
27
|
|
|
private $authenticator; |
|
28
|
|
|
|
|
29
|
|
|
public function __construct(Authenticator $authenticator, string $accessToken) |
|
30
|
|
|
{ |
|
31
|
|
|
$this->authenticator = $authenticator; |
|
32
|
|
|
$this->accessToken = json_decode($accessToken, true); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
public function handleRequest(RequestInterface $request, callable $next, callable $first) |
|
36
|
|
|
{ |
|
37
|
|
|
$header = sprintf('Bearer %s', $this->accessToken['access_token']); |
|
38
|
|
|
$request = $request->withHeader('Authorization', $header); |
|
39
|
|
|
|
|
40
|
|
|
$promise = $next($request); |
|
41
|
|
|
return $promise->then(function (ResponseInterface $response) use ($request, $next, $first) { |
|
42
|
|
|
if ($response->getStatusCode() !== 401) { |
|
43
|
|
|
return $response; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
$accessToken = $this->authenticator->refreshAccessToken($this->accessToken['access_token'], $this->accessToken['refresh_token']); |
|
47
|
|
|
if (null === $accessToken) { |
|
48
|
|
|
return $response; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
// Save new token |
|
52
|
|
|
$this->accessToken = json_decode($accessToken, true); |
|
53
|
|
|
|
|
54
|
|
|
// Add new token to request |
|
55
|
|
|
$header = sprintf('Bearer %s', $this->accessToken['access_token']); |
|
56
|
|
|
$request = $request->withHeader('Authorization', $header); |
|
|
|
|
|
|
57
|
|
|
|
|
58
|
|
|
// Retry |
|
59
|
|
|
$promise = $this->handleRequest($request, $next, $first); |
|
60
|
|
|
|
|
61
|
|
|
return $promise->wait(); |
|
62
|
|
|
}); |
|
63
|
|
|
|
|
64
|
|
|
return $response; |
|
|
|
|
|
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
public function getAccessToken(): string |
|
68
|
|
|
{ |
|
69
|
|
|
return json_encode($this->accessToken); |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|
It seems like you are assigning to a variable which was imported through a
usestatement which was not imported by reference.For clarity, we suggest to use a different name or import by reference depending on whether you would like to have the change visibile in outer-scope.
Change not visible in outer-scope
Change visible in outer-scope