JsonConverter.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. declare(strict_types=1);
  7. namespace Magento\Analytics\Model\Connector\Http;
  8. use Magento\Framework\Serialize\Serializer\Json;
  9. /**
  10. * Represents JSON converter for http request and response body.
  11. */
  12. class JsonConverter implements ConverterInterface
  13. {
  14. /**
  15. * Content-Type HTTP header for json.
  16. * @deprecated
  17. * @see CONTENT_MEDIA_TYPE
  18. */
  19. const CONTENT_TYPE_HEADER = 'Content-Type: application/json';
  20. /**
  21. * Media-Type corresponding to this converter.
  22. */
  23. const CONTENT_MEDIA_TYPE = 'application/json';
  24. /**
  25. * @var Json
  26. */
  27. private $serializer;
  28. /**
  29. * @param Json $serializer
  30. */
  31. public function __construct(Json $serializer)
  32. {
  33. $this->serializer = $serializer;
  34. }
  35. /**
  36. * @param string $body
  37. *
  38. * @return array
  39. */
  40. public function fromBody($body)
  41. {
  42. $decodedBody = $this->serializer->unserialize($body);
  43. return $decodedBody === null ? [$body] : $decodedBody;
  44. }
  45. /**c
  46. * @param array $data
  47. *
  48. * @return string
  49. */
  50. public function toBody(array $data)
  51. {
  52. return $this->serializer->serialize($data);
  53. }
  54. /**
  55. * @return string
  56. */
  57. public function getContentTypeHeader()
  58. {
  59. return sprintf('Content-Type: %s', self::CONTENT_MEDIA_TYPE);
  60. }
  61. /**
  62. * @inheritdoc
  63. */
  64. public function getContentMediaType(): string
  65. {
  66. return self::CONTENT_MEDIA_TYPE;
  67. }
  68. }