ArrayToJSONSerializer.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. namespace Elasticsearch\Serializers;
  3. use Elasticsearch\Common\Exceptions\RuntimeException;
  4. /**
  5. * Class JSONSerializer
  6. *
  7. * @category Elasticsearch
  8. * @package Elasticsearch\Serializers\JSONSerializer
  9. * @author Zachary Tong <zach@elastic.co>
  10. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache2
  11. * @link http://elastic.co
  12. */
  13. class ArrayToJSONSerializer implements SerializerInterface
  14. {
  15. /**
  16. * Serialize assoc array into JSON string
  17. *
  18. * @param string|array $data Assoc array to encode into JSON
  19. *
  20. * @return string
  21. */
  22. public function serialize($data)
  23. {
  24. if (is_string($data) === true) {
  25. return $data;
  26. } else {
  27. $data = json_encode($data, JSON_PRESERVE_ZERO_FRACTION);
  28. if ($data === false) {
  29. throw new RuntimeException("Failed to JSON encode: ".json_last_error());
  30. }
  31. if ($data === '[]') {
  32. return '{}';
  33. } else {
  34. return $data;
  35. }
  36. }
  37. }
  38. /**
  39. * Deserialize JSON into an assoc array
  40. *
  41. * @param string $data JSON encoded string
  42. * @param array $headers Response Headers
  43. *
  44. * @return array
  45. */
  46. public function deserialize($data, $headers)
  47. {
  48. return json_decode($data, true);
  49. }
  50. }