Response.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. <?php
  2. namespace ModulesGarden\ProxmoxAddon\Core\UI\ResponseTemplates;
  3. use \ModulesGarden\ProxmoxAddon\Core\Helper;
  4. use \ModulesGarden\ProxmoxAddon\Core\ServiceLocator;
  5. /**
  6. * Abstract Ajax Response Model
  7. */
  8. abstract class Response
  9. {
  10. const STATUS_SUCCESS = 'success';
  11. const STATUS_ERROR = 'error';
  12. protected $status = self::STATUS_SUCCESS;
  13. protected $data = [];
  14. protected $message = null;
  15. protected $dataType = 'data';
  16. protected $callBackFunction = null;
  17. protected $refreshTargetId = [];
  18. protected $lang = null;
  19. public function __construct($data = [])
  20. {
  21. $this->data = $data;
  22. }
  23. public function setStatusSuccess()
  24. {
  25. $this->status = self::STATUS_SUCCESS;
  26. return $this;
  27. }
  28. public function setRefreshTargetIds(array $targetIds = [])
  29. {
  30. $this->refreshTargetId = $targetIds;
  31. return $this;
  32. }
  33. public function addRefreshTargetId($targetId)
  34. {
  35. if (in_array($targetId, $this->refreshTargetId, true) === false)
  36. {
  37. $this->refreshTargetId[] = $targetId;
  38. }
  39. return $this;
  40. }
  41. public function setStatusError()
  42. {
  43. $this->status = self::STATUS_ERROR;
  44. return $this;
  45. }
  46. public function setData($data)
  47. {
  48. $this->data = $data;
  49. return $this;
  50. }
  51. public function addData($key, $data)
  52. {
  53. $this->data[$key] = $data;
  54. return $this;
  55. }
  56. public function setCallBackFunction($name)
  57. {
  58. $this->callBackFunction = $name;
  59. return $this;
  60. }
  61. public function disableCallBackFunction()
  62. {
  63. $this->callBackFunction = null;
  64. return $this;
  65. }
  66. public function getData()
  67. {
  68. $return = [
  69. 'status' => $this->status,
  70. 'message' => $this->message,
  71. $this->dataType => $this->data,
  72. 'refreshIds' => $this->refreshTargetId
  73. ];
  74. if ($this->callBackFunction)
  75. {
  76. $return['callBackFunction'] = $this->callBackFunction;
  77. }
  78. return $return;
  79. }
  80. public function getFormatedResponse()
  81. {
  82. return Helper\json($this->getData())->setStatusCode(200);
  83. }
  84. public function setMessage($message)
  85. {
  86. $this->message = $message;
  87. return $this;
  88. }
  89. protected function loadLang()
  90. {
  91. if ($this->lang === null)
  92. {
  93. $this->lang = ServiceLocator::call('lang');
  94. }
  95. }
  96. public function setMessageAndTranslate($message)
  97. {
  98. $this->loadLang();
  99. $this->message = $this->lang->absoluteT($message);
  100. return $this;
  101. }
  102. }