SmartSerializer.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace Elasticsearch\Serializers;
  3. use Elasticsearch\Common\Exceptions;
  4. use Elasticsearch\Common\Exceptions\Serializer\JsonErrorException;
  5. /**
  6. * Class SmartSerializer
  7. *
  8. * @category Elasticsearch
  9. * @package Elasticsearch\Serializers\JSONSerializer
  10. * @author Zachary Tong <zach@elastic.co>
  11. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache2
  12. * @link http://elastic.co
  13. */
  14. class SmartSerializer implements SerializerInterface
  15. {
  16. /**
  17. * Serialize assoc array into JSON string
  18. *
  19. * @param string|array $data Assoc array to encode into JSON
  20. *
  21. * @return string
  22. */
  23. public function serialize($data)
  24. {
  25. if (is_string($data) === true) {
  26. return $data;
  27. } else {
  28. $data = json_encode($data, JSON_PRESERVE_ZERO_FRACTION);
  29. if ($data === false) {
  30. throw new Exceptions\RuntimeException("Failed to JSON encode: ".json_last_error());
  31. }
  32. if ($data === '[]') {
  33. return '{}';
  34. } else {
  35. return $data;
  36. }
  37. }
  38. }
  39. /**
  40. * Deserialize by introspecting content_type. Tries to deserialize JSON,
  41. * otherwise returns string
  42. *
  43. * @param string $data JSON encoded string
  44. * @param array $headers Response Headers
  45. *
  46. * @throws JsonErrorException
  47. * @return array
  48. */
  49. public function deserialize($data, $headers)
  50. {
  51. if (isset($headers['content_type']) === true) {
  52. if (strpos($headers['content_type'], 'json') !== false) {
  53. return $this->decode($data);
  54. } else {
  55. //Not json, return as string
  56. return $data;
  57. }
  58. } else {
  59. //No content headers, assume json
  60. return $this->decode($data);
  61. }
  62. }
  63. /**
  64. * @todo For 2.0, remove the E_NOTICE check before raising the exception.
  65. *
  66. * @param $data
  67. *
  68. * @return array
  69. * @throws JsonErrorException
  70. */
  71. private function decode($data)
  72. {
  73. if ($data === null || strlen($data) === 0) {
  74. return "";
  75. }
  76. $result = @json_decode($data, true);
  77. // Throw exception only if E_NOTICE is on to maintain backwards-compatibility on systems that silently ignore E_NOTICEs.
  78. if (json_last_error() !== JSON_ERROR_NONE && (error_reporting() & E_NOTICE) === E_NOTICE) {
  79. $e = new JsonErrorException(json_last_error(), $data, $result);
  80. throw $e;
  81. }
  82. return $result;
  83. }
  84. }