Skip to content

Commit

Permalink
Add opt-in for ignoring JSON_PRESERVE_ZERO_FRACTION when serializing
Browse files Browse the repository at this point in the history
  • Loading branch information
polyfractal committed Feb 2, 2017
1 parent 7d1b0ec commit e34fdfd
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
15 changes: 15 additions & 0 deletions src/Elasticsearch/ClientBuilder.php
Expand Up @@ -89,6 +89,9 @@ class ClientBuilder
/** @var null|bool|string */
private $sslVerification = null;

/** @var bool */
private $allowBadJSON = false;

/**
* @return ClientBuilder
*/
Expand Down Expand Up @@ -395,11 +398,23 @@ public function setSSLVerification($value = true)
return $this;
}

public function allowBadJSONSerialization()
{
$this->allowBadJSON = true;
}

/**
* @return Client
*/
public function build()
{
if(!defined('JSON_PRESERVE_ZERO_FRACTION') && $this->allowBadJSON === false) {
throw new RuntimeException("Your version of PHP / json-ext does not support the constant 'JSON_PRESERVE_ZERO_FRACTION',".
" which is important for proper type mapping in Elasticsearch. Please upgrade your PHP or json-ext.\n".
"If you are unable to upgrade, and are willing to accept the consequences, you may use the allowBadJSONSerialization()".
" method on the ClientBuilder to bypass this limitation.");
}

$this->buildLoggers();

if (is_null($this->handler)) {
Expand Down
13 changes: 12 additions & 1 deletion src/Elasticsearch/Serializers/SmartSerializer.php
Expand Up @@ -15,6 +15,13 @@
*/
class SmartSerializer implements SerializerInterface
{
private $PHP_VERSION;

public function __construct()
{
$this->PHP_VERSION = phpversion();
}

/**
* Serialize assoc array into JSON string
*
Expand All @@ -27,7 +34,11 @@ public function serialize($data)
if (is_string($data) === true) {
return $data;
} else {
$data = json_encode($data, JSON_PRESERVE_ZERO_FRACTION);
if (version_compare($this->PHP_VERSION, '5.6.6', '<') || ! defined('JSON_PRESERVE_ZERO_FRACTION')) {
$data = json_encode($data);
} else {
$data = json_encode($data, JSON_PRESERVE_ZERO_FRACTION);
}
if ($data === '[]') {
return '{}';
} else {
Expand Down

0 comments on commit e34fdfd

Please sign in to comment.