Skip to content

Commit

Permalink
JSONType: throw on invalid UTF-8 string; avoid escaping Unicode chara…
Browse files Browse the repository at this point in the history
…cters by default (and provide an option)
  • Loading branch information
Rasmus Schultz committed Jul 21, 2016
1 parent 79699f6 commit 13fedd8
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
16 changes: 15 additions & 1 deletion src/model/types/JSONType.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,30 @@
namespace mindplay\sql\model\types;

use mindplay\sql\model\schema\Type;
use RuntimeException;

class JSONType implements Type
{
/**
* @var int options for json_encode()
*
* @see json_encode()
*/
public $json_encode_options = JSON_UNESCAPED_UNICODE;

public function convertToSQL($value)
{
if ($value === null || $value === '') {
return null;
}

return json_encode($value);
$json = json_encode($value, $this->json_encode_options);

if ($json === false) {
throw new RuntimeException(json_last_error_msg());
}

return $json;
}

public function convertToPHP($value)
Expand Down
15 changes: 13 additions & 2 deletions test/test.php
Original file line number Diff line number Diff line change
Expand Up @@ -866,11 +866,22 @@ function () {
function () {
$type = new JSONType();

$valid_value = ['foo' => 'bar'];
$valid_json = '{"foo":"bar"}';
$valid_value = ['foo' => 'bår'];
$valid_json = '{"foo":"bår"}';

eq($type->convertToPHP($valid_json), $valid_value, "can convert to PHP value");
eq($type->convertToSQL($valid_value), $valid_json, "can convert to SQL JSON value");

$invalid_string = "\xc3\x28"; // invalid 2 Octet Sequence

expect(
RuntimeException::class,
"should throw for invalid UTF-8 string",
function () use ($type, $invalid_string) {
$type->convertToSQL($invalid_string);
},
'#' . preg_quote('malformed utf-8') . '#i'
);
}
);

Expand Down

0 comments on commit 13fedd8

Please sign in to comment.