Completed
Push — master ( e98ae3...0e888f )
by Matt
02:50
created

Assert::type()   B

Complexity

Conditions 5
Paths 4

Duplication

Lines 0
Ratio 0 %

Size

Total Lines 17
Code Lines 11

Code Coverage

Tests 11
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 11
nc 4
nop 4
dl 0
loc 17
ccs 11
cts 11
cp 1
crap 5
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
namespace League\JsonGuard;
4
5
use League\JsonGuard\Exceptions\InvalidSchemaException;
6
7
/**
8
 * Assertions to verify a schema is valid.
9
 */
10
class Assert
11
{
12
    /**
13
     * Validate an array has at least one element.
14
     *
15
     * @param array       $value
16
     * @param string      $keyword
17
     * @param string|null $pointer
18
     */
19 40
    public static function notEmpty(array $value, $keyword, $pointer = null)
20
    {
21 40
        if (!empty($value)) {
22 34
            return;
23
        }
24
25 6
        throw InvalidSchemaException::emptyArray($keyword, $pointer);
26
    }
27
28
    /**
29
     * Validate an integer is non-negative.
30
     *
31
     * @param integer     $value
32
     * @param string      $keyword
33
     * @param string|null $pointer
34
     */
35 68
    public static function nonNegative($value, $keyword, $pointer = null)
36
    {
37 68
        if ($value >= 0) {
38 52
            return;
39
        }
40
41 16
        throw InvalidSchemaException::negativeValue(
42 16
            $value,
43 16
            $keyword,
44
            $pointer
45 16
        );
46
    }
47
48
    /**
49
     * Validate a value is one of the allowed types.
50
     *
51
     * @param mixed        $value
52
     * @param array|string $choices
53
     * @param string       $keyword
54
     * @param string|null  $pointer
55
     *
56
     * @throws InvalidSchemaException
57
     */
58 232
    public static function type($value, $choices, $keyword, $pointer = null)
59
    {
60 232
        $actualType = gettype($value);
61 232
        $choices    = is_array($choices)  ? $choices : [$choices];
62
63 232
        if (in_array($actualType, $choices) ||
64 232
            (is_json_number($value) && in_array('number', $choices))) {
65 176
            return;
66
        }
67
68 56
        throw InvalidSchemaException::invalidParameterType(
69 56
            $actualType,
70 56
            $choices,
71 56
            $keyword,
72
            $pointer
73 56
        );
74
    }
75
}
76