-
Notifications
You must be signed in to change notification settings - Fork 0
/
AttributeValue.php
131 lines (111 loc) · 2.93 KB
/
AttributeValue.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
<?php
declare(strict_types=1);
namespace MsgPhp\Eav;
use MsgPhp\Eav\Model\AttributeField;
/**
* @author Roland Franssen <franssen.roland@gmail.com>
*/
abstract class AttributeValue
{
use AttributeField;
/** @var null|bool */
private $boolValue;
/** @var null|int */
private $intValue;
/** @var null|float */
private $floatValue;
/** @var null|string */
private $stringValue;
/** @var null|\DateTimeInterface */
private $dateTimeValue;
/** @var string */
private $checksum;
/** @var bool */
private $isNull;
/** @var mixed */
private $value;
/**
* @param mixed $value
*/
public function __construct(Attribute $attribute, $value)
{
$this->attribute = $attribute;
$this->changeValue($value);
}
/**
* @param mixed $value
*/
public static function getChecksum($value): string
{
return md5(serialize([\is_object($value) ? \get_class($value) : \gettype($value), static::getIdentityValue($value)]));
}
abstract public function getId(): AttributeValueId;
/**
* @return mixed
*/
final public function getValue()
{
if ($this->isNull) {
return null;
}
if (null !== $this->value) {
return $this->value;
}
if (null === $value = $this->doGetValue()) {
$this->isNull = true;
}
return $this->value = $value;
}
/**
* @param mixed $value
*/
final public function changeValue($value): void
{
$this->doClearValue();
$this->isNull = null === $value;
if (!$this->isNull) {
$this->doSetValue($value);
}
$this->value = $value;
$this->checksum = static::getChecksum($value);
}
/**
* @param mixed $value
*
* @return mixed
*/
protected static function getIdentityValue($value)
{
return $value;
}
protected function doClearValue(): void
{
$this->boolValue = $this->intValue = $this->floatValue = $this->stringValue = $this->dateTimeValue = null;
}
/**
* @param mixed $value
*/
protected function doSetValue($value): void
{
if (\is_bool($value)) {
$this->boolValue = $value;
} elseif (\is_int($value)) {
$this->intValue = $value;
} elseif (\is_float($value)) {
$this->floatValue = $value;
} elseif (\is_string($value)) {
$this->stringValue = $value;
} elseif ($value instanceof \DateTimeInterface) {
$this->dateTimeValue = $value;
} else {
throw new \LogicException('Unsupported attribute value type "'.\gettype($value).'".');
}
}
/**
* @return mixed
*/
protected function doGetValue()
{
return $this->boolValue ?? $this->intValue ?? $this->floatValue ?? $this->stringValue ?? $this->dateTimeValue;
}
}