Completed
Pull Request — master (#2)
by René
05:02 queued 02:37
created

EntityProperty::formatValueForDatabase()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 20
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 9
cts 9
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 9
nc 3
nop 1
crap 3
1
<?php
2
declare(strict_types = 1);
3
4
namespace Zortje\MVC\Model\Table\Entity;
5
6
/**
7
 * Class EntityProperty
8
 *
9
 * @package Zortje\MVC\Model\Table\Entity
10
 */
11
class EntityProperty
12
{
13
14
    /**
15
     * @var string Entity property type
16
     */
17
    protected $type;
18
19
    // @todo Should be aware of the column type length to avoid truncation or even query errors
20
21
    /**
22
     * @param string $type
23
     */
24 1
    public function __construct(string $type)
25
    {
26 1
        $this->type = $type;
27 1
    }
28
29
    /**
30
     * Format value according to entity property type
31
     *
32
     * @param mixed $value Value
33
     *
34
     * @return mixed Value
35
     */
36 5
    public function formatValueForEntity($value)
37
    {
38 5
        switch ($this->type) {
39 5
            case 'string':
40 4
            case 'uuid':
41 1
                $value = "$value";
42 1
                break;
43
44 4
            case 'integer':
45 1
                $value = (int)$value;
46 1
                break;
47
48 3
            case 'float':
49 1
                $value = (float)$value;
50 1
                break;
51
52 2
            case 'date':
53 1
            case 'datetime':
54 2
                $value = new \DateTime($value);
55 2
                break;
56
        }
57
58 5
        return $value;
59
    }
60
61
    /**
62
     * Format value for insertion into the database
63
     *
64
     * @param mixed $value Value
65
     *
66
     * @return mixed Value
67
     */
68 2
    public function formatValueForDatabase($value)
69
    {
70 2
        switch ($this->type) {
71 2
            case 'date':
72
                /**
73
                 * @var \DateTime $value
74
                 */
75 1
                $value = $value->format('Y-m-d');
76 1
                break;
77
78 1
            case 'datetime':
79
                /**
80
                 * @var \DateTime $value
81
                 */
82 1
                $value = $value->format('Y-m-d H:i:s');
83 1
                break;
84
        }
85
86 2
        return $value;
87
    }
88
}
89