-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEntity.php
778 lines (668 loc) · 22 KB
/
Entity.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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
<?php
// There be dragons lurking around in this file,
// may Gods be with you if you have to debug it.
namespace Core;
use Core\Attributes\Table;
use Core\Attributes\PrimaryKey;
use Core\Attributes\Traceable;
use Core\Attributes\TraceLazyLoad;
/**
* Base class for database models
* You should define all types of all variables in your class
*
* @author azcraft
*/
abstract class Entity
{
/**
* Used for resolving traceable references
* @var array
*/
private static array $referencedLists = [];
/**
* Caching all objects
* @var array
*/
private static array $objectCache = [];
/**
* List of loaded entity classes
* @var array
*/
private static array $initialized = [];
/**
* Caches table names. Used by getTableName()
* @var array
*/
private static array $tableNamesCache;
/**
* Caches primary keys names. Used by getPrimaryKeys()
* @var array
*/
private static array $primaryKeysCache;
/**
* Cache use count. (Debugging Stats)
* @var int
*/
private static int $cacheUsed = 0;
/**
* Loaded SQL Objects. (Debugging Stats)
* @var int
*/
private static int $entitiesLoaded = 0;
/**
* Done SQL Queries. (Debugging Stats)
* @var int
*/
private static int $queriesDone = 0;
/**
* Current object's id
* @var int|array
*/
private $id;
/**
* Populates $referencedFrom
* Includes all referenced classes (autoloader)
* @return void
*/
public static function init(): void {
$class = get_called_class();
if (in_array($class, self::$initialized)){
return;
}
self::$initialized[] = $class;
self::$objectCache[$class] = [];
self::$referencedLists[$class] = [];
$entity = new \ReflectionClass($class);
$isEntityFilter = function (\ReflectionProperty $property){
if ($property->isStatic()){
return false;
}
$type = $property->getType();
if (!isset($type) || $type->isBuiltin()){
return false;
}
return isEntity($type->getName());
};
$flags = \ReflectionProperty::IS_PROTECTED | \ReflectionProperty::IS_PUBLIC;
$properties = array_filter($entity->getProperties($flags), $isEntityFilter);
foreach ($properties as $property){
$typeName = $property->getType()->getName();
if (!isset(self::$referencedLists[$typeName])){
self::$referencedLists[$typeName] = [];
}
self::$referencedLists[$typeName][] = $property;
}
}
/**
* Creates an object in the database
* @throws Exception
*/
public function __construct() {
$dbh = self::getPDO();
$tableName = self::getTableName();
$properties = $this->getDefinedProperties();
$data = self::simplifyData($properties);
$keys = array_keys($data);
$prefixedKeys = array_map(function ($k){
return ":$k";
}, $keys);
$statement_columns = implode(", ", $keys);
$statement_values = implode(", ", $prefixedKeys);
$statement = $dbh->prepare(<<<EOF
INSERT INTO $tableName($statement_columns)
VALUES ($statement_values);
EOF);
self::$queriesDone++;
if (defined("DEBUG_PRINT_QUERY_TYPES")){
echo get_called_class() . " [SQL] insert element. <br />\n";
}
foreach ($keys as $key){
$statement->bindParam($key, $data[$key]);
}
$statement->execute();
$this->resolveId(true);
$class = get_called_class();
$id = $this->getId();
if (!is_array($id)){
$id = [$id];
}
$idHash = self::hashIds($id);
self::$objectCache[$class][$idHash] = &$this;
}
/**
* Sets id after inserting element
* @return void
*/
private function resolveId(bool $justInserted = false): void {
if (isset($this->id)){
return;
}
$keys = self::getPrimaryKeys();
$defined = true;
$values = [];
foreach ($keys as $key){
if (!isset($this->$key)){
$defined = false;
break;
}
$values[] = $this->$key;
}
if ($defined){
$values = self::simplifyData($values);
$this->setId(...$values);
} else if (count($keys) == 1 && $justInserted){
$pdo = self::getPDO();
$this->setId($pdo->lastInsertId());
} else {
throw new Exception("Can not resolve id of inserted element.");
}
}
/**
* Sets properties of this object from given associative array
* @param array $data
* @return void
*/
private function morph(array $data): void {
self::$entitiesLoaded++;
$entity = new \ReflectionClass($this);
$flags = \ReflectionProperty::IS_PROTECTED | \ReflectionProperty::IS_PUBLIC;
$properties = $entity->getProperties($flags);
foreach ($properties as $property){
$name = $property->getName();
if ($property->isStatic() || !isset($data[$name])){
continue;
}
$type = $property->getType();
$typeName = $type->getName();
if (!$type->isBuiltin()){
if ($typeName == 'DateTime'){
$data[$name] = new \DateTime($data[$name]);
$this->$name = $data[$name];
continue;
}
if (isEntity($typeName)){
$class = new \ReflectionClass($typeName);
$parent = $class->getParentClass();
if ($parent == new \ReflectionClass(get_class())){
$className = $class->getName();
$data[$name] = $className::get($data[$name]);
}
}
}
$this->$name = $data[$name];
}
}
/**
* Returns the entity's id
* @return mixed|array
*/
public function getId() {
return $this->id;
}
/**
* Defines id of entity
* @param mixed|array $id
* @return void
*/
protected function setId(...$id): void {
if (count($id) == 1){
$this->id = $id[0];
} else {
$this->id = $id;
}
}
/**
* Saves the object in the database
* @throws Exception
* @return void
*/
public function save(): void {
$this->resolveId();
$dbh = self::getPDO();
$entity = new \ReflectionClass($this);
$tableName = self::getTableName();
$id_keys = self::getPrimaryKeys();
$properties = $this->getDefinedProperties();
$data = self::simplifyData($properties);
$keys = array_keys($data);
$queryCondition = "$id_keys[0] = :$id_keys[0]";
for ($i = 1; $i < count($id_keys); $i++){
$key = $id_keys[$i];
$queryCondition .= " AND $key = :$key";
}
$set_clause = "";
if (count($keys)){
$conditions = array_map(function ($key){
return "$key = :$key";
}, $keys);
$set_clause = implode(', ', $conditions);
}
$statement = $dbh->prepare(<<<EOF
UPDATE $tableName
SET $set_clause
WHERE $queryCondition;
EOF);
self::$queriesDone++;
if (defined("DEBUG_PRINT_QUERY_TYPES")){
echo get_called_class() . " [SQL] save element. <br />\n";
}
foreach ($keys as $key){
$statement->bindParam($key, $data[$key]);
}
$id = $this->getId();
if (!is_array($id) && isset($id))
$id = [$id];
$id = self::simplifyData($id);
for($k = 0; $k < count($id_keys); $k++)
$statement->bindParam($id_keys[$k], $id[$k]);
$statement->execute();
$this->setId(...$id);
}
/**
* Reloads object from database.
* It's not recursive.
* @return void
*/
public function load(): void {
$this->resolveId();
$dbh = self::getPDO();
$tableName = self::getTableName();
$keys = self::getPrimaryKeys();
$id = $this->getId();
if (!is_array($id) && isset($id)){
$id = [$id];
}
if (count($id) == 0 || count($id) != count($keys)){
throw new Exception("Incorrect number of primary keys.");
}
$queryCondition = "$keys[0] = ?";
for ($i = 1; $i < count($keys); $i++){
$key = $keys[$i];
$queryCondition .= " AND $key = ?";
}
$statement = $dbh->prepare(<<<EOF
SELECT *
FROM $tableName
WHERE $queryCondition;
EOF);
self::$queriesDone++;
if (defined("DEBUG_PRINT_QUERY_TYPES")){
echo get_called_class() . " [SQL] load element. <br />\n";
}
$statement->execute($id);
$data = $statement->fetch(\PDO::FETCH_ASSOC);
if ($data){
$this->morph($data);
}
}
/**
* Returns an object by primary key
* @param mixed|array $id
* @return Entity
*/
public static function &get(...$id): ?Entity {
$dbh = self::getPDO();
$className = get_called_class();
$tableName = self::getTableName();
$keys = self::getPrimaryKeys();
if (count($id) == 0 || count($id) != count($keys)){
throw new Exception("Incorrect number of primary keys.");
}
$id = self::simplifyData($id);
$idHash = self::hashIds($id);
if (isset(self::$objectCache[$className][$idHash])){
self::$cacheUsed++;
return self::$objectCache[$className][$idHash];
}
$queryCondition = "$keys[0] = ?";
for ($i = 1; $i < count($keys); $i++){
$key = $keys[$i];
$queryCondition .= " AND $key = ?";
}
$statement = $dbh->prepare(<<<EOF
SELECT *
FROM $tableName
WHERE $queryCondition;
EOF);
self::$queriesDone++;
if (defined("DEBUG_PRINT_QUERY_TYPES")){
echo get_called_class() . " [SQL] get element. <br />\n";
}
$statement->execute($id);
$data = $statement->fetch(\PDO::FETCH_ASSOC);
if (!$data){
$dummy = null;
return $dummy;
}
$entity = new \ReflectionClass($className);
$object = $entity->newInstanceWithoutConstructor();
self::$objectCache[$className][$idHash] = &$object;
$object->setId(...$id);
$object->morph($data);
return $object;
}
/**
* Returns an object
* @param array $conditions
* @return Entity[]
*/
public static function find(array $conditions): array {
$dbh = self::getPDO();
$tableName = self::getTableName();
$primaryKeys = self::getPrimaryKeys();
$data = self::simplifyData($conditions);
$keys = array_keys($data);
$conditionString = "";
if (count($keys)){
$conditions = array_map(function ($key){
return "$key = :$key";
}, $keys);
$conditionString = "WHERE " . implode(' AND ', $conditions);
}
$statement = $dbh->prepare(<<<EOF
SELECT *
FROM $tableName
$conditionString;
EOF);
self::$queriesDone++;
if (defined("DEBUG_PRINT_QUERY_TYPES")){
echo get_called_class() . " [SQL] find elements. <br />\n";
}
foreach ($keys as $key){
$statement->bindParam($key, $data[$key]);
}
$statement->execute();
$objects = [];
$className = get_called_class();
while ($data = $statement->fetch(\PDO::FETCH_ASSOC)){
$id = [];
foreach ($primaryKeys as $prim){
$id[] = $data[$prim];
}
$idHash = self::hashIds($id);
if (isset(self::$objectCache[$className][$idHash])){
self::$cacheUsed++;
$objects[] = &self::$objectCache[$className][$idHash];
continue;
}
$entity = new \ReflectionClass($className);
self::$objectCache[$className][$idHash] =
$entity->newInstanceWithoutConstructor();
$object = &self::$objectCache[$className][$idHash];
$object->setId(...$id);
$object->morph($data);
$objects[] = &$object;
}
return $objects;
}
/**
* Deletes object from database by primary key
* @param mixed|array $id
* @return void
*/
public static function delete(...$id): void {
$dbh = self::getPDO();
$class = get_called_class();
$tableName = self::getTableName();
$keys = self::getPrimaryKeys();
if (count($id) == 1 && count($keys) > 1 && $id[0] instanceof self){
self::delete(...$id[0]->getId());
return;
}
if (!count($id) || count($keys) != count($id)){
throw new Exception("Incorrect number of primary keys.");
}
$id = self::simplifyData($id);
$condition = "$keys[0] = ?";
for ($i = 1; $i < count($keys); $i++){
$condition .= " AND $keys[$i] = ?";
}
$statement = $dbh->prepare(<<<EOF
DELETE FROM $tableName
WHERE $condition;
EOF);
self::$queriesDone++;
if (defined("DEBUG_PRINT_QUERY_TYPES")){
echo get_called_class() . " [SQL] delete element. <br />\n";
}
$statement->execute($id);
$idHash = self::hashIds($id);
if (isset(self::$objectCache[$class][$idHash])){
unset(self::$objectCache[$class][$idHash]);
}
}
/**
* Returns defined properties as associative array
* @return array
*/
private function getDefinedProperties(): array {
$entity = new \ReflectionObject($this);
$flags = \ReflectionProperty::IS_PROTECTED | \ReflectionProperty::IS_PUBLIC;
$properties = $entity->getProperties($flags);
$data = [];
foreach ($properties as $property){
if (!$property->isStatic()){
$name = $property->getName();
if (isset($this->$name)){
$data[$name] = $this->$name;
}
}
}
return $data;
}
private static function simplifyData(array $data): array {
$data = self::resolveReferences($data);
foreach($data as $key => $value){
if (gettype($value) == "boolean"){
$data[$key] = $value ? 1 : 0;
}
}
return $data;
}
/**
* Replaces Entities with their id.
* @param array $properties Output from getDefinedProperties.
* @return array
*/
private static function resolveReferences(array $properties): array {
foreach ($properties as $key => $value){
if ($value instanceof Entity){
$properties[$key] = $value->getId();
}
if ($value instanceof \DateTime){
$properties[$key] = $value->format("Y-m-d H:i:s");
}
}
return $properties;
}
/**
* Returns the active PDO connection or throws exception
* @return PDO
*/
public static function getPDO(): \PDO {
$dbh = Controller::getPDO();
if ($dbh == null){
throw new Exception("You may not use Entities without specifying database.");
}
return $dbh;
}
/**
* Prints statistics about database and cache usage.
* @return void
*/
public static function printDebugStats(): void {
echo "MySQL Queries: " . self::$queriesDone . " queries <br />\n";
echo "Loaded entities: " . self::$entitiesLoaded . " entities <br />\n";
echo "Cache used: " . self::$cacheUsed . " times <br />\n";
}
/**
* Covers user-selected reference tracing functions
* @param string $method
* @param array $arguments
*/
public function __call(string $method, array $arguments) {
$className = get_called_class();
$traces = $this->getReferenceTraces();
if (!in_array($method, array_keys($traces))){
self::loadLazyTrace($method);
$traces = $this->getReferenceTraces();
}
if (isset($traces[$method])){
$property = $traces[$method];
$targetClass = $property->class;
$propertyName = $property->getName();
$condition = [];
if (isset($arguments[0]) && is_array($arguments[0])){
$condition = $arguments[0];
}
$condition[$propertyName] = $this;
return $targetClass::find($condition);
}
throw new Exception("$className::$method is not initialized.");
}
/**
* Loads methods named with TraceLazyLoad attribute on demand
* @param string $method
* @return void
*/
private static function loadLazyTrace(string $method): void {
$self = new \ReflectionClass(get_called_class());
$attributes = $self->getAttributes();
foreach ($attributes as $attribute){
$instance = $attribute->newInstance();
if (!($instance instanceof TraceLazyLoad)){
continue;
}
if ($instance->contains($method)){
$instance->load();
return;
}
}
}
/**
* Returns list of traceable references.
* This function is only for debugging.
* @return array
*/
public static function listReferenceTraces(): array {
$info = [];
$self = new \ReflectionClass(get_called_class());
$attributes = $self->getAttributes();
foreach ($attributes as $attribute){
$instance = $attribute->newInstance();
if (!($instance instanceof TraceLazyLoad)){
continue;
}
$class = $instance->className();
foreach ($instance->methods() as $method){
$info[$method] = "Can be lazy loaded from $class";
}
}
$traces = self::getReferenceTraces();
foreach ($traces as $trace => $property){
$className = $property->class;
$shortName = $property->getDeclaringClass()->getShortName();
$propertyName = $property->getName();
$info[$trace] = "Performs find() operation on $className";
$info[$trace] .= " where $shortName::$propertyName == \$this";
}
return $info;
}
/**
* Returns array of pairs ($parameter, $method)
* $parameter is the parameter that references this class.
* $method is the name of the method that this class need to have
* @return array
*/
private static function getReferenceTraces(): array {
$name = get_called_class();
$references = self::$referencedLists[$name];
$response = [];
foreach ($references as $property){
$class = $property->getDeclaringClass();
$name = $class->getShortName();
$trace = null;
foreach ($property->getAttributes() as $attribute){
$instance = $attribute->newInstance();
if ($instance instanceof Traceable){
$trace = $instance->name();
continue;
}
}
if (!isset($trace)){
continue;
}
$response[$trace] = $property;
}
return $response;
}
/**
* Buffers and returns table name per called class
* @param string $className
* @return string
* @throws Exception
*/
private static function getTableName(string $className = null): string {
$name = $className ?? get_called_class();
if (isset(self::$tableNamesCache[$name])){
return self::$tableNamesCache[$name];
}
$class = new \ReflectionClass($name);
foreach ($class->getAttributes() as $attr){
$instance = $attr->newInstance();
if ($instance instanceof Table){
$tableName = $instance->table();
self::$tableNamesCache[$name] = $tableName;
return $tableName;
}
}
throw new Exception("Table name for $name is not defined");
}
/**
* Buffers and returns primary keys per called class
* @param string $className
* @return array
* @throws Exception
*/
private static function getPrimaryKeys(string $className = null): array {
$name = $className ?? get_called_class();
if (isset(self::$primaryKeysCache[$name])){
return self::$primaryKeysCache[$name];
}
$class = new \ReflectionClass($name);
foreach ($class->getAttributes() as $attr){
$instance = $attr->newInstance();
if ($instance instanceof PrimaryKey){
$keys = $instance->keys();
if (count($keys)){
self::$primaryKeysCache[$name] = $keys;
return $keys;
}
}
}
throw new Exception("Primary keys for $name are not defined");
}
/**
* Returns hash of array of resolved ids
* @param array $ids
* @return string
*/
private static function hashIds(array $ids): string {
foreach ($ids as $k => $id){
if (!is_numeric($id)){
$ids[$k] = (string) $id;
continue;
}
if ((float) $id == (int) $id){
$ids[$k] = (int) $id;
continue;
}
$ids[$k] = (float) $id;
}
if (count(self::getPrimaryKeys()) == 1){
return $ids[0];
} else {
return serialize($ids);
}
}
}