Skip to content

Commit 07861aa

Browse files
siganushkanicolas-grekas
authored andcommitted
[Serializer] Fixed framework.serializer.default_context is not working for JsonEncoder
1 parent 776fa30 commit 07861aa

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

Encoder/JsonEncoder.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,10 @@ class JsonEncoder implements EncoderInterface, DecoderInterface
2323
protected $encodingImpl;
2424
protected $decodingImpl;
2525

26-
public function __construct(JsonEncode $encodingImpl = null, JsonDecode $decodingImpl = null)
26+
public function __construct(JsonEncode $encodingImpl = null, JsonDecode $decodingImpl = null, array $defaultContext = [])
2727
{
28-
$this->encodingImpl = $encodingImpl ?? new JsonEncode();
29-
$this->decodingImpl = $decodingImpl ?? new JsonDecode([JsonDecode::ASSOCIATIVE => true]);
28+
$this->encodingImpl = $encodingImpl ?? new JsonEncode($defaultContext);
29+
$this->decodingImpl = $decodingImpl ?? new JsonDecode(array_merge([JsonDecode::ASSOCIATIVE => true], $defaultContext));
3030
}
3131

3232
/**

Tests/Encoder/JsonEncoderTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,22 @@ public function testOptions()
6666
$this->assertEquals($expected, $this->serializer->serialize($arr, 'json'), 'Context should not be persistent');
6767
}
6868

69+
public function testWithDefaultContext()
70+
{
71+
$defaultContext = [
72+
'json_encode_options' => \JSON_UNESCAPED_UNICODE,
73+
'json_decode_associative' => false,
74+
];
75+
76+
$encoder = new JsonEncoder(null, null, $defaultContext);
77+
78+
$data = new \stdClass();
79+
$data->msg = '你好';
80+
81+
$this->assertEquals('{"msg":"你好"}', $json = $encoder->encode($data, 'json'));
82+
$this->assertEquals($data, $encoder->decode($json, 'json'));
83+
}
84+
6985
public function testEncodeNotUtf8WithoutPartialOnError()
7086
{
7187
$this->expectException(UnexpectedValueException::class);

0 commit comments

Comments
 (0)