0

Final Class Yiisoft\HttpMiddleware\ContentLengthMiddleware

InheritanceYiisoft\HttpMiddleware\ContentLengthMiddleware
ImplementsPsr\Http\Server\MiddlewareInterface

Configurable middleware that adds or removes the Content-Length header from the response.

See also https://datatracker.ietf.org/doc/html/rfc9110#section-8.6.

Method Details

Hide inherited methods

__construct() public method

public mixed __construct ( boolean $removeOnTransferEncoding = true, boolean $add = true, array $doNotAddOnStatusCode = [
    
100,
    
// Continue
    
101,
    
// Switching Protocols
    
102,
    
// Processing
    
103,
    
// Early Hints
    
204,
    
// No Content
    
205,
    
// Reset Content
    
304,
]
, array $removeOnStatusCode = [
    
100,
    
// Continue
    
101,
    
// Switching Protocols
    
102,
    
// Processing
    
103,
    
// Early Hints
    
204,
    
// No Content
    
205,
]
)
$removeOnTransferEncoding boolean

Whether to remove the Content-Length header if Transfer-Encoding header is present.

$add boolean

Whether to add the Content-Length header if not present.

$doNotAddOnStatusCode array

List of HTTP status codes where Content-Length header should not be added.

$removeOnStatusCode array

List of HTTP status codes for which an already present Content-Length header should be removed.

                public function __construct(
    private readonly bool $removeOnTransferEncoding = true,
    private readonly bool $add = true,
    private readonly array $doNotAddOnStatusCode = [
        100, // Continue
        101, // Switching Protocols
        102, // Processing
        103, // Early Hints
        204, // No Content
        205, // Reset Content
        304, // Not Modified
    ],
    private readonly array $removeOnStatusCode = [
        100, // Continue
        101, // Switching Protocols
        102, // Processing
        103, // Early Hints
        204, // No Content
        205, // Reset Content
    ],
) {}

            
process() public method

public \Psr\Http\Message\ResponseInterface process ( \Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Server\RequestHandlerInterface $handler )
$request \Psr\Http\Message\ServerRequestInterface
$handler \Psr\Http\Server\RequestHandlerInterface

                public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
    $response = $handler->handle($request);
    if ($this->shouldRemoveContentLength($response)) {
        return $response->withoutHeader('Content-Length');
    }
    if ($this->shouldSkipContentLength($response)) {
        return $response;
    }
    return $this->addContentLength($response);
}