Completed
Pull Request — master (#10)
by Jan
02:30
created

Types::isA()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 3
Metric Value
dl 0
loc 7
ccs 3
cts 3
cp 1
rs 9.4285
cc 3
eloc 4
nc 3
nop 2
crap 3
1
<?php
2
3
/*
4
 * This file is part of the JVal package.
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
namespace JVal;
11
12
use JVal\Exception\UnsupportedTypeException;
13
14
/**
15
 * Wraps the list of primitive types defined in the JSON Schema Core
16
 * specification and provides utility methods to deal with them.
17
 */
18
class Types
19
{
20
    const TYPE_ARRAY = 'array';
21
    const TYPE_BOOLEAN = 'boolean';
22
    const TYPE_INTEGER = 'integer';
23
    const TYPE_NUMBER = 'number';
24
    const TYPE_NULL = 'null';
25
    const TYPE_OBJECT = 'object';
26
    const TYPE_STRING = 'string';
27
28
    /**
29
     * Returns the type of an instance according to JSON Schema Core 3.5.
30
     *
31
     * @param mixed $instance
32
     *
33
     * @return string
34
     *
35
     * @throws UnsupportedTypeException
36
     */
37 356
    public static function getPrimitiveTypeOf($instance)
38
    {
39 356
        switch ($type = gettype($instance)) {
40 356
            case 'integer':
41 119
                return self::TYPE_INTEGER;
42 304
            case 'string':
43 97
                return self::TYPE_STRING;
44 242
            case 'boolean':
45 25
                return self::TYPE_BOOLEAN;
46 225
            case 'double':
47 34
                return self::TYPE_NUMBER;
48 191
            case 'object':
49 126
                return self::TYPE_OBJECT;
50 78
            case 'array':
51 62
                return self::TYPE_ARRAY;
52 18
            case 'NULL':
53 17
                return self::TYPE_NULL;
54 1
        }
55
56 1
        throw new UnsupportedTypeException($type);
57
    }
58
59
    /**
60
     * Returns whether a type is part of the list of primitive types
61
     * defined by the specification.
62
     *
63
     * @param string $type
64
     *
65
     * @return bool
66
     */
67 204
    public static function isPrimitive($type)
68
    {
69
        return $type === self::TYPE_ARRAY
70 204
            || $type === self::TYPE_BOOLEAN
71 197
            || $type === self::TYPE_INTEGER
72 185
            || $type === self::TYPE_NUMBER
73 96
            || $type === self::TYPE_NULL
74 79
            || $type === self::TYPE_OBJECT
75 204
            || $type === self::TYPE_STRING;
76
    }
77
}
78