15
15
*/
16
16
class AuthenticationPlugin implements Plugin
17
17
{
18
+ const RETRY_LIMIT = 2 ;
19
+
18
20
/**
19
21
* @var array
20
22
*/
@@ -25,6 +27,13 @@ class AuthenticationPlugin implements Plugin
25
27
*/
26
28
private $ authenticator ;
27
29
30
+ /**
31
+ * Store the retry counter for each request.
32
+ *
33
+ * @var array
34
+ */
35
+ private $ retryStorage = [];
36
+
28
37
public function __construct (Authenticator $ authenticator , string $ accessToken )
29
38
{
30
39
$ this ->authenticator = $ authenticator ;
@@ -33,13 +42,24 @@ public function __construct(Authenticator $authenticator, string $accessToken)
33
42
34
43
public function handleRequest (RequestInterface $ request , callable $ next , callable $ first )
35
44
{
36
- $ header = \sprintf ('Bearer %s ' , $ this ->accessToken ['access_token ' ]);
45
+ if (null === $ this ->accessToken ) {
46
+ return $ next ($ request );
47
+ }
48
+
49
+ $ chainIdentifier = \spl_object_hash ((object ) $ first );
50
+ $ header = \sprintf ('Bearer %s ' , $ this ->accessToken ['access_token ' ] ?? '' );
37
51
$ request = $ request ->withHeader ('Authorization ' , $ header );
38
52
39
53
$ promise = $ next ($ request );
40
54
41
- return $ promise ->then (function (ResponseInterface $ response ) use ($ request , $ next , $ first ) {
42
- if (401 !== $ response ->getStatusCode ()) {
55
+ return $ promise ->then (function (ResponseInterface $ response ) use ($ request , $ next , $ first , $ chainIdentifier ) {
56
+ if (!\array_key_exists ($ chainIdentifier , $ this ->retryStorage )) {
57
+ $ this ->retryStorage [$ chainIdentifier ] = 0 ;
58
+ }
59
+
60
+ if (401 !== $ response ->getStatusCode () || $ this ->retryStorage [$ chainIdentifier ] >= self ::RETRY_LIMIT ) {
61
+ unset($ this ->retryStorage [$ chainIdentifier ]);
62
+
43
63
return $ response ;
44
64
}
45
65
@@ -56,6 +76,7 @@ public function handleRequest(RequestInterface $request, callable $next, callabl
56
76
$ request = $ request ->withHeader ('Authorization ' , $ header );
57
77
58
78
// Retry
79
+ ++$ this ->retryStorage [$ chainIdentifier ];
59
80
$ promise = $ this ->handleRequest ($ request , $ next , $ first );
60
81
61
82
return $ promise ->wait ();
0 commit comments