JSONResponse.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Lukas Reschke <lukas@statuscode.ch>
  8. * @author Morris Jobke <hey@morrisjobke.de>
  9. * @author Roeland Jago Douma <roeland@famdouma.nl>
  10. * @author Thomas Müller <thomas.mueller@tmit.eu>
  11. * @author Thomas Tanghus <thomas@tanghus.net>
  12. *
  13. * @license AGPL-3.0
  14. *
  15. * This code is free software: you can redistribute it and/or modify
  16. * it under the terms of the GNU Affero General Public License, version 3,
  17. * as published by the Free Software Foundation.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU Affero General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU Affero General Public License, version 3,
  25. * along with this program. If not, see <http://www.gnu.org/licenses/>
  26. *
  27. */
  28. namespace OCP\AppFramework\Http;
  29. use OCP\AppFramework\Http;
  30. /**
  31. * A renderer for JSON calls
  32. * @since 6.0.0
  33. */
  34. class JSONResponse extends Response {
  35. /**
  36. * response data
  37. * @var array|object
  38. */
  39. protected $data;
  40. /**
  41. * constructor of JSONResponse
  42. * @param array|object $data the object or array that should be transformed
  43. * @param int $statusCode the Http status code, defaults to 200
  44. * @since 6.0.0
  45. */
  46. public function __construct($data = [], $statusCode = Http::STATUS_OK) {
  47. parent::__construct();
  48. $this->data = $data;
  49. $this->setStatus($statusCode);
  50. $this->addHeader('Content-Type', 'application/json; charset=utf-8');
  51. }
  52. /**
  53. * Returns the rendered json
  54. * @return string the rendered json
  55. * @since 6.0.0
  56. * @throws \Exception If data could not get encoded
  57. */
  58. public function render() {
  59. return json_encode($this->data, JSON_HEX_TAG | JSON_THROW_ON_ERROR);
  60. }
  61. /**
  62. * Sets values in the data json array
  63. * @param array|object $data an array or object which will be transformed
  64. * to JSON
  65. * @return JSONResponse Reference to this object
  66. * @since 6.0.0 - return value was added in 7.0.0
  67. */
  68. public function setData($data) {
  69. $this->data = $data;
  70. return $this;
  71. }
  72. /**
  73. * Used to get the set parameters
  74. * @return array the data
  75. * @since 6.0.0
  76. */
  77. public function getData() {
  78. return $this->data;
  79. }
  80. }