JSONResponse.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCP\AppFramework\Http;
  8. use OCP\AppFramework\Http;
  9. /**
  10. * A renderer for JSON calls
  11. * @since 6.0.0
  12. * @template S of int
  13. * @template-covariant T of array|object|\stdClass|\JsonSerializable
  14. * @template H of array<string, mixed>
  15. * @template-extends Response<int, array<string, mixed>>
  16. */
  17. class JSONResponse extends Response {
  18. /**
  19. * response data
  20. * @var T
  21. */
  22. protected $data;
  23. /**
  24. * constructor of JSONResponse
  25. * @param T $data the object or array that should be transformed
  26. * @param S $statusCode the Http status code, defaults to 200
  27. * @param H $headers
  28. * @since 6.0.0
  29. */
  30. public function __construct(mixed $data = [], int $statusCode = Http::STATUS_OK, array $headers = []) {
  31. parent::__construct($statusCode, $headers);
  32. $this->data = $data;
  33. $this->addHeader('Content-Type', 'application/json; charset=utf-8');
  34. }
  35. /**
  36. * Returns the rendered json
  37. * @return string the rendered json
  38. * @since 6.0.0
  39. * @throws \Exception If data could not get encoded
  40. */
  41. public function render() {
  42. return json_encode($this->data, JSON_HEX_TAG | JSON_THROW_ON_ERROR);
  43. }
  44. /**
  45. * Sets values in the data json array
  46. * @psalm-suppress InvalidTemplateParam
  47. * @param T $data an array or object which will be transformed
  48. * to JSON
  49. * @return JSONResponse Reference to this object
  50. * @since 6.0.0 - return value was added in 7.0.0
  51. */
  52. public function setData($data) {
  53. $this->data = $data;
  54. return $this;
  55. }
  56. /**
  57. * @return T the data
  58. * @since 6.0.0
  59. */
  60. public function getData() {
  61. return $this->data;
  62. }
  63. }