Completed
Push — master ( afc521...1cce3a )
by Vincent
03:19
created

assertIsValidResourceLinkage()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 16
nc 5
nop 2
dl 0
loc 24
rs 9.4222
c 0
b 0
f 0
1
<?php
2
namespace VGirol\JsonApiAssert\Asserts;
3
4
use PHPUnit\Framework\Assert as PHPUnit;
5
use VGirol\JsonApiAssert\Messages;
6
use PHPUnit\Framework\ExpectationFailedException;
7
8
trait AssertResourceLinkage
9
{
10
    /**
11
     * Asserts that a json fragment is a valid resource linkage object.
12
     *
13
     * @param array     $json
14
     * @param boolean   $strict     If true, unsafe characters are not allowed when checking members name.
15
     *
16
     * @throws PHPUnit\Framework\ExpectationFailedException
17
     */
18
    public static function assertIsValidResourceLinkage($json, $strict)
19
    {
20
        try {
21
            PHPUnit::assertIsArray(
22
                $json,
23
                Messages::RESOURCE_LINKAGE_NOT_ARRAY
24
            );
25
            if (empty($json)) {
26
                return;
27
            }
28
        } catch (ExpectationFailedException $e) {
29
            PHPUnit::assertNull(
30
                $json,
31
                Messages::RESOURCE_LINKAGE_NOT_ARRAY
32
            );
33
            return;
34
        }
35
36
        if (static::isArrayOfObjects($json)) {
37
            foreach ($json as $resource) {
38
                static::assertIsValidResourceIdentifierObject($resource, $strict);
39
            }
40
        } else {
41
            static::assertIsValidResourceIdentifierObject($json, $strict);
42
        }
43
    }
44
45
    /**
46
     * Asserts that a json fragment is a valid resource identifier object.
47
     *
48
     * @param array     $resource
49
     * @param boolean   $strict         If true, unsafe characters are not allowed when checking members name.
50
     *
51
     * @throws PHPUnit\Framework\ExpectationFailedException
52
     */
53
    public static function assertIsValidResourceIdentifierObject($resource, $strict)
54
    {
55
        PHPUnit::assertIsArray(
56
            $resource,
57
            Messages::RESOURCE_IDENTIFIER_IS_NOT_ARRAY
58
        );
59
60
        PHPUnit::assertArrayHasKey(
61
            'id',
62
            $resource,
63
            Messages::RESOURCE_ID_MEMBER_IS_ABSENT
64
        );
65
        static::assertResourceIdMember($resource);
66
67
        PHPUnit::assertArrayHasKey(
68
            'type',
69
            $resource,
70
            Messages::RESOURCE_TYPE_MEMBER_IS_ABSENT
71
        );
72
        static::assertResourceTypeMember($resource, $strict);
73
74
        $allowed = ['id', 'type', 'meta'];
75
        static::assertContainsOnlyAllowedMembers($allowed, $resource);
76
77
        if (isset($resource['meta'])) {
78
            static::assertIsValidMetaObject($resource['meta'], $strict);
79
        }
80
    }
81
}
82