phasync
HttpClient / addMiddlewareFunction

Method

HttpClient::addMiddlewareFunction

Wrap HttpClient::sendRequest in a function that can change the request or the response.

Description#

public HttpClient::addMiddlewareFunction(
    Closure $middleware
): void

Every request goes through the middleware, including those from get(), post(), put() and request(). Each middleware wraps every one added before it, so the last one added is the outermost: it runs first, and its $next calls the previous one, down to the client's own request handling. A middleware that does not call $next answers the request itself.

Calling $next->sendRequest() returns the response before its transfer has started, unlike the client's own sendRequest(): a failure is thrown when the middleware, or the caller, first reads the status, the headers or the body, so a middleware that handles failures reads the status itself. The client's sendRequest() waits for the headers after the middleware chain has returned.

Parameters#

$middleware Closure

Examples#

Example 1A header and a log line for every request
use phasync\HttpClient\HttpClient;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

$base   = require __DIR__ . '/../server.php';
$client = new HttpClient();

$client->addMiddlewareFunction(function (RequestInterface $request, ClientInterface $next): ResponseInterface {
    return $next->sendRequest($request->withHeader('X-Request-Id', 'req-1'));
});
// Added last, so it runs first: it sees the request before the header is added
$client->addMiddlewareFunction(function (RequestInterface $request, ClientInterface $next): ResponseInterface {
    $response = $next->sendRequest($request);
    echo 'log: ', $request->getMethod(), ' ', $request->getUri()->getPath(), ' -> ', $response->getStatusCode(), "\n";

    return $response;
});

$echo = json_decode((string) $client->get("$base/echo")->getBody(), true);
echo 'the server got X-Request-Id: ', $echo['headers']['x-request-id'], "\n";
Output
log: GET /echo -> 200
the server got X-Request-Id: req-1
Example 2
$client->addMiddlewareFunction(
    function (RequestInterface $request, ClientInterface $next): ResponseInterface {
        return $next->sendRequest($request->withHeader('X-Request-Id', \bin2hex(\random_bytes(8))));
    }
);

See also#