0 follower

Final Class Yiisoft\DataResponse\ResponseFactory\ContentNegotiatorResponseFactory

InheritanceYiisoft\DataResponse\ResponseFactory\ContentNegotiatorResponseFactory

Factory that selects a response factory based on the request's Accept header.

Public Methods

Hide inherited methods

Method Description Defined By
__construct() Yiisoft\DataResponse\ResponseFactory\ContentNegotiatorResponseFactory
createResponse() Creates an HTTP response using a factory selected based on the request's Accept header. Yiisoft\DataResponse\ResponseFactory\ContentNegotiatorResponseFactory

Method Details

Hide inherited methods

__construct() public method

public __construct( Yiisoft\DataResponse\ResponseFactory\DataResponseFactoryInterface[] $factories, Yiisoft\DataResponse\ResponseFactory\DataResponseFactoryInterface|\Psr\Http\Server\RequestHandlerInterface $fallback ): mixed
$factories Yiisoft\DataResponse\ResponseFactory\DataResponseFactoryInterface[]

Map of content types to factories. For example: ['application/json' => $jsonFactory, 'application/xml' => $xmlFactory].

$fallback Yiisoft\DataResponse\ResponseFactory\DataResponseFactoryInterface|\Psr\Http\Server\RequestHandlerInterface

Factory or request handler to use when no match is found.

                public function __construct(
    private readonly array $factories,
    private readonly DataResponseFactoryInterface|RequestHandlerInterface $fallback,
) {
    $this->checkFactories($factories);
}

            
createResponse() public method

Creates an HTTP response using a factory selected based on the request's Accept header.

public createResponse( \Psr\Http\Message\ServerRequestInterface $request, mixed $data null, integer $code Status::OK, string $reasonPhrase '' ): \Psr\Http\Message\ResponseInterface
$request \Psr\Http\Message\ServerRequestInterface

The request to extract the Accept header from.

$data mixed

The response data to be included in the response body.

$code integer

The HTTP status code for the response.

$reasonPhrase string

The reason phrase associated with the status code.

return \Psr\Http\Message\ResponseInterface

The created HTTP response.

                public function createResponse(
    ServerRequestInterface $request,
    mixed $data = null,
    int $code = Status::OK,
    string $reasonPhrase = '',
): ResponseInterface {
    $accepted = HeaderValueHelper::getSortedAcceptTypes(
        $request->getHeader('Accept'),
    );
    foreach ($accepted as $accept) {
        foreach ($this->factories as $contentType => $factory) {
            if (str_contains($accept, $contentType)) {
                return $factory->createResponse($data, $code, $reasonPhrase);
            }
        }
    }
    if ($this->fallback instanceof RequestHandlerInterface) {
        return $this->fallback->handle($request);
    }
    return $this->fallback->createResponse($data, $code, $reasonPhrase);
}