0 follower

Final Class Yiisoft\DataResponse\Middleware\ContentNegotiatorDataResponseMiddleware

InheritanceYiisoft\DataResponse\Middleware\ContentNegotiatorDataResponseMiddleware
ImplementsPsr\Http\Server\MiddlewareInterface

Middleware that selects a formatter for Yiisoft\DataResponse\DataStream\DataStream responses based on the request's Accept header and sets appropriate response headers.

Method Details

Hide inherited methods

__construct() public method

public __construct( Yiisoft\DataResponse\Formatter\FormatterInterface[] $formatters = [], Yiisoft\DataResponse\Formatter\FormatterInterface|\Psr\Http\Server\RequestHandlerInterface|null $fallback null ): mixed
$formatters Yiisoft\DataResponse\Formatter\FormatterInterface[]

Map of content types to formatters. For example: ['application/json' => new JsonFormatter(), 'application/xml' => new XmlFormatter()].

$fallback Yiisoft\DataResponse\Formatter\FormatterInterface|\Psr\Http\Server\RequestHandlerInterface|null

Formatter or request handler to use when no match is found. If null, the response is returned unmodified.

                public function __construct(
    private readonly array $formatters = [],
    private readonly FormatterInterface|RequestHandlerInterface|null $fallback = null,
) {
    $this->checkFormatters($formatters);
}

            
process() public method

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

                public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
    $accepted = HeaderValueHelper::getSortedAcceptTypes(
        $request->getHeader('Accept'),
    );
    $response = $handler->handle($request);
    $body = $response->getBody();
    if (!$body instanceof DataStream || $body->hasFormatter()) {
        return $response;
    }
    foreach ($accepted as $accept) {
        foreach ($this->formatters as $contentType => $formatter) {
            if (str_contains($accept, $contentType)) {
                $body->changeFormatter($formatter);
                return $formatter->formatResponse($response);
            }
        }
    }
    if ($this->fallback === null) {
        return $response;
    }
    if ($this->fallback instanceof RequestHandlerInterface) {
        return $this->fallback->handle($request);
    }
    $body->changeFormatter($this->fallback);
    return $this->fallback->formatResponse($response);
}