JSONResponse.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. * Additional `json_encode` flags
  25. * @var int
  26. */
  27. protected $encodeFlags;
  28. /**
  29. * constructor of JSONResponse
  30. * @param T $data the object or array that should be transformed
  31. * @param S $statusCode the Http status code, defaults to 200
  32. * @param H $headers
  33. * @param int $encodeFlags Additional `json_encode` flags
  34. * @since 6.0.0
  35. * @since 30.0.0 Added `$encodeFlags` param
  36. */
  37. public function __construct(
  38. mixed $data = [],
  39. int $statusCode = Http::STATUS_OK,
  40. array $headers = [],
  41. int $encodeFlags = 0,
  42. ) {
  43. parent::__construct($statusCode, $headers);
  44. $this->data = $data;
  45. $this->encodeFlags = $encodeFlags;
  46. $this->addHeader('Content-Type', 'application/json; charset=utf-8');
  47. }
  48. /**
  49. * Returns the rendered json
  50. * @return string the rendered json
  51. * @since 6.0.0
  52. * @throws \Exception If data could not get encoded
  53. */
  54. public function render() {
  55. return json_encode($this->data, JSON_HEX_TAG | JSON_THROW_ON_ERROR | $this->encodeFlags, 2048);
  56. }
  57. /**
  58. * Sets values in the data json array
  59. * @psalm-suppress InvalidTemplateParam
  60. * @param T $data an array or object which will be transformed
  61. * to JSON
  62. * @return JSONResponse Reference to this object
  63. * @since 6.0.0 - return value was added in 7.0.0
  64. */
  65. public function setData($data) {
  66. $this->data = $data;
  67. return $this;
  68. }
  69. /**
  70. * @return T the data
  71. * @since 6.0.0
  72. */
  73. public function getData() {
  74. return $this->data;
  75. }
  76. }