Completed
Pull Request — master (#76)
by Simone
03:11
created

Schema::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 10
rs 9.4285
cc 2
eloc 6
nc 2
nop 1
1
<?php
2
3
/**
4
 * This file is part of sensorario/resources repository
5
 *
6
 * (c) Simone Gentili <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sensorario\Resources;
13
14
use RuntimeException;
15
use Sensorario\Resources\Exceptions\InvalidTypeException;
16
use Sensorario\Resources\Exceptions\MissingPropertyException;
17
use Sensorario\Resources\Exceptions\NoPropertiesException;
18
use Sensorario\Resources\Exceptions\NoPropertyTypeException;
19
use Sensorario\Resources\Exceptions\NoTypeException;
20
use Sensorario\Resources\Exceptions\NotAllowedPropertyException;
21
use Sensorario\Resources\Exceptions\NotAllowedValueException;
22
23
final class Schema
24
{
25
    const PRIMITIVE_ARRAY   = 'array';
26
    const PRIMITIVE_BOOLEAN = 'boolean';
27
    const PRIMITIVE_DEFAULT = Schema::PRIMITIVE_NULL;
28
    const PRIMITIVE_INTEGER = 'integer';
29
    const PRIMITIVE_NULL    = 'null';
30
    const PRIMITIVE_NUMBER  = 'number';
31
    const PRIMITIVE_OBJECT  = 'object';
32
    const PRIMITIVE_STRING  = 'string';
33
34
    private $completeSchema;
35
36
    private $schemaNames = [];
37
38
    private $required = [];
39
40
    private $validTypes = [
41
        self::PRIMITIVE_ARRAY,
42
        self::PRIMITIVE_BOOLEAN,
43
        self::PRIMITIVE_DEFAULT,
44
        self::PRIMITIVE_INTEGER,
45
        self::PRIMITIVE_NULL,
46
        self::PRIMITIVE_NUMBER,
47
        self::PRIMITIVE_OBJECT,
48
        self::PRIMITIVE_STRING,
49
    ];
50
51
    private $subSchemaCounter = 0;
52
53
    private $properties = [];
54
55
    public function __construct($schema)
56
    {
57
        $this->completeSchema = $schema;
58
        $this->schemaNames[] = 'root';
59
        $this->parseSchema($this->completeSchema);
60
61
        if (isset($schema['required'])) {
62
            $this->required = $schema['required'];
63
        }
64
    }
65
66
    private function parseSchema($schema)
67
    {
68
        if (!isset($schema['type'])) {
69
            throw new NoTypeException('Schema type is not defined');
70
        }
71
72
        if (!in_array($schema['type'], $this->validTypes)) {
73
            throw new InvalidTypeException();
74
        }
75
76
        if (!isset($schema['properties'])) {
77
            throw new NoPropertiesException();
78
        }
79
80
        foreach ($schema['properties'] as $name => $def) {
81
            $this->properties[$name] = $def;
82
            if (!isset($def['type'])) {
83
                throw new NoPropertyTypeException(
84
                    'Property `' . $name . '`'
85
                    . ' MUST HAVE a type'
86
                );
87
            }
88
        }
89
90
        foreach ($schema as $key => $value) {
91
            if (!in_array($key, ['required', 'properties', 'title', 'type'])) {
92
                $this->schemaNames[] = $key;
93
                $this->subSchemaCounter++;
94
                $this->parseSchema($value);
95
            }
96
        }
97
    }
98
99
    public function countSubSchemas()
100
    {
101
        return $this->subSchemaCounter;
102
    }
103
104
    public function completeSchema()
105
    {
106
        return $this->completeSchema;
107
    }
108
109
    public function schemaNames()
110
    {
111
        return $this->schemaNames;
112
    }
113
114
    public function getTitle()
115
    {
116
        return $this->completeSchema['title'];
117
    }
118
119
    /** @todo move this inside an applipcation service */
120
    public function validate($json) 
121
    {
122
        $jsonAsArray = json_decode($json, true);
123
124
        foreach ($jsonAsArray as $name => $property) {
125
            if (!isset($this->properties()[$name])) {
126
                throw new NotAllowedPropertyException(
127
                    'Property ' . $name . ' is not allowed'
128
                );
129
            }
130
        }
131
132
        foreach ($this->required as $requiredProperty) {
133
            if (!isset($jsonAsArray[$requiredProperty])) {
134
                throw new MissingPropertyException(
135
                    'Property ' . $name . ' is not allowed'
136
                );
137
            }
138
        }
139
140
        foreach ($jsonAsArray as $name => $property) {
141
            $prop = $this->properties()[$name];
142
            if (gettype($jsonAsArray[$name]) != $prop['type']) {
143
                if ($prop['type'] == Schema::PRIMITIVE_INTEGER && is_numeric($jsonAsArray[$name])) {
144
                    continue;
145
                }
146
147
                throw new NotAllowedValueException(
148
                    'property ' . $name . ' is not allowed'
149
                );
150
            }
151
        }
152
153
        return json_decode($json);
154
    }
155
156
    public function properties()
157
    {
158
        return $this->properties;
159
    }
160
}
161