Final Class Yiisoft\DataResponse\Formatter\JsonFormatter
| Inheritance | Yiisoft\DataResponse\Formatter\JsonFormatter |
|---|---|
| Implements | Yiisoft\DataResponse\Formatter\FormatterInterface |
Formatter that encodes data as JSON and sets appropriate response headers.
Public Methods
Method Details
| public __construct( string $contentType = 'application/json', string $encoding = 'UTF-8', integer $options = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ): mixed | ||
| $contentType | string |
The content type for the response. |
| $encoding | string |
The character encoding for the response. |
| $options | integer |
The JSON encoding options. |
public function __construct(
private readonly string $contentType = 'application/json',
private readonly string $encoding = 'UTF-8',
private readonly int $options = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE,
) {}
| public formatData( mixed $data ): string | ||
| $data | mixed | |
public function formatData(mixed $data): string
{
try {
return Json::encode($data, $this->options);
} catch (JsonException $e) {
throw new DataEncodingException($e->getMessage(), previous: $e);
}
}
| public formatResponse( \Psr\Http\Message\ResponseInterface $response ): \Psr\Http\Message\ResponseInterface | ||
| $response | \Psr\Http\Message\ResponseInterface | |
public function formatResponse(ResponseInterface $response): ResponseInterface
{
return $response->withHeader(Header::CONTENT_TYPE, "$this->contentType; charset=$this->encoding");
}
Signup or Login in order to comment.