PHP SDK middlewares
Middleware adds functionality to the requests and the responses in the PHP SDK.
You can add middleware when creating the PHP SDK client. Multiple middleware can be added using an array of middlewares.
MiddlewareFactory
The scope of this Factory pattern is to handle and customize the available middleware. The methods that are contained in this class are used to create an array of middlewares.
Default middleware
createDefaultMiddlewares creates an array with default values of OAuth Handler, Authentication, Logger, Retry and Correlation ID.
$authConfig = new ClientCredentialsConfig(new ClientCredentials($clientId, $clientSecret), ['handler' => $authHandler,]);$oauthHandler = OAuthHandlerFactory::ofAuthConfig($authConfig),$logger = new Logger('client', [new StreamHandler('./logs/requests.log')]);$maxRetries = 3;$correlationIdProvider = new DefaultCorrelationIdProvider();$middlewares = MiddlewareFactory::createDefaultMiddlewares($oauthHandler,$logger,$maxRetries,$correlationIdProvider);
CorrelationIdMiddleware
createCorrelationIdMiddleware creates a middleware that adds a correlation ID to the headers of HTTP requests.
$correlationIdProvider = new DefaultCorrelationIdProvider();$correlationIdMiddleware = MiddlewareFactory::createCorrelationIdMiddleware($correlationIdProvider);
RetryNAMiddleware
createRetryNAMiddleware creates middleware that retries HTTP requests under certain conditions.
$maxRetries = 3;$retryMiddleware = MiddlewareFactory::createRetryNAMiddleware($maxRetries);
OAuthHandlerMiddleware
createMiddlewareForOAuthHandler creates a middleware for handling OAuth2 authentication, ensuring necessary OAuth credentials are included.
$tokenProvider = new YourTokenProvider();$oauthHandler = OAuthHandlerFactory::ofProvider($tokenProvider),$oauthMiddleware = MiddlewareFactory::createMiddlewareForOAuthHandler($oauthHandler);
LoggerMiddleware
createLoggerMiddleware creates a middleware for logging HTTP requests and responses.
$logger = new Logger('auth');$logger->pushHandler(new StreamHandler('./logs/requests.log', Logger::DEBUG));$loggerMiddleware = MiddlewareFactory::createLoggerMiddleware($logger);
ReauthenticateMiddleware
createReauthenticateMiddleware creates a middleware that automatically reauthenticates HTTP requests when an invalid token error (HTTP 401) is encountered. It uses an OAuth2Handler to refresh the token and retry the request up to a specified number of times.
$maxRetries = 3;$authConfig = new ClientCredentialsConfig(new ClientCredentials($clientId, $clientSecret), ['handler' => $authHandler,]);$oauthHandler = OAuthHandlerFactory::ofAuthConfig($authConfig),//$maxRetries is optional. If not specified, a default value of 1 is used$reauthMiddleware = MiddlewareFactory::createReauthenticateMiddleware($oauthHandler, $maxRetries);