-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathModel.php
More file actions
137 lines (108 loc) · 3.16 KB
/
Model.php
File metadata and controls
137 lines (108 loc) · 3.16 KB
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
132
133
134
135
136
137
<?php
declare(strict_types=1);
namespace PHPCensor;
use DateTime;
use Exception;
/**
* @package PHP Censor
* @subpackage Application
*
* @author Dan Cryer <dan@block8.co.uk>
* @author Dmitry Khomutov <poisoncorpsee@gmail.com>
*/
class Model
{
protected array $data = [];
protected array $dataTypes = [];
private array $modified = [];
protected StoreRegistry $storeRegistry;
public function __construct(
StoreRegistry $storeRegistry,
array $initialData = []
) {
if (!isset($this->dataTypes['id'])) {
$this->dataTypes['id'] = 'integer';
}
foreach ($initialData as $column => $value) {
$this->setDataItem($column, $this->castToDataType($this->getDataType($column), $value));
}
$this->storeRegistry = $storeRegistry;
}
public function getDataType(string $column): string
{
return $this->dataTypes[$column] ?? 'string';
}
protected function getDataItem(string $column, $defaultValue = null)
{
return $this->castToDataType($this->getDataType($column), $this->data[$column] ?? $defaultValue);
}
protected function setDataItem(string $column, $value): bool
{
if (!\array_key_exists($column, $this->data) || $this->data[$column] === $value) {
return false;
}
$this->data[$column] = $value;
$this->modified[$column] = $column;
return true;
}
public function getDataArray(): array
{
return $this->data;
}
public function getModified(): array
{
return $this->modified;
}
/**
* @return mixed
*/
private function castToDataType(string $type, $value)
{
if ($value === null) {
return null;
}
switch ($type) {
case 'int':
case 'integer':
return \is_integer($value) ? $value : \intval($value);
case 'bool':
case 'boolean':
return \is_bool($value) ? $value : \boolval($value);
case 'float':
return \is_float($value) ? $value : \floatval($value);
case 'array':
return \is_array($value) ? $value : \json_decode($value, true);
case 'datetime':
if (\is_a($value, DateTime::class)) {
return $value;
}
try {
return new DateTime($value);
} catch (\Throwable $e) {
return null;
}
case 'newline':
if (!\is_string($value)) {
return $value;
}
return \array_values(
\array_filter(
\array_map(
'trim',
\explode("\n", $value)
)
)
);
default:
return $value;
}
}
public function getId(): ?int
{
return $this->getDataItem('id');
}
public function setId(?int $value): bool
{
return $this->setDataItem('id', $value);
}
}