|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
|
4
|
|
|
|
|
5
|
|
|
namespace KingsonDe\Marshal; |
|
6
|
|
|
|
|
7
|
|
|
use KingsonDe\Marshal\Data\CollectionCallable; |
|
8
|
|
|
use PHPUnit\Framework\TestCase; |
|
9
|
|
|
|
|
10
|
|
|
class MarshalJsonTest extends TestCase { |
|
11
|
|
|
|
|
12
|
|
|
public function testJsonSerialize() { |
|
13
|
|
|
$json = MarshalJson::serializeItemCallable([$this, 'mapUser'], $this->createUser()); |
|
14
|
|
|
|
|
15
|
|
|
$this->assertJsonStringEqualsJsonFile(__DIR__ . '/Fixtures/User.json', $json); |
|
16
|
|
|
} |
|
17
|
|
|
|
|
18
|
|
|
public function testJsonSerializeWithOptions() { |
|
19
|
|
|
MarshalJson::setEncodingOptions(JSON_HEX_TAG | JSON_HEX_AMP); |
|
20
|
|
|
|
|
21
|
|
|
$json = MarshalJson::serializeItemCallable([$this, 'mapUser'], $this->createUser()); |
|
22
|
|
|
|
|
23
|
|
|
$this->assertJsonStringEqualsJsonFile(__DIR__ . '/Fixtures/UserEscaped.json', $json); |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
public function testBuildDataStructureIsNull() { |
|
27
|
|
|
$json = MarshalJson::serializeItemCallable(function () { |
|
|
|
|
|
|
28
|
|
|
return null; |
|
29
|
|
|
}); |
|
30
|
|
|
|
|
31
|
|
|
$this->assertJsonStringEqualsJsonString('{}', $json); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* @expectedException \KingsonDe\Marshal\Exception\JsonSerializeException |
|
36
|
|
|
*/ |
|
37
|
|
|
public function testSerializationFailed() { |
|
38
|
|
|
MarshalJson::serializeItemCallable(function () { |
|
|
|
|
|
|
39
|
|
|
return [ |
|
40
|
|
|
'malformedJson' => "\xB1\x31", |
|
41
|
|
|
]; |
|
42
|
|
|
}); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
public function mapUser(\stdClass $user) { |
|
46
|
|
|
return [ |
|
47
|
|
|
'id' => $user->id, |
|
48
|
|
|
'score' => $user->score, |
|
49
|
|
|
'email' => $user->email, |
|
50
|
|
|
'null' => null, |
|
51
|
|
|
'followers' => new CollectionCallable(function ($username) { |
|
52
|
|
|
return [ |
|
53
|
|
|
'username' => $username, |
|
54
|
|
|
]; |
|
55
|
|
|
}, $user->followers) |
|
56
|
|
|
]; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
private function createUser() { |
|
60
|
|
|
$user = new \stdClass(); |
|
61
|
|
|
$user->id = 123; |
|
62
|
|
|
$user->score = 3.4; |
|
63
|
|
|
$user->email = '[email protected]'; |
|
64
|
|
|
$user->followers = ['pfefferkuchenmann & <co>', 'lululu']; |
|
65
|
|
|
|
|
66
|
|
|
return $user; |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|
This check looks for function calls that miss required arguments.