1
|
|
|
<?php |
2
|
|
|
declare (strict_types = 1); |
3
|
|
|
|
4
|
|
|
namespace VGirol\JsonApiAssert\Asserts\Structure; |
5
|
|
|
|
6
|
|
|
use PHPUnit\Framework\Assert as PHPUnit; |
7
|
|
|
use VGirol\JsonApiAssert\Members; |
8
|
|
|
use VGirol\JsonApiAssert\Messages; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Assertions relating to the links object |
12
|
|
|
*/ |
13
|
|
|
trait AssertLinksObject |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* Asserts that a json fragment is a valid links object. |
17
|
|
|
* |
18
|
|
|
* @param array $json |
19
|
|
|
* @param array<string> $allowedMembers |
20
|
|
|
* @param boolean $strict If true, unsafe characters are not allowed when checking members name. |
21
|
|
|
* @return void |
22
|
|
|
* @throws \PHPUnit\Framework\ExpectationFailedException |
23
|
|
|
*/ |
24
|
|
|
public static function assertIsValidLinksObject($json, array $allowedMembers, bool $strict): void |
25
|
|
|
{ |
26
|
|
|
PHPUnit::assertIsArray( |
27
|
|
|
$json, |
28
|
|
|
Messages::LINKS_OBJECT_NOT_ARRAY |
29
|
|
|
); |
30
|
|
|
|
31
|
|
|
static::assertContainsOnlyAllowedMembers( |
32
|
|
|
$allowedMembers, |
33
|
|
|
$json |
34
|
|
|
); |
35
|
|
|
|
36
|
|
|
foreach ($json as $link) { |
37
|
|
|
static::assertIsValidLinkObject($link, $strict); |
38
|
|
|
} |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Asserts that a json fragment is a valid link object. |
43
|
|
|
* |
44
|
|
|
* @param array $json |
45
|
|
|
* @param boolean $strict If true, unsafe characters are not allowed when checking members name. |
46
|
|
|
* @return void |
47
|
|
|
* @throws \PHPUnit\Framework\ExpectationFailedException |
48
|
|
|
*/ |
49
|
|
|
public static function assertIsValidLinkObject($json, bool $strict): void |
50
|
|
|
{ |
51
|
|
|
if (!\is_array($json)) { |
|
|
|
|
52
|
|
|
if (\is_null($json)) { |
53
|
|
|
$json = ''; |
54
|
|
|
} |
55
|
|
|
PHPUnit::assertIsString( |
56
|
|
|
$json, |
57
|
|
|
Messages::LINK_OBJECT_IS_NOT_ARRAY |
58
|
|
|
); |
59
|
|
|
return; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
PHPUnit::assertArrayHasKey( |
63
|
|
|
Members::HREF, |
64
|
|
|
$json, |
65
|
|
|
Messages::LINK_OBJECT_MISS_HREF_MEMBER |
66
|
|
|
); |
67
|
|
|
|
68
|
|
|
$allowed = [ |
69
|
|
|
Members::HREF, |
70
|
|
|
Members::META |
71
|
|
|
]; |
72
|
|
|
static::assertContainsOnlyAllowedMembers( |
73
|
|
|
$allowed, |
74
|
|
|
$json |
75
|
|
|
); |
76
|
|
|
|
77
|
|
|
if (isset($json[Members::META])) { |
78
|
|
|
static::assertIsValidMetaObject($json[Members::META], $strict); |
|
|
|
|
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|