Completed
Branch feature/pre-split (656bce)
by Anton
04:24
created

EnumColumn::hasChanges()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * components
4
 *
5
 * @author    Wolfy-J
6
 */
7
8
namespace Spiral\ORM\Columns;
9
10
use Spiral\Database\Schemas\Prototypes\AbstractColumn;
11
use Spiral\ORM\ColumnInterface;
12
use Spiral\ORM\Exceptions\AccessorException;
13
use Spiral\ORM\Exceptions\EnumException;
14
use Spiral\ORM\RecordAccessorInterface;
15
16
/**
17
 * Mocks enums values and provides ability to describe associated AbstractColumn via set of
18
 * configuration constants.
19
 */
20
class EnumColumn implements RecordAccessorInterface, ColumnInterface
21
{
22
    /**
23
     * Set of allowed enum values.
24
     */
25
    const VALUES  = [];
26
27
    /**
28
     * Default value.
29
     */
30
    const DEFAULT = null;
31
32
    /**
33
     * @var bool
34
     */
35
    private $changed = false;
36
37
    /**
38
     * @var string
39
     */
40
    private $value;
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    public function __construct(string $value)
46
    {
47
        $this->value = $value;
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53
    public function stateValue($data)
54
    {
55
        if (!in_array($data, static::VALUES)) {
56
            throw new AccessorException("Unable to set enum value, invalid value given");
57
        }
58
59
        $this->value = $data;
60
        $this->changed = true;
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66
    public function packValue(): string
67
    {
68
        return $this->value;
69
    }
70
71
    /**
72
     * {@inheritdoc}
73
     */
74
    public function hasChanges(): bool
75
    {
76
        return $this->changed;
77
    }
78
79
    /**
80
     * {@inheritdoc}
81
     */
82
    public function flushChanges()
83
    {
84
        $this->changed = false;
85
    }
86
87
    /**
88
     * {@inheritdoc}
89
     */
90
    public function compileUpdates(string $field = '')
91
    {
92
        return $this->value;
93
    }
94
95
    /**
96
     * {@inheritdoc}
97
     */
98
    public function __toString()
99
    {
100
        return $this->packValue();
101
    }
102
103
    /**
104
     * {@inheritdoc}
105
     */
106
    public function jsonSerialize()
107
    {
108
        return $this->packValue();
109
    }
110
111
    /**
112
     * {@inheritdoc}
113
     */
114
    public static function describeColumn(AbstractColumn $column)
115
    {
116
        if (empty(static::VALUES)) {
117
            throw new EnumException("Unable to describe enum column, no values are given");
118
        }
119
120
        $column->enum(static::VALUES);
121
122
        if (!empty(static::DEFAULT)) {
123
            $column->defaultValue(static::DEFAULT)->nullable(false);
124
        }
125
    }
126
}