EverythingToJSONSerializer.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. namespace Elasticsearch\Serializers;
  3. use Elasticsearch\Common\Exceptions\RuntimeException;
  4. /**
  5. * Class EverythingToJSONSerializer
  6. *
  7. * @category Elasticsearch
  8. * @package Elasticsearch\Serializers
  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 EverythingToJSONSerializer 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. $data = json_encode($data, JSON_PRESERVE_ZERO_FRACTION);
  25. if ($data === false) {
  26. throw new RuntimeException("Failed to JSON encode: ".json_last_error());
  27. }
  28. if ($data === '[]') {
  29. return '{}';
  30. } else {
  31. return $data;
  32. }
  33. }
  34. /**
  35. * Deserialize JSON into an assoc array
  36. *
  37. * @param string $data JSON encoded string
  38. * @param array $headers Response headers
  39. *
  40. * @return array
  41. */
  42. public function deserialize($data, $headers)
  43. {
  44. return json_decode($data, true);
  45. }
  46. }