Completed
Push — master ( abe227...316baf )
by Raffael
13:55 queued 08:01
created

Validator::validate()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 25
ccs 0
cts 19
cp 0
rs 9.52
c 0
b 0
f 0
cc 4
nc 3
nop 1
crap 20
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * tubee.io
7
 *
8
 * @copyright   Copryright (c) 2017-2019 gyselroth GmbH (https://gyselroth.com)
9
 * @license     GPL-3.0 https://opensource.org/licenses/GPL-3.0
10
 */
11
12
namespace Tubee\DataObjectRelation;
13
14
use InvalidArgumentException;
15
use Tubee\Resource\Validator as ResourceValidator;
16
17
class Validator extends ResourceValidator
18
{
19
    /**
20
     * Validate resource.
21
     */
22
    public static function validate(array $resource): array
23
    {
24
        $resource = parent::validate($resource);
25
26
        $defaults = [
27
            'data' => [
28
                'relation' => [],
29
                'context' => [],
30
            ],
31
        ];
32
33
        $resource = array_replace_recursive($defaults, $resource);
34
35
        if (!is_array($resource['data']['relation']) || count($resource['data']['relation']) !== 2) {
36
            throw new InvalidArgumentException('relation requires data.relation with exactly two objects');
37
        }
38
39
        self::validateRelation($resource['data']['relation']);
40
41
        if (!is_array($resource['data']['context'])) {
42
            throw new InvalidArgumentException('relation requires data.context to be an array');
43
        }
44
45
        return $resource;
46
    }
47
48
    /**
49
     * Validate relation.
50
     */
51 View Code Duplication
    protected static function validateRelation(array $resource): void
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
52
    {
53
        foreach ($resource as $object) {
54
            if (['namespace', 'collection', 'object'] != array_keys($object)) {
55
                throw new InvalidArgumentException('relation in data.relation must contain namespace, collection and object as strings');
56
            }
57
58
            if (array_filter($object, 'is_string') != $object) {
59
                throw new InvalidArgumentException('relation in data.relation must contain namespace, collection and object as strings');
60
            }
61
        }
62
    }
63
}
64