Completed
Push — master ( a787fa...dc9af5 )
by Vincent
05:35
created

assertIsValidResourceIdentifierObject()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 30
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 20
c 0
b 0
f 0
dl 0
loc 30
rs 9.6
cc 2
nc 2
nop 2
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 resource linkage
12
 */
13
trait AssertResourceLinkage
14
{
15
    /**
16
     * Asserts that a json fragment is a valid resource linkage object.
17
     *
18
     * @param array|null    $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 assertIsValidResourceLinkage($json, bool $strict): void
24
    {
25
        if (\is_null($json)) {
26
            $json = [];
27
        }
28
29
        PHPUnit::assertIsArray(
30
            $json,
31
            Messages::RESOURCE_LINKAGE_NOT_ARRAY
32
        );
33
34
        if (!static::isArrayOfObjects($json)) {
35
            $json = [$json];
36
        }
37
        foreach ($json as $resource) {
38
            static::assertIsValidResourceIdentifierObject($resource, $strict);
39
        }
40
    }
41
42
    /**
43
     * Asserts that a json fragment is a valid resource identifier object.
44
     *
45
     * @param array     $resource
46
     * @param boolean   $strict         If true, unsafe characters are not allowed when checking members name.
47
     * @return void
48
     * @throws \PHPUnit\Framework\ExpectationFailedException
49
     */
50
    public static function assertIsValidResourceIdentifierObject($resource, bool $strict): void
51
    {
52
        PHPUnit::assertIsArray(
53
            $resource,
54
            Messages::RESOURCE_IDENTIFIER_IS_NOT_ARRAY
55
        );
56
57
        PHPUnit::assertArrayHasKey(
58
            Members::ID,
59
            $resource,
60
            Messages::RESOURCE_ID_MEMBER_IS_ABSENT
61
        );
62
        static::assertResourceIdMember($resource);
63
64
        PHPUnit::assertArrayHasKey(
65
            Members::TYPE,
66
            $resource,
67
            Messages::RESOURCE_TYPE_MEMBER_IS_ABSENT
68
        );
69
        static::assertResourceTypeMember($resource, $strict);
70
71
        $allowed = [
72
            Members::ID,
73
            Members::TYPE,
74
            Members::META
75
        ];
76
        static::assertContainsOnlyAllowedMembers($allowed, $resource);
77
78
        if (isset($resource[Members::META])) {
79
            static::assertIsValidMetaObject($resource[Members::META], $strict);
80
        }
81
    }
82
}
83