0 follower

Final Class Yiisoft\DataResponse\Middleware\ContentNegotiator

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

ContentNegotiator supports response format negotiation.

Method Details

Hide inherited methods

__construct() public method

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;
}

            
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 ($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;
}

            
withContentFormatters() public method

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;
}