. */ namespace SP\Http; use JsonException; use Klein\Response; use SP\Domain\Core\Exceptions\SPException; use SP\Domain\Html\Header; use SP\Domain\Http\JsonResponseInterface; use function SP\__u; /** * Class JsonResponse */ final class JsonResponse implements JsonResponseInterface { /** * Json constructor. */ public function __construct(private readonly Response $response) { } public static function factory(Response $response): JsonResponseInterface { return new self($response); } /** * Devuelve una respuesta en formato JSON * * @param string $data JSON string * * @return bool */ public function sendRaw(string $data): bool { return $this->response ->header(Header::CONTENT_TYPE->value, Header::CONTENT_TYPE_JSON->value) ->body($data) ->send(true) ->isSent(); } /** * Devuelve una respuesta en formato JSON con el estado y el mensaje. * * @param JsonMessage $jsonMessage * * @return bool * @throws SPException */ public function send(JsonMessage $jsonMessage): bool { $this->response->header(Header::CONTENT_TYPE->value, Header::CONTENT_TYPE_JSON->value); try { $this->response->body(self::buildJsonFrom($jsonMessage)); } catch (SPException $e) { $jsonMessage = new JsonMessage($e->getMessage()); $jsonMessage->addMessage($e->getHint()); $this->response->body(self::buildJsonFrom($jsonMessage)); } return $this->response->send(true)->isSent(); } /** * Devuelve una cadena en formato JSON * * @param mixed $data * @param int $flags JSON_* flags * * @return string * @throws SPException */ public static function buildJsonFrom(mixed $data, int $flags = 0): string { try { return json_encode($data, JSON_THROW_ON_ERROR | $flags); } catch (JsonException $e) { throw new SPException(__u('Encoding error'), SPException::ERROR, $e->getMessage()); } } }