1515 */
1616class AuthenticationPlugin implements Plugin
1717{
18+ const RETRY_LIMIT = 2 ;
19+
1820 /**
1921 * @var array
2022 */
@@ -25,6 +27,13 @@ class AuthenticationPlugin implements Plugin
2527 */
2628 private $ authenticator ;
2729
30+ /**
31+ * Store the retry counter for each request.
32+ *
33+ * @var array
34+ */
35+ private $ retryStorage = [];
36+
2837 public function __construct (Authenticator $ authenticator , string $ accessToken )
2938 {
3039 $ this ->authenticator = $ authenticator ;
@@ -33,13 +42,24 @@ public function __construct(Authenticator $authenticator, string $accessToken)
3342
3443 public function handleRequest (RequestInterface $ request , callable $ next , callable $ first )
3544 {
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 ' ] ?? '' );
3751 $ request = $ request ->withHeader ('Authorization ' , $ header );
3852
3953 $ promise = $ next ($ request );
4054
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+
4363 return $ response ;
4464 }
4565
@@ -56,6 +76,7 @@ public function handleRequest(RequestInterface $request, callable $next, callabl
5676 $ request = $ request ->withHeader ('Authorization ' , $ header );
5777
5878 // Retry
79+ ++$ this ->retryStorage [$ chainIdentifier ];
5980 $ promise = $ this ->handleRequest ($ request , $ next , $ first );
6081
6182 return $ promise ->wait ();
0 commit comments