Passed
Pull Request — master (#47)
by
unknown
02:59
created

Schema   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 13
c 0
b 0
f 0
lcom 0
cbo 1
dl 0
loc 60
ccs 31
cts 31
cp 1
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 15 4
A castProperty() 0 10 3
A __get() 0 10 2
schema() 0 1 ?
A toArray() 0 4 1
A cast() 0 7 2
A castSchema() 0 4 1
1
<?php
2
namespace Fathomminds\Rest;
3
4
use Fathomminds\Rest\Contracts\ISchema;
5
use Fathomminds\Rest\Schema\TypeValidators\ValidatorFactory;
6
use Fathomminds\Rest\Exceptions\RestException;
7
8
abstract class Schema implements ISchema
9
{
10 77
    public function __construct($object = null)
11
    {
12 77
        if ($object === null) {
13 73
            return;
14
        }
15 21
        if (gettype($object) !== 'object') {
16 1
            throw new RestException('Schema constructor expects object or null as parameter', [
17 1
                'parameter' => $object,
18
            ]);
19
        }
20 20
        $schema = $this->schema();
21 20
        foreach (get_object_vars($object) as $name => $value) {
22 18
            $this->{$name} = $this->castProperty($schema, $name, $value);
23
        }
24 20
    }
25
26 18
    private function castProperty($schema, $name, $value)
27
    {
28 18
        if (!array_key_exists($name, $schema)) {
29 1
            return $value;
30
        }
31 18
        $params = empty($schema[$name]['validator']['params'])
32 18
            ? null
33 18
            : $schema[$name]['validator']['params'];
34 18
        return $schema[$name]['validator']['class']::cast($value, $params);
35
    }
36
37 2
    public function __get($name)
38
    {
39 2
        if (!isset($this->{$name})) {
40 1
            throw new RestException(
41 1
                'Trying to access undefined property ' . $name,
42 1
                []
43
            );
44
        }
45 1
        return $this->{$name};
46
    }
47
48
    abstract public function schema();
49
50 4
    public function toArray()
51
    {
52 4
        return json_decode(json_encode($this), true);
53
    }
54
55 2
    public static function cast($object, $params = null)
56
    {
57 2
        if ($params === null) {
58 1
            return self::castSchema($object);
59
        }
60 1
        return new static($object);
61
    }
62
63 1
    private static function castSchema($object)
64
    {
65 1
        return new static($object);
66
    }
67
}
68