Final Class Yiisoft\DataResponse\ResponseFactory\ContentNegotiatorResponseFactory
| Inheritance | Yiisoft\ |
|---|
Factory that selects a response factory based on the request's Accept header.
Public Methods
| Method | Description | Defined By |
|---|---|---|
| __construct() | Yiisoft\ |
|
| createResponse() | Creates an HTTP response using a factory selected based on the request's Accept header. |
Yiisoft\ |
Method Details
| public mixed __construct ( Yiisoft\ | ||
| $factories | Yiisoft\ |
Map of content types to factories.
For example: |
| $fallback | Yiisoft\ |
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 \ | ||
| $request | \ |
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 | \ |
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);
}
User Contributed Notes
Leave a comment
Join the conversation to share a note.