88use Geocaching \Enum \Environment ;
99use Geocaching \Plugin \CircuitBreakerPlugin ;
1010use Geocaching \Plugin \GeocachingHttpLoggerPlugin ;
11+ use Geocaching \Plugin \StorageAwareAuthenticationPlugin ;
1112use Geocaching \Plugin \ReliabilityPlugin ;
1213use Geocaching \Plugin \RetryPlugin ;
1314use Geocaching \Reliability \CircuitBreaker ;
@@ -58,7 +59,7 @@ public function __construct(array $options = [])
5859 $ this ->getClientBuilder ()->setBaseUri ($ baseUri ->value );
5960
6061 $ this ->getClientBuilder ()->addPlugin (new BaseUriPlugin ($ this ->getUri ()));
61- $ this ->getClientBuilder ()-> addPlugin ( new AuthenticationPlugin ( new Bearer ( $ this -> getAccessToken ())) );
62+ $ this ->addAuthenticationPlugin ( );
6263 }
6364
6465 private function configureOptions (OptionsResolver $ resolver ): void
@@ -68,6 +69,8 @@ private function configureOptions(OptionsResolver $resolver): void
6869 [
6970 'client_builder ' => new ClientBuilder (),
7071 'uri_factory ' => Psr17FactoryDiscovery::findUriFactory (),
72+ 'token_storage ' => null ,
73+ 'reference_code ' => null ,
7174 ]
7275 );
7376
@@ -76,6 +79,8 @@ private function configureOptions(OptionsResolver $resolver): void
7679 $ resolver ->setAllowedTypes ('client_builder ' , ClientBuilder::class);
7780 $ resolver ->setAllowedTypes ('uri_factory ' , UriFactoryInterface::class);
7881 $ resolver ->setAllowedTypes ('uri ' , 'string ' );
82+ $ resolver ->setAllowedTypes ('token_storage ' , [TokenStorageInterface::class, 'null ' ]);
83+ $ resolver ->setAllowedTypes ('reference_code ' , ['string ' , 'null ' ]);
7984 }
8085
8186 public function getClientBuilder (): ClientBuilder
@@ -97,6 +102,31 @@ public function getAccessToken(): string
97102 {
98103 return $ this ->options ['access_token ' ];
99104 }
105+
106+ /**
107+ * Register an authentication plugin that always uses the freshest token.
108+ *
109+ * If a TokenStorage is provided, we pull the current token from storage so
110+ * retries after refresh use the updated access token. Otherwise we fall
111+ * back to a static Bearer token.
112+ */
113+ private function addAuthenticationPlugin (): void
114+ {
115+ $ storage = $ this ->options ['token_storage ' ];
116+ $ referenceCode = $ this ->options ['reference_code ' ];
117+
118+ if ($ storage && $ referenceCode ) {
119+ $ plugin = new StorageAwareAuthenticationPlugin (
120+ $ storage ,
121+ $ referenceCode ,
122+ $ this ->getAccessToken ()
123+ );
124+ } else {
125+ $ plugin = new AuthenticationPlugin (new Bearer ($ this ->getAccessToken ()));
126+ }
127+
128+ $ this ->getClientBuilder ()->addPlugin ($ plugin );
129+ }
100130
101131 /**
102132 * Enable HTTP logging for all API requests/responses with a pre-configured logger.
0 commit comments