Final Class Yiisoft\DataResponse\Middleware\ContentNegotiatorDataResponseMiddleware
| Inheritance | Yiisoft\DataResponse\Middleware\ContentNegotiatorDataResponseMiddleware |
|---|---|
| Implements | Psr\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.
Public Methods
| Method | Description | Defined By |
|---|---|---|
| __construct() | Yiisoft\DataResponse\Middleware\ContentNegotiatorDataResponseMiddleware | |
| process() | Yiisoft\DataResponse\Middleware\ContentNegotiatorDataResponseMiddleware |
Method Details
| 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: |
| $fallback | Yiisoft\DataResponse\Formatter\FormatterInterface|\Psr\Http\Server\RequestHandlerInterface|null |
Formatter or request handler
to use when no match is found. If |
public function __construct(
private readonly array $formatters = [],
private readonly FormatterInterface|RequestHandlerInterface|null $fallback = null,
) {
$this->checkFormatters($formatters);
}
| 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);
}
Signup or Login in order to comment.