|
1
|
|
|
<?php |
|
2
|
|
|
namespace VGirol\JsonApiAssert\Asserts; |
|
3
|
|
|
|
|
4
|
|
|
use PHPUnit\Framework\Assert as PHPUnit; |
|
5
|
|
|
use PHPUnit\Util\InvalidArgumentHelper; |
|
6
|
|
|
use VGirol\JsonApiAssert\Messages; |
|
7
|
|
|
|
|
8
|
|
|
trait AssertAttributesObject |
|
9
|
|
|
{ |
|
10
|
|
|
/** |
|
11
|
|
|
* Asserts that an attributes object is valid. |
|
12
|
|
|
* |
|
13
|
|
|
* @param array $attributes |
|
14
|
|
|
* @param boolean $strict If true, excludes not safe characters when checking members name |
|
15
|
|
|
* |
|
16
|
|
|
* @throws PHPUnit\Framework\ExpectationFailedException |
|
17
|
|
|
*/ |
|
18
|
26 |
|
public static function assertIsValidAttributesObject($attributes, $strict) |
|
19
|
|
|
{ |
|
20
|
26 |
|
static::assertIsNotArrayOfObjects( |
|
21
|
26 |
|
$attributes, |
|
22
|
26 |
|
Messages::ATTRIBUTES_OBJECT_IS_NOT_ARRAY |
|
23
|
|
|
); |
|
24
|
|
|
|
|
25
|
25 |
|
static::assertFieldHasNoForbiddenMemberName($attributes); |
|
26
|
|
|
|
|
27
|
24 |
|
foreach (array_keys($attributes) as $key) { |
|
28
|
24 |
|
static::assertIsValidMemberName($key, $strict); |
|
29
|
|
|
} |
|
30
|
21 |
|
} |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* Asserts that a field object has no forbidden member name |
|
34
|
|
|
* |
|
35
|
|
|
* @param mixed $field |
|
36
|
|
|
* |
|
37
|
|
|
* @throws PHPUnit\Framework\ExpectationFailedException |
|
38
|
|
|
*/ |
|
39
|
28 |
|
public static function assertFieldHasNoForbiddenMemberName($field) |
|
40
|
|
|
{ |
|
41
|
28 |
|
if (!is_array($field)) { |
|
42
|
28 |
|
return; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
28 |
|
foreach ($field as $key => $value) { |
|
46
|
|
|
// For objects, $key is a string |
|
47
|
|
|
// For arrays of objects, $key is an integer |
|
48
|
28 |
|
if (is_string($key)) { |
|
49
|
28 |
|
static::assertIsNotForbiddenMemberName($key); |
|
50
|
|
|
} |
|
51
|
28 |
|
static::assertFieldHasNoForbiddenMemberName($value); |
|
52
|
|
|
} |
|
53
|
25 |
|
} |
|
54
|
|
|
|
|
55
|
|
|
/** |
|
56
|
|
|
* Asserts that a member name is not forbidden |
|
57
|
|
|
* |
|
58
|
|
|
* @param string $name |
|
59
|
|
|
* |
|
60
|
|
|
* @throws PHPUnit\Framework\ExpectationFailedException |
|
61
|
|
|
*/ |
|
62
|
32 |
|
public static function assertIsNotForbiddenMemberName($name) |
|
63
|
|
|
{ |
|
64
|
32 |
|
if (!\is_string($name)) { |
|
|
|
|
|
|
65
|
1 |
|
throw InvalidArgumentHelper::factory( |
|
66
|
1 |
|
1, |
|
67
|
1 |
|
'string', |
|
68
|
1 |
|
$name |
|
69
|
|
|
); |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
31 |
|
$forbidden = ['relationships', 'links']; |
|
73
|
31 |
|
PHPUnit::assertNotContains( |
|
74
|
31 |
|
$name, |
|
75
|
31 |
|
$forbidden, |
|
76
|
31 |
|
Messages::MEMBER_NAME_NOT_ALLOWED |
|
77
|
|
|
); |
|
78
|
29 |
|
} |
|
79
|
|
|
} |
|
80
|
|
|
|