-
Notifications
You must be signed in to change notification settings - Fork 204
/
Copy pathDbObject.php
1416 lines (1244 loc) · 36.9 KB
/
DbObject.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
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Icinga\Module\Director\Data\Db;
use Icinga\Exception\NotFoundError;
use Icinga\Module\Director\Data\InvalidDataException;
use Icinga\Module\Director\Db;
use Icinga\Module\Director\Exception\DuplicateKeyException;
use InvalidArgumentException;
use LogicException;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidInterface;
use RuntimeException;
use Zend_Db_Adapter_Abstract;
use Zend_Db_Exception;
/**
* Base class for ...
*/
abstract class DbObject
{
/** @var DbConnection $connection */
protected $connection;
/** @var string Table name. MUST be set when extending this class */
protected $table;
/** @var Zend_Db_Adapter_Abstract */
protected $db;
/**
* Default columns. MUST be set when extending this class. Each table
* column MUST be defined with a default value. Default value may be null.
*
* @var array
*/
protected $defaultProperties;
/**
* Properties as loaded from db
*/
protected $loadedProperties;
/**
* Whether at least one property has been modified
*/
protected $hasBeenModified = false;
/**
* Whether this object has been loaded from db
*/
protected $loadedFromDb = false;
/**
* Object properties
*/
protected $properties = array();
/**
* Property names that have been modified since object creation
*/
protected $modifiedProperties = array();
/**
* Unique key name, could be primary
*/
protected $keyName;
/**
* Set this to an eventual autoincrementing column. May equal $keyName
*/
protected $autoincKeyName;
/** @var string optional uuid column */
protected $uuidColumn;
/** @var bool forbid updates to autoinc values */
protected $protectAutoinc = true;
protected $binaryProperties = [];
/**
* Filled with object instances when prefetchAll is used
*/
protected static $prefetched = array();
/**
* object_name => id map for prefetched objects
*/
protected static $prefetchedNames = array();
protected static $prefetchStats = array();
/**
* Constructor is not accessible and should not be overridden
*/
protected function __construct()
{
if ($this->table === null
|| $this->keyName === null
|| $this->defaultProperties === null
) {
throw new LogicException("Someone extending this class didn't RTFM");
}
$this->properties = $this->defaultProperties;
$this->beforeInit();
}
public function getTableName()
{
return $this->table;
}
/************************************************************************\
* When extending this class one might want to override any of the *
* following hooks. Try to use them whenever possible, especially *
* instead of overriding other essential methods like store(). *
\************************************************************************/
/**
* One can override this to allow for cross checks and more before storing
* the object. Please note that the method is public and allows to check
* object consistence at any time.
*
* @return boolean Whether this object is valid
*/
public function validate()
{
return true;
}
/**
* This is going to be executed before any initialization method takes *
* (load from DB, populate from Array...) takes place
*
* @return void
*/
protected function beforeInit()
{
}
/**
* Will be executed every time an object has successfully been loaded from
* Database
*
* @return void
*/
protected function onLoadFromDb()
{
}
/**
* Will be executed before an Object is going to be stored. In case you
* want to prevent the store() operation from taking place, please throw
* an Exception.
*
* @return void
*/
protected function beforeStore()
{
}
/**
* Wird ausgeführt, nachdem ein Objekt erfolgreich gespeichert worden ist
*
* @return void
*/
protected function onStore()
{
}
/**
* Wird ausgeführt, nachdem ein Objekt erfolgreich der Datenbank hinzu-
* gefügt worden ist
*
* @return void
*/
protected function onInsert()
{
}
/**
* Wird ausgeführt, nachdem bestehendes Objekt erfolgreich der Datenbank
* geändert worden ist
*
* @return void
*/
protected function onUpdate()
{
}
/**
* Wird ausgeführt, bevor ein Objekt gelöscht wird. Die Operation wird
* aber auf jeden Fall durchgeführt, außer man wirft eine Exception
*
* @return void
*/
protected function beforeDelete()
{
}
/**
* Wird ausgeführt, nachdem bestehendes Objekt erfolgreich aud der
* Datenbank gelöscht worden ist
*
* @return void
*/
protected function onDelete()
{
}
/**
* Set database connection
*
* @param DbConnection $connection Database connection
*
* @return self
*/
public function setConnection(DbConnection $connection)
{
$this->connection = $connection;
$this->db = $connection->getDbAdapter();
return $this;
}
/**
* Getter
*
* @param string $property Property
*
* @return mixed
*/
public function get($property)
{
$func = 'get' . ucfirst($property);
if (substr($func, -2) === '[]') {
$func = substr($func, 0, -2);
}
// TODO: id check avoids collision with getId. Rethink this.
if ($property !== 'id' && method_exists($this, $func)) {
return $this->$func();
}
$this->assertPropertyExists($property);
return $this->properties[$property];
}
public function getProperty($key)
{
$this->assertPropertyExists($key);
return $this->properties[$key];
}
protected function assertPropertyExists($key)
{
if (! array_key_exists($key, $this->properties)) {
throw new InvalidArgumentException(sprintf(
'Trying to get invalid property "%s"',
$key
));
}
return $this;
}
public function hasProperty($key)
{
if (array_key_exists($key, $this->properties)) {
return true;
} elseif ($key === 'id') {
// There is getId, would give false positive
return false;
}
return $this->hasGetterForProperty($key);
}
protected function hasGetterForProperty($key)
{
$func = 'get' . ucfirst($key);
if (\substr($func, -2) === '[]') {
$func = substr($func, 0, -2);
}
return \method_exists($this, $func);
}
protected function hasSetterForProperty($key)
{
$func = 'set' . ucfirst($key);
if (\substr($func, -2) === '[]') {
$func = substr($func, 0, -2);
}
return \method_exists($this, $func);
}
/**
* Generic setter
*
* @param string $key
* @param mixed $value
*
* @return self
*/
public function set($key, $value)
{
$key = (string) $key;
if ($value === '') {
$value = null;
}
if (is_resource($value)) {
$value = stream_get_contents($value);
}
$func = 'validate' . ucfirst($key);
if (method_exists($this, $func) && $this->$func($value) !== true) {
throw new InvalidArgumentException(sprintf(
'Got invalid value "%s" for "%s"',
$value,
$key
));
}
$func = 'munge' . ucfirst($key);
if (method_exists($this, $func)) {
$value = $this->$func($value);
}
$func = 'set' . ucfirst($key);
if (substr($func, -2) === '[]') {
$func = substr($func, 0, -2);
}
if (method_exists($this, $func)) {
return $this->$func($value);
}
if (! $this->hasProperty($key)) {
throw new InvalidArgumentException(sprintf(
'Trying to set invalid key "%s"',
$key
));
}
if ((is_numeric($value) || is_string($value))
&& (string) $value === (string) $this->get($key)
) {
return $this;
}
if ($key === $this->getAutoincKeyName() && $this->hasBeenLoadedFromDb()) {
throw new InvalidArgumentException('Changing autoincremental key is not allowed');
}
return $this->reallySet($key, $value);
}
protected function reallySet($key, $value)
{
if ($value === $this->properties[$key]) {
return $this;
}
$this->hasBeenModified = true;
$this->modifiedProperties[$key] = true;
$this->properties[$key] = $value;
return $this;
}
/**
* Magic getter
*
* @param mixed $key
*
* @return mixed
*/
public function __get($key)
{
return $this->get($key);
}
/**
* Magic setter
*
* @param string $key Key
* @param mixed $val Value
*
* @return void
*/
public function __set($key, $val)
{
$this->set($key, $val);
}
/**
* Magic isset check
*
* @param string $key
* @return boolean
*/
public function __isset($key)
{
return array_key_exists($key, $this->properties);
}
/**
* Magic unsetter
*
* @param string $key
* @return void
*/
public function __unset($key)
{
if (! array_key_exists($key, $this->properties)) {
throw new InvalidArgumentException('Trying to unset invalid key');
}
$this->properties[$key] = $this->defaultProperties[$key];
}
/**
* Runs set() for every key/value pair of the given Array
*
* @param array $props Array of properties
* @return self
*/
public function setProperties($props)
{
if (! is_array($props)) {
throw new InvalidArgumentException(sprintf(
'Array required, got %s',
gettype($props)
));
}
foreach ($props as $key => $value) {
$this->set($key, $value);
}
return $this;
}
/**
* Return an array with all object properties
*
* @return array
*/
public function getProperties()
{
//return $this->properties;
$res = array();
foreach ($this->listProperties() as $key) {
$res[$key] = $this->get($key);
}
return $res;
}
protected function getPropertiesForDb()
{
return $this->properties;
}
public function listProperties()
{
return array_keys($this->properties);
}
/**
* Return all properties that changed since object creation
*
* @return array
*/
public function getModifiedProperties()
{
$props = array();
foreach (array_keys($this->modifiedProperties) as $key) {
if ($key === $this->autoincKeyName) {
if ($this->protectAutoinc) {
continue;
} elseif ($this->properties[$key] === null) {
continue;
}
}
$props[$key] = $this->properties[$key];
}
return $props;
}
/**
* List all properties that changed since object creation
*
* @return array
*/
public function listModifiedProperties()
{
return array_keys($this->modifiedProperties);
}
/**
* Whether this object has been modified
*
* @return bool
*/
public function hasBeenModified()
{
return $this->hasBeenModified;
}
/**
* Whether the given property has been modified
*
* @param string $key Property name
* @return boolean
*/
protected function hasModifiedProperty($key)
{
return array_key_exists($key, $this->modifiedProperties);
}
/**
* Unique key name
*
* @return string
*/
public function getKeyName()
{
return $this->keyName;
}
/**
* Autoinc key name
*
* @return string
*/
public function getAutoincKeyName()
{
return $this->autoincKeyName;
}
/**
* @return ?string
*/
public function getUuidColumn()
{
return $this->uuidColumn;
}
/**
* @return bool
*/
public function hasUuidColumn()
{
return $this->uuidColumn !== null;
}
/**
* @return \Ramsey\Uuid\UuidInterface
*/
public function getUniqueId()
{
if ($this->hasUuidColumn()) {
$binaryValue = $this->properties[$this->uuidColumn];
if (is_resource($binaryValue)) {
throw new RuntimeException('Properties contain binary UUID, probably a programming error');
}
if ($binaryValue === null) {
$uuid = Uuid::uuid4();
$this->reallySet($this->uuidColumn, $uuid->getBytes());
return $uuid;
}
return Uuid::fromBytes($binaryValue);
}
throw new InvalidArgumentException(sprintf('%s has no UUID column', $this->getTableName()));
}
public function getKeyParams()
{
$params = array();
$key = $this->getKeyName();
if (is_array($key)) {
foreach ($key as $k) {
$params[$k] = $this->get($k);
}
} else {
$params[$key] = $this->get($this->keyName);
}
return $params;
}
/**
* Return the unique identifier
*
* // TODO: may conflict with ->id
*
* @throws InvalidArgumentException When key can not be calculated
*
* @return string|array
*/
public function getId()
{
if (is_array($this->keyName)) {
$id = array();
foreach ($this->keyName as $key) {
if (isset($this->properties[$key])) {
$id[$key] = $this->properties[$key];
}
}
if (empty($id)) {
throw new InvalidArgumentException('Could not evaluate id for multi-column object!');
}
return $id;
} else {
if (isset($this->properties[$this->keyName])) {
return $this->properties[$this->keyName];
}
}
return null;
}
/**
* Get the autoinc value if set
*
* @return int
*/
public function getAutoincId()
{
if (isset($this->properties[$this->autoincKeyName])) {
return (int) $this->properties[$this->autoincKeyName];
}
return null;
}
protected function forgetAutoincId()
{
if (isset($this->properties[$this->autoincKeyName])) {
$this->properties[$this->autoincKeyName] = null;
}
return $this;
}
/**
* Liefert das benutzte Datenbank-Handle
*
* @return Zend_Db_Adapter_Abstract
*/
public function getDb()
{
return $this->db;
}
public function hasConnection()
{
return $this->connection !== null;
}
public function getConnection()
{
return $this->connection;
}
/**
* Lädt einen Datensatz aus der Datenbank und setzt die entsprechenden
* Eigenschaften dieses Objekts
*
* @throws NotFoundError
* @return self
*/
protected function loadFromDb()
{
$select = $this->db->select()->from($this->table)->where($this->createWhere());
$properties = $this->db->fetchRow($select);
if (empty($properties)) {
if (is_array($this->getKeyName())) {
throw new NotFoundError(
'Failed to load %s for %s',
$this->table,
$this->createWhere()
);
} else {
throw new NotFoundError(
'Failed to load %s "%s"',
$this->table,
$this->getLogId()
);
}
}
return $this->setDbProperties($properties);
}
/**
* @param object|array $row
* @param Db $db
* @return self
*/
public static function fromDbRow($row, Db $db)
{
$self = (new static())->setConnection($db);
if (is_object($row)) {
return $self->setDbProperties((array) $row);
}
if (is_array($row)) {
return $self->setDbProperties($row);
}
throw new InvalidDataException('array or object', $row);
}
protected function setDbProperties($properties)
{
foreach ($properties as $key => $val) {
if (! array_key_exists($key, $this->properties)) {
throw new LogicException(sprintf(
'Trying to set invalid %s key "%s". DB schema change?',
$this->table,
$key
));
}
if ($val === null) {
$this->properties[$key] = null;
} elseif (is_resource($val)) {
$this->properties[$key] = stream_get_contents($val);
} else {
$this->properties[$key] = (string) $val;
}
}
$this->setBeingLoadedFromDb();
$this->onLoadFromDb();
return $this;
}
public function setBeingLoadedFromDb()
{
$this->loadedFromDb = true;
$this->loadedProperties = $this->properties;
$this->hasBeenModified = false;
$this->modifiedProperties = [];
}
public function setLoadedProperty($key, $value)
{
if ($this->hasBeenLoadedFromDb()) {
$this->set($key, $value);
$this->loadedProperties[$key] = $this->get($key);
} else {
throw new RuntimeException('Cannot set loaded property for new object');
}
}
public function getOriginalProperties()
{
return $this->loadedProperties;
}
public function getOriginalProperty($key)
{
$this->assertPropertyExists($key);
if ($this->hasBeenLoadedFromDb()) {
return $this->loadedProperties[$key];
}
return null;
}
public function resetProperty($key)
{
$this->set($key, $this->getOriginalProperty($key));
if ($this->listModifiedProperties() === [$key]) {
$this->hasBeenModified = false;
}
return $this;
}
public function hasBeenLoadedFromDb()
{
return $this->loadedFromDb;
}
/**
* Ändert den entsprechenden Datensatz in der Datenbank
*
* @return int Anzahl der geänderten Zeilen
* @throws \Zend_Db_Adapter_Exception
*/
protected function updateDb()
{
$properties = $this->getModifiedProperties();
if (empty($properties)) {
// Fake true, we might have manually set this to "modified"
return true;
}
$this->quoteBinaryProperties($properties);
// TODO: Remember changed data for audit and log
return $this->db->update(
$this->table,
$properties,
$this->createWhere()
);
}
/**
* Fügt der Datenbank-Tabelle einen entsprechenden Datensatz hinzu
*
* @return int Anzahl der betroffenen Zeilen
* @throws \Zend_Db_Adapter_Exception
*/
protected function insertIntoDb()
{
$properties = $this->getPropertiesForDb();
if ($this->autoincKeyName !== null) {
if ($this->protectAutoinc || $properties[$this->autoincKeyName] === null) {
unset($properties[$this->autoincKeyName]);
}
}
if ($column = $this->getUuidColumn()) {
$properties[$column] = $this->getUniqueId()->getBytes();
}
$this->quoteBinaryProperties($properties);
return $this->db->insert($this->table, $properties);
}
protected function quoteBinaryProperties(&$properties)
{
foreach ($properties as $key => $value) {
if ($this->isBinaryColumn($key)) {
$properties[$key] = $this->getConnection()->quoteBinary($value);
}
}
}
protected function isBinaryColumn($column)
{
return in_array($column, $this->binaryProperties) || $this->getUuidColumn() === $column;
}
/**
* Store object to database
*
* @param DbConnection $db
* @return bool Whether storing succeeded. Always true, throws otherwise
* @throws DuplicateKeyException
*/
public function store(DbConnection $db = null)
{
if ($db !== null) {
$this->setConnection($db);
}
if ($this->validate() !== true) {
throw new InvalidArgumentException(sprintf(
'%s[%s] validation failed',
$this->table,
$this->getLogId()
));
}
if ($this->hasBeenLoadedFromDb() && ! $this->hasBeenModified()) {
return true;
}
$this->beforeStore();
$table = $this->table;
$id = $this->getId();
try {
if ($this->hasBeenLoadedFromDb()) {
if ($this->updateDb() !== false) {
$this->onUpdate();
} else {
throw new RuntimeException(sprintf(
'FAILED storing %s "%s"',
$table,
$this->getLogId()
));
}
} else {
if ($id && $this->existsInDb()) {
$logId = '"' . $this->getLogId() . '"';
if ($autoId = $this->getAutoincId()) {
$logId .= sprintf(', %s=%s', $this->autoincKeyName, $autoId);
}
throw new DuplicateKeyException(
'Trying to recreate %s (%s)',
$table,
$logId
);
}
if ($this->insertIntoDb()) {
if ($this->autoincKeyName && $this->getProperty($this->autoincKeyName) === null) {
if ($this->connection->isPgsql()) {
$this->properties[$this->autoincKeyName] = $this->db->lastInsertId(
$table,
$this->autoincKeyName
);
} else {
$this->properties[$this->autoincKeyName] = $this->db->lastInsertId();
}
}
// $this->log(sprintf('New %s "%s" has been stored', $table, $id));
$this->onInsert();
} else {
throw new RuntimeException(sprintf(
'FAILED to store new %s "%s"',
$table,
$this->getLogId()
));
}
}
} catch (Zend_Db_Exception $e) {
throw new RuntimeException(sprintf(
'Storing %s[%s] failed: %s {%s}',
$this->table,
$this->getLogId(),
$e->getMessage(),
var_export($this->getProperties(), 1) // TODO: Remove properties
));
}
// Hint: order is differs from setBeingLoadedFromDb() as of the onStore hook
$this->modifiedProperties = [];
$this->hasBeenModified = false;
$this->loadedProperties = $this->properties;
$this->onStore();
$this->loadedFromDb = true;
return true;
}
/**
* Delete item from DB
*
* @return int Affected rows
*/
protected function deleteFromDb()
{
return $this->db->delete(
$this->table,
$this->createWhere()
);
}
/**
* @param string $key
* @return self
* @throws InvalidArgumentException
*/
protected function setKey($key)
{
$keyname = $this->getKeyName();
if (is_array($keyname)) {
if (! is_array($key)) {
throw new InvalidArgumentException(sprintf(
'%s has a multicolumn key, array required',
$this->table
));
}
foreach ($keyname as $k) {
if (! array_key_exists($k, $key)) {
// We allow for null in multicolumn keys:
$key[$k] = null;
}
$this->set($k, $key[$k]);
}
} else {
$this->set($keyname, $key);
}
return $this;
}
protected function existsInDb()
{
$result = $this->db->fetchRow(
$this->db->select()->from($this->table)->where($this->createWhere())
);
return $result !== false;
}
public function createWhere()
{
if ($id = $this->getAutoincId()) {
if ($originalId = $this->getOriginalProperty($this->autoincKeyName)) {
return $this->db->quoteInto(
sprintf('%s = ?', $this->autoincKeyName),
$originalId
);