Final Class Yiisoft\DataResponse\ResponseFactory\ContentNegotiatorResponseFactory
| Inheritance | Yiisoft\DataResponse\ResponseFactory\ContentNegotiatorResponseFactory |
|---|
Factory that selects a response factory based on the request's Accept header.
Public 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
| 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: |
| $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);
}
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 |
| $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);
}
Signup or Login in order to comment.