Final Class Yiisoft\DataResponse\Middleware\ContentNegotiator
| Inheritance | Yiisoft\DataResponse\Middleware\ContentNegotiator |
|---|---|
| Implements | Psr\Http\Server\MiddlewareInterface |
ContentNegotiator supports response format negotiation.
Public Methods
| Method | Description | Defined By |
|---|---|---|
| __construct() | Yiisoft\DataResponse\Middleware\ContentNegotiator | |
| process() | Yiisoft\DataResponse\Middleware\ContentNegotiator | |
| withContentFormatters() | Returns a new instance with the specified content formatters. | Yiisoft\DataResponse\Middleware\ContentNegotiator |
Method Details
| public mixed __construct ( array $contentFormatters ) | ||
| $contentFormatters | array |
The array key is the content type, and the value is an instance of {@see \Yiisoft\DataResponse\DataResponseFormatterInterface}. |
public function __construct(array $contentFormatters)
{
$this->checkFormatters($contentFormatters);
$this->contentFormatters = $contentFormatters;
}
| 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 ($response instanceof DataResponse && !$response->hasResponseFormatter()) {
$accepted = $request->getHeader(Header::ACCEPT);
foreach ($accepted as $accept) {
foreach ($this->contentFormatters as $contentType => $formatter) {
if (str_contains($accept, $contentType)) {
return $response->withResponseFormatter($formatter);
}
}
}
}
return $response;
}
Returns a new instance with the specified content formatters.
| public self withContentFormatters ( array $contentFormatters ) | ||
| $contentFormatters | array |
The array key is the content type, and the value is an instance of {@see \Yiisoft\DataResponse\DataResponseFormatterInterface}. |
public function withContentFormatters(array $contentFormatters): self
{
$this->checkFormatters($contentFormatters);
$new = clone $this;
$new->contentFormatters = $contentFormatters;
return $new;
}
Signup or Login in order to comment.