Completed
Pull Request — master (#2)
by René
04:17 queued 02:12
created

EntityProperty::formatValueForEntity()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 6

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 0
loc 23
ccs 16
cts 16
cp 1
rs 8.5906
cc 6
eloc 16
nc 6
nop 1
crap 6
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 1
                $value = "$value";
41 1
                break;
42
43 4
            case 'integer':
44 1
                $value = (int)$value;
45 1
                break;
46
47 3
            case 'float':
48 1
                $value = (float)$value;
49 1
                break;
50
51 2
            case 'date':
52 1
            case 'datetime':
53 2
                $value = new \DateTime($value);
54 2
                break;
55
        }
56
57 5
        return $value;
58
    }
59
60
    /**
61
     * Format value for insertion into the database
62
     *
63
     * @param mixed $value Value
64
     *
65
     * @return mixed Value
66
     */
67 2
    public function formatValueForDatabase($value)
68
    {
69 2
        switch ($this->type) {
70 2
            case 'date':
71
                /**
72
                 * @var \DateTime $value
73
                 */
74 1
                $value = $value->format('Y-m-d');
75 1
                break;
76
77 1
            case 'datetime':
78
                /**
79
                 * @var \DateTime $value
80
                 */
81 1
                $value = $value->format('Y-m-d H:i:s');
82 1
                break;
83
        }
84
85 2
        return $value;
86
    }
87
}
88