8
8
9
9
namespace LaminasTest \View \Model ;
10
10
11
- use Laminas \Json \ Json ;
11
+ use Laminas \View \ Exception \ DomainException ;
12
12
use Laminas \View \Model \JsonModel ;
13
13
use Laminas \View \Variables ;
14
14
use PHPUnit \Framework \TestCase ;
15
15
16
+ use function json_encode ;
17
+
18
+ use const JSON_PRETTY_PRINT ;
19
+ use const JSON_THROW_ON_ERROR ;
20
+
16
21
class JsonModelTest extends TestCase
17
22
{
18
- public function testAllowsEmptyConstructor ()
23
+ public function testAllowsEmptyConstructor (): void
19
24
{
20
25
$ model = new JsonModel ();
21
26
$ this ->assertInstanceOf (Variables::class, $ model ->getVariables ());
22
27
$ this ->assertEquals ([], $ model ->getOptions ());
23
28
}
24
29
25
- public function testCanSerializeVariablesToJson ()
30
+ public function testCanSerializeVariablesToJson (): void
26
31
{
27
32
$ array = ['foo ' => 'bar ' ];
28
33
$ model = new JsonModel ($ array );
29
34
$ this ->assertEquals ($ array , $ model ->getVariables ());
30
- $ this ->assertEquals (Json:: encode ($ array ), $ model ->serialize ());
35
+ $ this ->assertJsonStringEqualsJsonString ( json_encode ($ array, JSON_THROW_ON_ERROR ), $ model ->serialize ());
31
36
}
32
37
33
- public function testCanSerializeWithJsonpCallback ()
38
+ public function testCanSerializeWithJsonpCallback (): void
34
39
{
35
40
$ array = ['foo ' => 'bar ' ];
36
41
$ model = new JsonModel ($ array );
37
42
$ model ->setJsonpCallback ('callback ' );
38
- $ this ->assertEquals ('callback( ' . Json::encode ($ array ) . '); ' , $ model ->serialize ());
43
+ $ expect = sprintf (
44
+ 'callback(%s); ' ,
45
+ json_encode ($ array , JSON_THROW_ON_ERROR )
46
+ );
47
+ $ this ->assertEquals ($ expect , $ model ->serialize ());
39
48
}
40
49
41
- public function testPrettyPrint ()
50
+ public function testPrettyPrint (): void
42
51
{
43
52
$ array = [
44
53
'simple ' => 'simple test string ' ,
@@ -49,6 +58,17 @@ public function testPrettyPrint()
49
58
]
50
59
];
51
60
$ model = new JsonModel ($ array , ['prettyPrint ' => true ]);
52
- $ this ->assertEquals (Json::encode ($ array , false , ['prettyPrint ' => true ]), $ model ->serialize ());
61
+ $ expect = json_encode ($ array , JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT );
62
+ $ this ->assertEquals ($ expect , $ model ->serialize ());
63
+ }
64
+
65
+ public function testThatAnExceptionIsThrownIfItIsNotPossibleToEncodeThePayload (): void
66
+ {
67
+ $ malformedUtf8 = [
68
+ 'string ' => "\x92" ,
69
+ ];
70
+ $ this ->expectException (DomainException::class);
71
+ $ this ->expectExceptionMessage ('Failed to encode Json ' );
72
+ (new JsonModel ($ malformedUtf8 ))->serialize ();
53
73
}
54
74
}
0 commit comments