Json.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\Controller\Result;
  7. use Magento\Framework\App\Response\HttpInterface as HttpResponseInterface;
  8. use Magento\Framework\Controller\AbstractResult;
  9. use Magento\Framework\Translate\InlineInterface;
  10. /**
  11. * A possible implementation of JSON response type (instead of hardcoding json_encode() all over the place)
  12. * Actual for controller actions that serve ajax requests
  13. *
  14. * @api
  15. * @since 100.0.2
  16. */
  17. class Json extends AbstractResult
  18. {
  19. /**
  20. * @var \Magento\Framework\Translate\InlineInterface
  21. */
  22. protected $translateInline;
  23. /**
  24. * @var string
  25. */
  26. protected $json;
  27. /**
  28. * @var \Magento\Framework\Serialize\Serializer\Json
  29. */
  30. private $serializer;
  31. /**
  32. * @param \Magento\Framework\Translate\InlineInterface $translateInline
  33. * @param \Magento\Framework\Serialize\Serializer\Json $serializer
  34. */
  35. public function __construct(
  36. InlineInterface $translateInline,
  37. \Magento\Framework\Serialize\Serializer\Json $serializer = null
  38. ) {
  39. $this->translateInline = $translateInline;
  40. $this->serializer = $serializer ?: \Magento\Framework\App\ObjectManager::getInstance()
  41. ->get(\Magento\Framework\Serialize\Serializer\Json::class);
  42. }
  43. /**
  44. * Set json data
  45. *
  46. * @param mixed $data
  47. * @param boolean $cycleCheck Optional; whether or not to check for object recursion; off by default
  48. * @param array $options Additional options used during encoding
  49. * @return $this
  50. * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  51. */
  52. public function setData($data, $cycleCheck = false, $options = [])
  53. {
  54. if ($data instanceof \Magento\Framework\DataObject) {
  55. $data = $data->toArray();
  56. }
  57. $this->json = $this->serializer->serialize($data);
  58. return $this;
  59. }
  60. /**
  61. * @param string $jsonData
  62. * @return $this
  63. */
  64. public function setJsonData($jsonData)
  65. {
  66. $this->json = (string)$jsonData;
  67. return $this;
  68. }
  69. /**
  70. * {@inheritdoc}
  71. */
  72. protected function render(HttpResponseInterface $response)
  73. {
  74. $this->translateInline->processResponseBody($this->json, true);
  75. $response->setHeader('Content-Type', 'application/json', true);
  76. $response->setBody($this->json);
  77. return $this;
  78. }
  79. }