Completed
Pull Request — master (#76)
by Simone
02:48
created

Schema::countSubSchemas()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
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\NoPropertiesException;
17
use Sensorario\Resources\Exceptions\NoTypeException;
18
19
final class Schema
20
{
21
    const PRIMITIVE_ARRAY   = 'array';
22
    const PRIMITIVE_BOOLEAN = 'boolean';
23
    const PRIMITIVE_DEFAULT = Schema::PRIMITIVE_NULL;
24
    const PRIMITIVE_INTEGER = 'integer';
25
    const PRIMITIVE_NULL    = 'null';
26
    const PRIMITIVE_NUMBER  = 'number';
27
    const PRIMITIVE_OBJECT  = 'object';
28
    const PRIMITIVE_STRING  = 'string';
29
30
    private $completeSchema;
31
32
    private $schemaNames = [];
33
34
    public function __construct($schema)
35
    {
36
        $this->completeSchema = $schema;
37
38
        $this->schemaNames[] = 'root';
39
40
        $this->parseSchema($this->completeSchema);
41
    }
42
43
    private function parseSchema($schema)
44
    {
45
        if (!isset($schema['type'])) {
46
            throw new NoTypeException('Schema type is not defined');
47
        }
48
49
        if (!isset($schema['properties'])) {
50
            throw new NoPropertiesException();
51
        }
52
53
        foreach ($schema['properties'] as $name => $def) {
54
            if (!isset($def['type'])) {
55
                throw new NoTypeException(
56
                    'Property `' . $name . '`'
57
                    . ' MUST HAVE a type'
58
                );
59
            }
60
        }
61
62
        foreach ($schema as $key => $value) {
63
            if (!in_array($key, ['properties', 'title', 'type'])) {
64
                $this->schemaNames[] = $key;
65
                $this->parseSchema($value);
66
            }
67
        }
68
    }
69
70
    public function countSubSchemas()
71
    {
72
        return 0;
73
    }
74
75
    public function completeSchema()
76
    {
77
        return $this->completeSchema;
78
    }
79
80
    public function schemaNames()
81
    {
82
        return $this->schemaNames;
83
    }
84
85
    public function getTitle()
86
    {
87
        return $this->completeSchema['title'];
88
    }
89
}
90