Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix for #1171 utf-16 issue in SmartSerializer #1179

Merged
merged 2 commits into from
Dec 6, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions src/Elasticsearch/Serializers/SmartSerializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

use Elasticsearch\Common\Exceptions;
use Elasticsearch\Common\Exceptions\Serializer\JsonErrorException;
use JsonException;

if (!defined('JSON_INVALID_UTF8_SUBSTITUTE')) {
//PHP < 7.2 Define it as 0 so it does nothing
Expand Down Expand Up @@ -84,9 +85,18 @@ private function decode(?string $data): array
try {
$result = json_decode($data, true, 512, JSON_THROW_ON_ERROR);
return $result;
} catch (\JsonException $e) {
$result = $result ?? [];
throw new JsonErrorException($e->getCode(), $data, $result);
} catch (JsonException $e) {
switch ($e->getCode()) {
case JSON_ERROR_UTF16:
try {
$data = str_replace('\\', '\\\\', $data);
$result = json_decode($data, true, 512, JSON_THROW_ON_ERROR);
return $result;
} catch (JsonException $e) {
throw new JsonErrorException($e->getCode(), $data, $result ?? []);
}
}
throw new JsonErrorException($e->getCode(), $data, $result ?? []);
}
}

Expand Down
14 changes: 14 additions & 0 deletions tests/Elasticsearch/Tests/Serializers/SmartSerializerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,18 @@ public function testThrowJsonErrorException()

$result = $this->serializer->deserialize('{ "foo" : bar" }', []);
}

/**
* Single unpaired UTF-16 surrogate in unicode escape
*
* @requires PHP 7.3
* @see https://github.com/elastic/elasticsearch-php/issues/1171
*/
public function testSingleUnpairedUTF16SurrogateInUnicodeEscape()
{
$json = '{ "data": "ud83d\ude4f" }';

$result = $this->serializer->deserialize($json, []);
$this->assertEquals($result['data'], 'ud83d\ude4f');
}
}