0 follower

Final Class Yiisoft\DataResponse\Formatter\JsonFormatter

InheritanceYiisoft\DataResponse\Formatter\JsonFormatter
ImplementsYiisoft\DataResponse\Formatter\FormatterInterface

Formatter that encodes data as JSON and sets appropriate response headers.

Method Details

Hide inherited methods

__construct() public method

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,
) {}

            
formatData() public method

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

            
formatResponse() public method

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