RestResponse.php 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Class RestApiResponse.
  5. */
  6. class RestResponse
  7. {
  8. /**
  9. * @var bool
  10. */
  11. private $error;
  12. /**
  13. * @var string
  14. */
  15. private $errorMessage;
  16. /**
  17. * @var array
  18. */
  19. private $data;
  20. /**
  21. * RestApiResponse constructor.
  22. */
  23. public function __construct()
  24. {
  25. $this->error = true;
  26. $this->errorMessage = null;
  27. $this->data = [];
  28. }
  29. /**
  30. * @param array $data
  31. */
  32. public function setData(array $data)
  33. {
  34. $this->error = false;
  35. $this->data = $data;
  36. }
  37. /**
  38. * @param string $message
  39. */
  40. public function setErrorMessage($message)
  41. {
  42. $this->error = true;
  43. $this->errorMessage = $message;
  44. }
  45. /**
  46. * @return string
  47. */
  48. public function format()
  49. {
  50. $json = ['error' => $this->error];
  51. if ($this->error) {
  52. $json['message'] = $this->errorMessage;
  53. } else {
  54. $json['data'] = $this->data;
  55. }
  56. return json_encode($json, JSON_PRETTY_PRINT);
  57. }
  58. }