Passed
Push — develop ( e2a568...9e4904 )
by Csaba
46s
created

Schema::cast()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 9.4285
cc 2
eloc 4
nc 2
nop 2
crap 2
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