JsonResponse.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. namespace ModulesGarden\Servers\ProxmoxCloudVps\Core\Http;
  3. use Symfony\Component\HttpFoundation\JsonResponse as SymfonyJsonResponse;
  4. use ModulesGarden\Servers\ProxmoxCloudVps\Core\ServiceLocator;
  5. use ModulesGarden\Servers\ProxmoxCloudVps\Core\Helper\Converter\Json;
  6. /**
  7. * Description of Json
  8. *
  9. * @author Rafał Ossowski <rafal.os@modulesgarden.com>
  10. */
  11. class JsonResponse extends SymfonyJsonResponse
  12. {
  13. protected $lang;
  14. public function setLang($lang)
  15. {
  16. $this->lang = $lang;
  17. return $this;
  18. }
  19. public function getLang()
  20. {
  21. return $this->lang;
  22. }
  23. public function setData($data = array())
  24. {
  25. try
  26. {
  27. return parent::setData($data);
  28. }
  29. catch (\Exception $e)
  30. {
  31. return parent::setData(Json::encodeUTF8($data));
  32. }
  33. }
  34. public function getData()
  35. {
  36. $data = null;
  37. if (defined('HHVM_VERSION'))
  38. {
  39. // HHVM does not trigger any warnings and let exceptions
  40. // thrown from a JsonSerializable object pass through.
  41. // If only PHP did the same...
  42. $data = json_decode($this->data, true, 512, $this->encodingOptions);
  43. }
  44. else
  45. {
  46. try
  47. {
  48. // PHP 5.4 and up wrap exceptions thrown by JsonSerializable
  49. // objects in a new exception that needs to be removed.
  50. // Fortunately, PHP 5.5 and up do not trigger any warning anymore.
  51. $data = json_decode($this->data, true, 512, $this->encodingOptions);
  52. }
  53. catch (\Exception $e)
  54. {
  55. if ('Exception' === get_class($e) && 0 === strpos($e->getMessage(), 'Failed calling '))
  56. {
  57. throw $e->getPrevious() ?: $e;
  58. }
  59. ServiceLocator::call('errorManager')->addError(self::class, $e->getMessage(), $e->getTrace());
  60. }
  61. }
  62. if (JSON_ERROR_NONE !== json_last_error())
  63. {
  64. throw new \InvalidArgumentException(json_last_error_msg());
  65. }
  66. return $data;
  67. }
  68. public function withSuccess($message = '')
  69. {
  70. $data = $this->getData();
  71. $data['status'] = 'success';
  72. $data['message'] = $message;
  73. $this->setData($data);
  74. return $this;
  75. }
  76. public function withError($message = '')
  77. {
  78. $data = $this->getData();
  79. $data['status'] = 'success';
  80. $data['message'] = $message;
  81. $this->setData($data);
  82. return $this;
  83. }
  84. }