Completed
Pull Request — master (#2)
by René
16:36 queued 06:34
created

EntityProperty::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
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
    /**
20
     * @param string $type
21
     */
22
    public function __construct(string $type)
23
    {
24
        $this->type = $type;
25
    }
26
27
    /**
28
     * Format value according to entity property type
29
     *
30
     * @param mixed $value Value
31
     *
32
     * @return mixed Value
33
     */
34
    public function formatValueForEntity($value)
35
    {
36
        switch ($this->type) {
37
            case 'string':
38
                $value = "$value";
39
                break;
40
41
            case 'integer':
42
                $value = (int)$value;
43
                break;
44
45
            case 'float':
46
                $value = (float)$value;
47
                break;
48
49
            case 'date':
50
            case 'datetime':
51
                $value = new \DateTime($value);
52
                break;
53
        }
54
55
        return $value;
56
    }
57
58
    /**
59
     * Format value for insertion into the database
60
     *
61
     * @param mixed $value Value
62
     *
63
     * @return mixed Value
64
     */
65
    public function formatValueForDatabase($value)
66
    {
67
        switch ($this->type) {
68
            case 'date':
69
                /**
70
                 * @var \DateTime $value
71
                 */
72
                $value = $value->format('Y-m-d');
73
                break;
74
75
            case 'datetime':
76
                /**
77
                 * @var \DateTime $value
78
                 */
79
                $value = $value->format('Y-m-d H:i:s');
80
                break;
81
        }
82
83
        return $value;
84
    }
85
}
86