Skip to content

Commit e34fdfd

Browse files
committed
Add opt-in for ignoring JSON_PRESERVE_ZERO_FRACTION when serializing
1 parent 7d1b0ec commit e34fdfd

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

src/Elasticsearch/ClientBuilder.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,9 @@ class ClientBuilder
8989
/** @var null|bool|string */
9090
private $sslVerification = null;
9191

92+
/** @var bool */
93+
private $allowBadJSON = false;
94+
9295
/**
9396
* @return ClientBuilder
9497
*/
@@ -395,11 +398,23 @@ public function setSSLVerification($value = true)
395398
return $this;
396399
}
397400

401+
public function allowBadJSONSerialization()
402+
{
403+
$this->allowBadJSON = true;
404+
}
405+
398406
/**
399407
* @return Client
400408
*/
401409
public function build()
402410
{
411+
if(!defined('JSON_PRESERVE_ZERO_FRACTION') && $this->allowBadJSON === false) {
412+
throw new RuntimeException("Your version of PHP / json-ext does not support the constant 'JSON_PRESERVE_ZERO_FRACTION',".
413+
" which is important for proper type mapping in Elasticsearch. Please upgrade your PHP or json-ext.\n".
414+
"If you are unable to upgrade, and are willing to accept the consequences, you may use the allowBadJSONSerialization()".
415+
" method on the ClientBuilder to bypass this limitation.");
416+
}
417+
403418
$this->buildLoggers();
404419

405420
if (is_null($this->handler)) {

src/Elasticsearch/Serializers/SmartSerializer.php

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,13 @@
1515
*/
1616
class SmartSerializer implements SerializerInterface
1717
{
18+
private $PHP_VERSION;
19+
20+
public function __construct()
21+
{
22+
$this->PHP_VERSION = phpversion();
23+
}
24+
1825
/**
1926
* Serialize assoc array into JSON string
2027
*
@@ -27,7 +34,11 @@ public function serialize($data)
2734
if (is_string($data) === true) {
2835
return $data;
2936
} else {
30-
$data = json_encode($data, JSON_PRESERVE_ZERO_FRACTION);
37+
if (version_compare($this->PHP_VERSION, '5.6.6', '<') || ! defined('JSON_PRESERVE_ZERO_FRACTION')) {
38+
$data = json_encode($data);
39+
} else {
40+
$data = json_encode($data, JSON_PRESERVE_ZERO_FRACTION);
41+
}
3142
if ($data === '[]') {
3243
return '{}';
3344
} else {

0 commit comments

Comments
 (0)