Skip to content
This repository was archived by the owner on Dec 23, 2021. It is now read-only.

HHVM-266: Javascript should emit $code/$scope for JSON #153

Merged
merged 2 commits into from
Nov 16, 2016
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
11 changes: 9 additions & 2 deletions ext_mongodb.php
Original file line number Diff line number Diff line change
Expand Up @@ -1327,7 +1327,14 @@ public function serialize() : string

public function jsonSerialize() : mixed
{
return $this->code;
$json = [ '$code' => $this->code ];

if ( isset( $this->scope ) )
{
$json['$scope'] = $this->scope;
}

return $json;
}

public function unserialize(mixed $serialized) : void
Expand Down Expand Up @@ -1378,7 +1385,7 @@ public function getCode() : string

public function getScope() : mixed
{
if ( isset( $this->scope) && $this->scope !== NULL )
if ( isset( $this->scope ) )
{
return (object) $this->scope;
}
Expand Down
29 changes: 29 additions & 0 deletions tests/json-serialize-javascript-001.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
--TEST--
JsonSerializable: Javascript (with scope)
--FILE--
<?php
$doc = [
'foo' => new MongoDB\BSON\Javascript( "function foo(bar) { return bar; }", [ 'foo' => 42 ] )
];

echo MongoDB\BSON\toJSON( \MongoDB\BSON\fromPHP( $doc ) ), "\n";
$d = json_encode( $doc );
echo $d, "\n";

var_dump( \MongoDB\BSON\toPHP( \MongoDB\BSON\fromJSON( $d ) ) );
?>
--EXPECTF--
{ "foo" : "function foo(bar) { return bar; }" }
{"foo":{"$code":"function foo(bar) { return bar; }","$scope":{"foo":42}}}
object(stdClass)#%d (%d) {
["foo"]=>
object(stdClass)#%d (%d) {
["$code"]=>
string(33) "function foo(bar) { return bar; }"
["$scope"]=>
object(stdClass)#%d (%d) {
["foo"]=>
int(42)
}
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
--TEST--
JsonSerializable: Javascript
JsonSerializable: Javascript (without scope)
--FILE--
<?php
$doc = [
'foo' => new MongoDB\BSON\Javascript( "function foo(bar) { return bar; }", [ 'foo' => 42 ] )
'foo' => new MongoDB\BSON\Javascript( "function foo(bar) { return bar; }")
];

echo MongoDB\BSON\toJSON( \MongoDB\BSON\fromPHP( $doc ) ), "\n";
Expand All @@ -14,8 +14,11 @@ var_dump( \MongoDB\BSON\toPHP( \MongoDB\BSON\fromJSON( $d ) ) );
?>
--EXPECTF--
{ "foo" : "function foo(bar) { return bar; }" }
{"foo":"function foo(bar) { return bar; }"}
{"foo":{"$code":"function foo(bar) { return bar; }"}}
object(stdClass)#%d (%d) {
["foo"]=>
string(33) "function foo(bar) { return bar; }"
object(stdClass)#%d (%d) {
["$code"]=>
string(33) "function foo(bar) { return bar; }"
}
}