From 7e958414223cdd14a8e46e5315dd772169fa2631 Mon Sep 17 00:00:00 2001 From: Lynh Date: Wed, 21 Feb 2024 10:23:15 +0700 Subject: [PATCH] Quickly configure middle (#27) --- src/ConnectorConfigurator.php | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/src/ConnectorConfigurator.php b/src/ConnectorConfigurator.php index 027556a..5ebdeae 100644 --- a/src/ConnectorConfigurator.php +++ b/src/ConnectorConfigurator.php @@ -10,6 +10,8 @@ use Fansipan\Middleware\RetryRequests; use Fansipan\Retry\Delay; use Fansipan\Retry\GenericRetryStrategy; +use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ResponseInterface; /** * @template T of ConnectorInterface @@ -38,6 +40,21 @@ final public function configure(ConnectorInterface $connector): ConnectorInterfa return $clone; } + /** + * Register a middleware configuration handler. + * + * @param callable(RequestInterface, callable): ResponseInterface $middleware + * @return static + */ + final public function middleware(callable $middleware, string $name = '') + { + return $this->register(static function (ConnectorInterface $connector) use ($middleware, $name) { + $connector->middleware()->unshift( + $middleware, $name + ); + }); + } + /** * Register a configuration handler. * @@ -84,13 +101,11 @@ public function followRedirects( bool $strict = false, bool $referer = false ) { - return $this->register(static function (ConnectorInterface $connector) use ($max, $protocols, $strict, $referer) { - $connector->middleware()->unshift(new FollowRedirects( - $max, - $protocols, - $strict, - $referer - ), 'follow_redirects'); - }); + return $this->middleware(new FollowRedirects( + $max, + $protocols, + $strict, + $referer + ), 'follow_redirects'); } }