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 attributes object |
12
|
|
|
*/ |
13
|
|
|
trait AssertAttributesObject |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* Asserts that a json fragment is a valid attributes object. |
17
|
|
|
* |
18
|
|
|
* @param array $json |
19
|
|
|
* @param boolean $strict If true, unsafe characters are not allowed when checking members name. |
20
|
|
|
* @return void |
21
|
|
|
* @throws \PHPUnit\Framework\ExpectationFailedException |
22
|
|
|
*/ |
23
|
|
|
public static function assertIsValidAttributesObject($json, bool $strict): void |
24
|
|
|
{ |
25
|
|
|
static::assertIsNotArrayOfObjects( |
26
|
|
|
$json, |
27
|
|
|
Messages::ATTRIBUTES_OBJECT_IS_NOT_ARRAY |
28
|
|
|
); |
29
|
|
|
|
30
|
|
|
static::assertFieldHasNoForbiddenMemberName($json); |
31
|
|
|
|
32
|
|
|
foreach (array_keys($json) as $key) { |
33
|
|
|
static::assertIsValidMemberName($key, $strict); |
34
|
|
|
} |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Asserts that a field object (i.e., a resource object’s attributes or one of its relationships) |
39
|
|
|
* has no forbidden member name. |
40
|
|
|
* |
41
|
|
|
* @param mixed $field |
42
|
|
|
* @return void |
43
|
|
|
* @throws \PHPUnit\Framework\ExpectationFailedException |
44
|
|
|
*/ |
45
|
|
|
public static function assertFieldHasNoForbiddenMemberName($field): void |
46
|
|
|
{ |
47
|
|
|
if (!is_array($field)) { |
48
|
|
|
return; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
foreach ($field as $key => $value) { |
52
|
|
|
// For objects, $key is a string |
53
|
|
|
// For arrays of objects, $key is an integer |
54
|
|
|
if (is_string($key)) { |
55
|
|
|
static::assertIsNotForbiddenMemberName($key); |
56
|
|
|
} |
57
|
|
|
static::assertFieldHasNoForbiddenMemberName($value); |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Asserts that a member name is not forbidden. |
63
|
|
|
* |
64
|
|
|
* @param string $name |
65
|
|
|
* @return void |
66
|
|
|
* @throws \PHPUnit\Framework\ExpectationFailedException |
67
|
|
|
*/ |
68
|
|
|
public static function assertIsNotForbiddenMemberName($name): void |
69
|
|
|
{ |
70
|
|
|
if (!\is_string($name)) { |
|
|
|
|
71
|
|
|
static::invalidArgument(1, 'string', $name); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
$forbidden = [ |
75
|
|
|
Members::RELATIONSHIPS, |
76
|
|
|
Members::LINKS |
77
|
|
|
]; |
78
|
|
|
PHPUnit::assertNotContains( |
79
|
|
|
$name, |
80
|
|
|
$forbidden, |
81
|
|
|
Messages::MEMBER_NAME_NOT_ALLOWED |
82
|
|
|
); |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|