Passed
Push — develop ( ab55d7...e2a568 )
by Csaba
01:26
created

Schema::castProperty()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 10
c 0
b 0
f 0
ccs 7
cts 7
cp 1
rs 9.4285
cc 3
eloc 7
nc 3
nop 3
crap 3
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 76
    public function __construct($object = null)
11
    {
12 76
        if ($object === null) {
13 73
            return;
14
        }
15 20
        if (gettype($object) !== 'object') {
16 1
            throw new RestException('Schema constructor expects object or null as parameter', [
17 1
                'parameter' => $object,
18
            ]);
19
        }
20 19
        $schema = $this->schema();
21 19
        foreach (get_object_vars($object) as $name => $value) {
22 17
            $this->{$name} = $this->castProperty($schema, $name, $value);
23
        }
24 19
    }
25
26 17
    private function castProperty($schema, $name, $value)
27
    {
28 17
        if (!array_key_exists($name, $schema)) {
29 1
            return $value;
30
        }
31 17
        $params = empty($schema[$name]['validator']['params'])
32 17
            ? null
33 17
            : $schema[$name]['validator']['params'];
34 17
        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 1
    public static function cast($object, $params = null)
0 ignored issues
show
Unused Code introduced by
The parameter $params is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
56
    {
57 1
        return new static($object);
58
    }
59
}
60