Completed
Push — master ( e7f8de...7e52b4 )
by Dmitry
03:22
created

Convention::setNumberType()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Tarantool\Mapper\Schema;
4
5
use Tarantool\Mapper\Contracts;
6
use Exception;
7
8
class Convention implements Contracts\Convention
9
{
10
    private $numberType;
11
12 64
    public function setNumberType($type)
13
    {
14 64
        $this->numberType = $type;
15 64
    }
16
17 64
    public function getType($property)
18
    {
19 64
        if ($property == 'id') {
20 64
            return 'integer';
21
        }
22 64
        if (substr($property, -3) == '_at') {
23 1
            return 'integer';
24
        }
25
26 64
        return 'string';
27
    }
28
29 64
    public function getTarantoolType($type)
30
    {
31 64
        if ($type == 'string') {
32 64
            return 'STR';
33
        }
34
35 64
        if(!$this->numberType) {
36
            throw new Exception("numberType property is null", 1);
37
        }
38 64
        return $this->numberType;
39
    }
40
41 64
    public function isPrimitive($type)
42
    {
43 64
        return in_array($type, ['integer', 'string', 'array']);
44
    }
45
46 64
    public function encode($type, $value)
47
    {
48 64
        if (!$this->isPrimitive($type)) {
49 5
            if ($value instanceof Contracts\Entity) {
50 5
                return $value->getId();
51
            }
52
53 5
            return +$value;
54
        }
55
56 64
        if ($type == 'integer') {
57 64
            return $value ? +$value : 0;
58
        }
59
60 64
        if (is_null($value)) {
61 1
            return;
62
        }
63
64 64
        if (!is_array($value)) {
65 64
            return "$value";
66
        }
67
68 3
        return $value;
69
    }
70
71 64
    public function decode($type, $value)
72
    {
73 64
        if ($type == 'integer') {
74 64
            return $value ? +$value : 0;
75
        }
76
77 31
        return $value;
78
    }
79
80 64
    public function getDefaultValue($type)
81
    {
82 64
        if ($type == 'integer' || !$this->isPrimitive($type)) {
83 64
            return 0;
84
        }
85
86 4
        return '';
87
    }
88
}
89