-
Notifications
You must be signed in to change notification settings - Fork 0
/
BaseModel.php
335 lines (274 loc) · 8.96 KB
/
BaseModel.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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
<?php
namespace Framework\Database;
use Exception;
use Framework\Database\Exception\DeleteOperationNotAllowedException;
use Framework\Database\Exception\EditOperationNotAllowedException;
use Framework\Database\Query\ColType;
use Framework\Database\Query\Condition;
use Framework\Database\Query\SortOrder;
use Framework\Database\Query\WhereQueryBuilder;
use Framework\Facades\Http;
/**
* The BaseModel provides helper functions e.g. to get the table name, get a initialized query builder and
* type save getter and setter functions.
*
* It also supports optional `allow` functions (`allowEdit` and `allowDelete`) that are called if a model
* implements them. If the return value is not true, the edit or delete operation throws an `OperationNotAllowedException`.
*/
abstract class BaseModel
{
public static array $orderBy = [];
protected const ID = 'id';
public function __construct(
protected array $data = []
) {
}
/**
* Create a new instance of the own class:
* `return new self($data);`
*/
abstract protected static function new(array $data = []): self;
/**
* Insert or update the model into the database.
* If getId() === null, then insert else update.
*/
abstract public function save(): self;
protected function checkAllowEdit(): void
{
if (method_exists($this, 'allowEdit')) {
if (!$this->allowEdit()) {
throw new EditOperationNotAllowedException();
}
}
}
/* Static functions */
public static function getQueryBuilder(): WhereQueryBuilder
{
return new WhereQueryBuilder(static::getTableName());
}
public static function all(WhereQueryBuilder $query = null): array
{
if ($query === null) {
$query = static::getQueryBuilder();
}
// Use default sort order if it is defined in the model and if no sort order is set via the query builder
if (!$query->hasOrderBySection() && count(static::$orderBy) > 0) {
foreach (static::$orderBy as $field => $sortOrderStr) {
$sortOrder = strtolower($sortOrderStr) === 'asc' ? SortOrder::Asc : SortOrder::Desc;
$query->orderBy($field, $sortOrder);
}
}
$dataSet = Database::executeBuilder($query);
if ($dataSet === false) {
return [];
}
$all = [];
while ($row = $dataSet->fetch()) {
array_push($all, static::new($row));
}
return $all;
}
public static function find(WhereQueryBuilder $query): self
{
$results = static::all($query);
if ($results === []) {
return static::new();
}
return $results[0];
}
public static function findById(int $id): self
{
return static::find(static::getQueryBuilder()->where(ColType::Int, 'id', Condition::Equal, $id));
}
public static function delete(int $id): void
{
$model = static::findById($id);
if ($model->getId() === null) {
return;
}
if (method_exists($model, 'allowDelete')) {
if (!$model->allowDelete()) {
throw new DeleteOperationNotAllowedException();
}
}
Database::prepared('DELETE FROM ' . static::getTableName() . ' WHERE id=?', 'i', $id);
}
/* Getter */
public function getId(): ?int
{
return $this->getDataIntOrNull(static::ID);
}
/* Magical getter and setter */
public function __call(string $name, array $arguments): mixed
{
// e.g. get('lastname')
if ($name === 'get') {
if (count($arguments) !== 1) {
throw new Exception('Getter function expects only one argument');
}
return $this->getData($arguments[0]);
}
// e.g. set('username', 'myusername')
if ($name === 'set') {
if (count($arguments) !== 2) {
throw new Exception('Getter function expects two arguments');
}
return $this->setData($arguments[0], $arguments[1]);
}
// e.g. getLastname() or setUsername('myusername')
if (!str_starts_with($name, 'get') && !str_starts_with($name, 'set')) {
return null;
}
$prefix = substr($name, 0, 3);
$property = lcfirst(str_replace($prefix, '', $name));
if ($prefix === 'get') {
return $this->getData($property);
}
if ($prefix === 'set') {
if (count($arguments) !== 1) {
throw new Exception('Setter functions expects only one argument');
}
return $this->setData($property, $arguments[0]);
}
}
public function setFromHttpParams(array $fields): self
{
foreach ($fields as $field) {
$this->setFromHttpParam($field);
}
return $this;
}
public function setFromHttpParam(string $field, string $param = null): self
{
if ($param === null) {
$param = $field;
}
$this->setData($field, Http::param($param));
return $this;
}
/* Getter & Setter - Bool */
protected function getDataBoolOrNull(string $field): ?bool
{
return $this->getData($field) !== null ? $this->getDataBool($field) : null;
}
protected function getDataBool(string $field): bool
{
return (bool)$this->getData($field);
}
protected function setDataBoolOrNull(string $field, ?bool $value): self
{
if ($this->getDataBoolOrNull($field) === $value) {
return $this;
}
return $this->setData($field, $value);
}
protected function setDataBool(string $field, bool $value): self
{
if ($this->getDataBool($field) === $value) {
return $this;
}
return $this->setData($field, $value);
}
/* Getter & Setter - Float */
protected function getDataFloatOrNull(string $field): ?float
{
return $this->getData($field) !== null ? $this->getDataFloat($field) : null;
}
protected function getDataFloat(string $field): float
{
return (float)$this->getData($field);
}
protected function setDataFloatOrNull(string $field, ?float $value): self
{
if ($this->getDataFloatOrNull($field) === $value) {
return $this;
}
return $this->setData($field, $value);
}
protected function setDataFloat(string $field, float $value): self
{
if ($this->getDataFloat($field) === $value) {
return $this;
}
return $this->setData($field, $value);
}
/* Getter & Setter - Integer */
protected function getDataIntOrNull(string $field): ?int
{
return $this->getData($field) !== null ? $this->getDataInt($field) : null;
}
protected function getDataInt(string $field): int
{
return (int)$this->getData($field);
}
protected function setDataIntOrNull(string $field, ?int $value): self
{
if ($this->getDataIntOrNull($field) === $value) {
return $this;
}
return $this->setData($field, $value);
}
protected function setDataInt(string $field, int $value): self
{
if ($this->getDataInt($field) === $value) {
return $this;
}
return $this->setData($field, $value);
}
/* Getter & Setter - String */
protected function getDataStringOrNull(string $field): ?string
{
return $this->getData($field) !== null ? $this->getDataString($field) : null;
}
protected function getDataString(string $field): string
{
return (string)$this->getData($field);
}
protected function setDataStringOrNull(string $field, ?string $value): self
{
if ($this->getDataStringOrNull($field) === $value) {
return $this;
}
return $this->setData($field, $value);
}
protected function setDataString(string $field, string $value): self
{
if ($this->getDataString($field) === $value) {
return $this;
}
return $this->setData($field, $value);
}
/* Helper functions */
private function getData(string $field): mixed
{
if (!array_key_exists($field, $this->data)) {
return null;
}
return $this->data[$field];
}
private function setData(string $field, mixed $value): self
{
$this->data[$field] = $value;
return $this;
}
protected static function getTableName(): string
{
$classNameParts = explode('\\', get_called_class());
$className = $classNameParts[count($classNameParts) - 1];
$tableName = lcfirst($className) . 's';
return $tableName;
}
}
/*
<?php
namespace System\Modules\DataObjects;
abstract class AbstractModel implements IObject
{
public function toArray(): array
{
$result = [];
array_push($result, ...$this->data);
return $result;
}
}
*/