This repository was archived by the owner on Dec 31, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathEntity.php
More file actions
342 lines (305 loc) · 9.03 KB
/
Entity.php
File metadata and controls
342 lines (305 loc) · 9.03 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
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
336
337
338
339
340
341
342
<?php
/**
* AVOLUTIONS
*
* Just another open source PHP framework.
*
* @copyright Copyright (c) 2019 - 2021 AVOLUTIONS
* @license MIT License (https://avolutions.org/license)
* @link https://avolutions.org
*/
namespace Avolutions\Orm;
use Avolutions\Core\Application;
use Avolutions\Database\Database;
use Avolutions\Event\EntityEvent;
use Avolutions\Event\EventDispatcher;
use Avolutions\Logging\Logger;
use ReflectionClass;
/**
* Entity class
*
* An entity represents a clearly identified object from an entity collection.
* It provides the methods for manipulating the Entity with CRUD operations.
*
* @author Alexander Vogt <alexander.vogt@avolutions.org>
* @since 0.1.0
*/
class Entity
{
/**
* The unique identifier of the entity.
*
* @var int|null $id
*/
public ?int $id = null;
/**
* The configuration of the entity.
*
* @var EntityConfiguration $EntityConfiguration
*/
private EntityConfiguration $EntityConfiguration;
/**
* The mapping of the entity.
*
* @var EntityMapping $EntityMapping
*/
private EntityMapping $EntityMapping;
/**
* The Entity after initializing.
*
* @var Entity $EntityBeforeChange
*/
private Entity $EntityBeforeChange;
/**
* Validation error messages.
*
* @var array $errors
*/
private array $errors = [];
/**
* __construct
*
* Creates a new Entity object and loads the corresponding EntityConfiguration
* and EntityMapping.
*
* @param array $values The Entity attributes as an array
*/
public function __construct(array $values = [])
{
$this->EntityConfiguration = new EntityConfiguration($this->getEntityName());
$this->EntityMapping = $this->EntityConfiguration->getMapping();
// Fill Entity attributes from values
if (!empty($values)) {
foreach ($this->EntityMapping as $key => $value) {
if (isset($values[$key])) {
// If the property is of type Entity
if ($value['isEntity']) {
// Create a the linked Entity and pass the values
$entityName = Application::getModelNamespace().$value['type'];
$this->$key = new $entityName($values[$key]);
} else {
$this->$key = $values[$key];
}
}
}
}
$this->EntityBeforeChange = clone $this;
}
/**
* save
*
* Saves the Entity object to the database. It will be either updated or inserted,
* depending on whether the Entity already exists or not.
*/
public function save()
{
EventDispatcher::dispatch(new EntityEvent('BeforeSave', $this));
if ($this->exists()) {
EventDispatcher::dispatch(new EntityEvent('BeforeUpdate', $this, $this->EntityBeforeChange));
$this->update();
EventDispatcher::dispatch(new EntityEvent('AfterUpdate', $this, $this->EntityBeforeChange));
} else {
EventDispatcher::dispatch(new EntityEvent('BeforeInsert', $this));
$this->insert();
EventDispatcher::dispatch(new EntityEvent('AfterInsert', $this));
}
EventDispatcher::dispatch(new EntityEvent('AfterSave', $this));
}
/**
* delete
*
* Deletes the Entity object from the database.
*/
public function delete()
{
EventDispatcher::dispatch(new EntityEvent('BeforeDelete', $this));
$values = ['id' => $this->id];
$query = 'DELETE FROM ';
$query .= $this->EntityConfiguration->getTable();
$query .= ' WHERE ';
$query .= $this->EntityConfiguration->getIdColumn();
$query .= ' = :id';
$this->execute($query, $values);
EventDispatcher::dispatch(new EntityEvent('AfterDelete', $this));
}
/**
* getEntityName
*
* Returns the shortname of the reflected class.
*
* @return string The name of the entity.
*/
public function getEntityName(): string
{
return (new ReflectionClass($this))->getShortName();
}
/**
* getErrors
*
* Returns all validation error messages.
*
* @return array Validation error messages.
*/
public function getErrors(): array
{
return $this->errors;
}
/**
* insert
*
* Inserts the Entity object into the database.
*/
private function insert()
{
$values = [];
$columns = [];
$parameters = [];
foreach ($this->EntityMapping as $key => $value) {
// Only for simple fields, no Entities
if (!$value['isEntity']) {
$columns[] = $value['column'];
$parameters[] = ':'.$key;
$values[$key] = $this->$key;
}
}
$query = 'INSERT INTO ';
$query .= $this->EntityConfiguration->getTable();
$query .= ' (';
$query .= implode(', ', $columns);
$query .= ') VALUES (';
$query .= implode(', ', $parameters);
$query .= ')';
$this->id = $this->execute($query, $values);
}
/**
* update
*
* Updates the existing database entry for the Entity object.
*/
private function update()
{
$values = [];
$query = 'UPDATE ';
$query .= $this->EntityConfiguration->getTable();
$query .= ' SET ';
foreach ($this->EntityMapping as $key => $value) {
// Only for simple fields, no Entities
if (!$value['isEntity']) {
$query .= $value['column'].' = :'.$key.', ';
$values[$key] = $this->$key;
}
}
$query = rtrim($query, ', ');
$query .= ' WHERE ';
$query .= $this->EntityConfiguration->getIdColumn();
$query .= ' = :id';
$this->execute($query, $values);
}
/**
* exists
*
* Checks if the Entity already exists in the database.
*
* @return bool Returns true if the entity exists in the database, false if not.
*/
public function exists(): bool
{
return $this->id != null;
}
/**
* execute
*
* Executes the previously created database query with the provided values.
*
* @param string $query The query string that will be executed.
* @param array $values The values for the query.
*
* @return string TODO
*/
private function execute(string $query, array $values): string
{
Logger::debug($query);
Logger::debug('Values: '.print_r($values, true));
$Database = new Database();
$stmt = $Database->prepare($query);
$stmt->execute($values);
return $Database->lastInsertId();
}
/**
* isValid
*
* Checks if entity was validated successfully last time by checking if errors are set or not.
*
* @return bool Returns true if Entity has no errors or false if it has errors.
*/
public function isValid(): bool
{
return count($this->errors) == 0;
}
/**
* validate
*
* Validates the Entity by using the Validators specified in mapping file.
* If a property is not valid the error message of the Validator will be added to the error array.
*
* @return bool Returns true if all validations passed or false if not.
*/
public function validate(): bool
{
foreach ($this->EntityMapping as $property => $value) {
if (isset($value['validation'])) {
foreach ($value['validation'] as $validator => $options) {
$fullValidatorName = 'Avolutions\\Validation\\'.ucfirst($validator).'Validator';
if (!class_exists($fullValidatorName)) {
// if validator can not be found in core namespace try in application namespace
$fullValidatorName = Application::getValidatorNamespace().ucfirst($validator).'Validator';
}
$Validator = new $fullValidatorName($options, $property, $this);
if (!$Validator->isValid($this->$property)) {
$this->errors[$property][$validator] = $Validator->getMessage();
}
}
}
}
return $this->isValid();
}
/**
* toArray
*
* Converts the Entity to an array.
*
* @param bool $includeEntities Whether to include entity-type properties or not.
*
* @return array
*/
public function toArray($includeEntities = false): array
{
$array = [];
foreach ($this->EntityMapping as $property => $value) {
if (!$value['isEntity']) {
$array[$property] = $this->$property ?? null;
} elseif ($includeEntities) {
if (!isset($this->$property)) {
$array[$property] = null;
} else {
$array[$property] = $this->$property->toArray();
}
}
}
return $array;
}
/**
* toJSON
*
* Converts the Entity to JSON.
*
* @param bool $includeEntities Whether to include entity-type properties or not.
*
* @return array
*/
public function toJSON($includeEntities = false): string
{
$array = $this->toArray($includeEntities);
return json_encode($array);
}
}