This repository has been archived by the owner on Nov 15, 2019. It is now read-only.
/
Record.php
2718 lines (2403 loc) · 87.5 KB
/
Record.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
/*
* $Id: Record.php 7673 2010-06-08 20:49:54Z jwage $
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
/**
* Doctrine_Record
* All record classes should inherit this super class
*
* @package Doctrine
* @subpackage Record
* @author Konsta Vesterinen <kvesteri@cc.hut.fi>
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 1.0
* @version $Revision: 7673 $
*/
abstract class Doctrine_Record extends Doctrine_Record_Abstract implements Countable, IteratorAggregate, Serializable
{
/**
* STATE CONSTANTS
*/
/**
* DIRTY STATE
* a Doctrine_Record is in dirty state when its properties are changed
*/
const STATE_DIRTY = 1;
/**
* TDIRTY STATE
* a Doctrine_Record is in transient dirty state when it is created
* and some of its fields are modified but it is NOT yet persisted into database
*/
const STATE_TDIRTY = 2;
/**
* CLEAN STATE
* a Doctrine_Record is in clean state when all of its properties are loaded from the database
* and none of its properties are changed
*/
const STATE_CLEAN = 3;
/**
* PROXY STATE
* a Doctrine_Record is in proxy state when its properties are not fully loaded
*/
const STATE_PROXY = 4;
/**
* NEW TCLEAN
* a Doctrine_Record is in transient clean state when it is created and none of its fields are modified
*/
const STATE_TCLEAN = 5;
/**
* LOCKED STATE
* a Doctrine_Record is temporarily locked during deletes and saves
*
* This state is used internally to ensure that circular deletes
* and saves will not cause infinite loops
*/
const STATE_LOCKED = 6;
/**
* TLOCKED STATE
* a Doctrine_Record is temporarily locked (and transient) during deletes and saves
*
* This state is used internally to ensure that circular deletes
* and saves will not cause infinite loops
*/
const STATE_TLOCKED = 7;
/**
* @var Doctrine_Node_<TreeImpl> node object
*/
protected $_node;
/**
* @var integer $_id the primary keys of this object
*/
protected $_id = array();
/**
* each element is one of 3 following types:
* - simple type (int, string) - field has a scalar value
* - null - field has NULL value in DB
* - Doctrine_Null - field value is unknown, it wasn't loaded yet
*
* @var array $_data the record data
*/
protected $_data = array();
/**
* @var array $_values the values array, aggregate values and such are mapped into this array
*/
protected $_values = array();
/**
* @var integer $_state the state of this record
* @see STATE_* constants
*/
protected $_state;
/**
* @var array $_lastModified an array containing field names that were modified in the previous transaction
*/
protected $_lastModified = array();
/**
* @var array $_modified an array containing field names that have been modified
* @todo Better name? $_modifiedFields?
*/
protected $_modified = array();
/**
* @var array $_oldValues an array of the old values from set properties
*/
protected $_oldValues = array();
/**
* @var Doctrine_Validator_ErrorStack error stack object
*/
protected $_errorStack;
/**
* @var array $_references an array containing all the references
*/
protected $_references = array();
/**
* Doctrine_Collection of objects needing to be deleted on save
*
* @var string
*/
protected $_pendingDeletes = array();
/**
* Array of pending un links in format alias => keys to be executed after save
*
* @var array $_pendingUnlinks
*/
protected $_pendingUnlinks = array();
/**
* Array of custom accessors for cache
*
* @var array
*/
protected static $_customAccessors = array();
/**
* Array of custom mutators for cache
*
* @var array
*/
protected static $_customMutators = array();
/**
* Whether or not to serialize references when a Doctrine_Record is serialized
*
* @var boolean
*/
protected $_serializeReferences = false;
/**
* Array containing the save hooks and events that have been invoked
*
* @var array
*/
protected $_invokedSaveHooks = false;
/**
* @var integer $index this index is used for creating object identifiers
*/
private static $_index = 1;
/**
* @var integer $oid object identifier, each Record object has a unique object identifier
*/
private $_oid;
/**
* constructor
* @param Doctrine_Table|null $table a Doctrine_Table object or null,
* if null the table object is retrieved from current connection
*
* @param boolean $isNewEntry whether or not this record is transient
*
* @throws Doctrine_Connection_Exception if object is created using the new operator and there are no
* open connections
* @throws Doctrine_Record_Exception if the cleanData operation fails somehow
*/
public function __construct($table = null, $isNewEntry = false)
{
if (isset($table) && $table instanceof Doctrine_Table) {
$this->_table = $table;
$exists = ( ! $isNewEntry);
} else {
// get the table of this class
$class = get_class($this);
$this->_table = Doctrine_Core::getTable($class);
$exists = false;
}
// Check if the current connection has the records table in its registry
// If not this record is only used for creating table definition and setting up
// relations.
if ( ! $this->_table->getConnection()->hasTable($this->_table->getComponentName())) {
return;
}
$this->_oid = self::$_index;
self::$_index++;
// get the data array
$this->_data = $this->_table->getData();
// get the column count
$count = count($this->_data);
$this->_values = $this->cleanData($this->_data);
$this->prepareIdentifiers($exists);
if ( ! $exists) {
if ($count > count($this->_values)) {
$this->_state = Doctrine_Record::STATE_TDIRTY;
} else {
$this->_state = Doctrine_Record::STATE_TCLEAN;
}
// set the default values for this record
$this->assignDefaultValues();
} else {
$this->_state = Doctrine_Record::STATE_CLEAN;
if ($this->isInProxyState()) {
$this->_state = Doctrine_Record::STATE_PROXY;
}
}
$repository = $this->_table->getRepository();
// Fix for #1682 and #1841.
// Doctrine_Table does not have the repository yet during dummy record creation.
if ($repository) {
$repository->add($this);
$this->construct();
}
}
/**
* Set whether or not to serialize references.
* This is used by caching since we want to serialize references when caching
* but not when just normally serializing a instance
*
* @param boolean $bool
* @return boolean $bool
*/
public function serializeReferences($bool = null)
{
if ( ! is_null($bool)) {
$this->_serializeReferences = $bool;
}
return $this->_serializeReferences;
}
/**
* the current instance counter used to generate unique ids for php objects. Contains the next identifier.
*
* @return integer
*/
public static function _index()
{
return self::$_index;
}
/**
* setUp
* this method is used for setting up relations and attributes
* it should be implemented by child classes
*
* @return void
*/
public function setUp()
{ }
/**
* construct
* Empty template method to provide concrete Record classes with the possibility
* to hook into the constructor procedure
*
* @return void
*/
public function construct()
{ }
/**
* @see $_oid;
*
* @return integer the object identifier
*/
public function getOid()
{
return $this->_oid;
}
public function oid()
{
return $this->_oid;
}
/**
* calls a subclass hook. Idempotent until @see clearInvokedSaveHooks() is called.
*
* <code>
* $this->invokeSaveHooks('pre', 'save');
* </code>
*
* @param string $when 'post' or 'pre'
* @param string $type serialize, unserialize, save, delete, update, insert, validate, dqlSelect, dqlDelete, hydrate
* @param Doctrine_Event $event event raised
* @return Doctrine_Event the event generated using the type, if not specified
*/
public function invokeSaveHooks($when, $type, $event = null)
{
$func = $when . ucfirst($type);
if (is_null($event)) {
$constant = constant('Doctrine_Event::RECORD_' . strtoupper($type));
//echo $func . " - " . 'Doctrine_Event::RECORD_' . strtoupper($type) . "\n";
$event = new Doctrine_Event($this, $constant);
}
if ( ! isset($this->_invokedSaveHooks[$func])) {
$this->$func($event);
$this->getTable()->getRecordListener()->$func($event);
$this->_invokedSaveHooks[$func] = $event;
} else {
$event = $this->_invokedSaveHooks[$func];
}
return $event;
}
/**
* makes all the already used save hooks available again
*/
public function clearInvokedSaveHooks()
{
$this->_invokedSaveHooks = array();
}
/**
* tests validity of the record using the current data.
*
* @param boolean $deep run the validation process on the relations
* @param boolean $hooks invoke save hooks before start
* @return boolean whether or not this record is valid
*/
public function isValid($deep = false, $hooks = true)
{
if ( ! $this->_table->getAttribute(Doctrine_Core::ATTR_VALIDATE)) {
return true;
}
if ($this->_state == self::STATE_LOCKED || $this->_state == self::STATE_TLOCKED) {
return true;
}
if ($hooks) {
$this->invokeSaveHooks('pre', 'save');
$this->invokeSaveHooks('pre', $this->exists() ? 'update' : 'insert');
}
// Clear the stack from any previous errors.
$this->getErrorStack()->clear();
// Run validation process
$event = new Doctrine_Event($this, Doctrine_Event::RECORD_VALIDATE);
$this->preValidate($event);
$this->getTable()->getRecordListener()->preValidate($event);
if ( ! $event->skipOperation) {
$validator = new Doctrine_Validator();
$validator->validateRecord($this);
$this->validate();
if ($this->_state == self::STATE_TDIRTY || $this->_state == self::STATE_TCLEAN) {
$this->validateOnInsert();
} else {
$this->validateOnUpdate();
}
}
$this->getTable()->getRecordListener()->postValidate($event);
$this->postValidate($event);
$valid = $this->getErrorStack()->count() == 0 ? true : false;
if ($valid && $deep) {
$stateBeforeLock = $this->_state;
$this->_state = $this->exists() ? self::STATE_LOCKED : self::STATE_TLOCKED;
foreach ($this->_references as $reference) {
if ($reference instanceof Doctrine_Record) {
if ( ! $valid = $reference->isValid($deep)) {
break;
}
} else if ($reference instanceof Doctrine_Collection) {
foreach ($reference as $record) {
if ( ! $valid = $record->isValid($deep)) {
break;
}
}
}
}
$this->_state = $stateBeforeLock;
}
return $valid;
}
/**
* Empty template method to provide concrete Record classes with the possibility
* to hook into the validation procedure, doing any custom / specialized
* validations that are neccessary.
*/
protected function validate()
{ }
/**
* Empty template method to provide concrete Record classes with the possibility
* to hook into the validation procedure only when the record is going to be
* updated.
*/
protected function validateOnUpdate()
{ }
/**
* Empty template method to provide concrete Record classes with the possibility
* to hook into the validation procedure only when the record is going to be
* inserted into the data store the first time.
*/
protected function validateOnInsert()
{ }
/**
* Empty template method to provide concrete Record classes with the possibility
* to hook into the serializing procedure.
*/
public function preSerialize($event)
{ }
/**
* Empty template method to provide concrete Record classes with the possibility
* to hook into the serializing procedure.
*/
public function postSerialize($event)
{ }
/**
* Empty template method to provide concrete Record classes with the possibility
* to hook into the serializing procedure.
*/
public function preUnserialize($event)
{ }
/**
* Empty template method to provide concrete Record classes with the possibility
* to hook into the serializing procedure.
*/
public function postUnserialize($event)
{ }
/**
* Empty template method to provide concrete Record classes with the possibility
* to hook into the saving procedure.
*/
public function preSave($event)
{ }
/**
* Empty template method to provide concrete Record classes with the possibility
* to hook into the saving procedure.
*/
public function postSave($event)
{ }
/**
* Empty template method to provide concrete Record classes with the possibility
* to hook into the deletion procedure.
*/
public function preDelete($event)
{ }
/**
* Empty template method to provide concrete Record classes with the possibility
* to hook into the deletion procedure.
*/
public function postDelete($event)
{ }
/**
* Empty template method to provide concrete Record classes with the possibility
* to hook into the saving procedure only when the record is going to be
* updated.
*/
public function preUpdate($event)
{ }
/**
* Empty template method to provide concrete Record classes with the possibility
* to hook into the saving procedure only when the record is going to be
* updated.
*/
public function postUpdate($event)
{ }
/**
* Empty template method to provide concrete Record classes with the possibility
* to hook into the saving procedure only when the record is going to be
* inserted into the data store the first time.
*/
public function preInsert($event)
{ }
/**
* Empty template method to provide concrete Record classes with the possibility
* to hook into the saving procedure only when the record is going to be
* inserted into the data store the first time.
*/
public function postInsert($event)
{ }
/**
* Empty template method to provide concrete Record classes with the possibility
* to hook into the validation procedure. Useful for cleaning up data before
* validating it.
*/
public function preValidate($event)
{ }
/**
* Empty template method to provide concrete Record classes with the possibility
* to hook into the validation procedure.
*/
public function postValidate($event)
{ }
/**
* Empty template method to provide Record classes with the ability to alter DQL select
* queries at runtime
*/
public function preDqlSelect($event)
{ }
/**
* Empty template method to provide Record classes with the ability to alter DQL update
* queries at runtime
*/
public function preDqlUpdate($event)
{ }
/**
* Empty template method to provide Record classes with the ability to alter DQL delete
* queries at runtime
*/
public function preDqlDelete($event)
{ }
/**
* Empty template method to provide Record classes with the ability to alter hydration
* before it runs
*/
public function preHydrate($event)
{ }
/**
* Empty template method to provide Record classes with the ability to alter hydration
* after it runs
*/
public function postHydrate($event)
{ }
/**
* Get the record error stack as a human readable string.
* Useful for outputting errors to user via web browser
*
* @return string $message
*/
public function getErrorStackAsString()
{
$errorStack = $this->getErrorStack();
if (count($errorStack)) {
$message = sprintf("Validation failed in class %s\n\n", get_class($this));
$message .= " " . count($errorStack) . " field" . (count($errorStack) > 1 ? 's' : null) . " had validation error" . (count($errorStack) > 1 ? 's' : null) . ":\n\n";
foreach ($errorStack as $field => $errors) {
$message .= " * " . count($errors) . " validator" . (count($errors) > 1 ? 's' : null) . " failed on $field (" . implode(", ", $errors) . ")\n";
}
return $message;
} else {
return false;
}
}
/**
* retrieves the ErrorStack. To be called after a failed validation attempt (@see isValid()).
*
* @return Doctrine_Validator_ErrorStack returns the errorStack associated with this record
*/
public function getErrorStack()
{
if ( ! $this->_errorStack) {
$this->_errorStack = new Doctrine_Validator_ErrorStack(get_class($this));
}
return $this->_errorStack;
}
/**
* assigns the ErrorStack or returns it if called without parameters
*
* @param Doctrine_Validator_ErrorStack errorStack to be assigned for this record
* @return void|Doctrine_Validator_ErrorStack returns the errorStack associated with this record
*/
public function errorStack($stack = null)
{
if ($stack !== null) {
if ( ! ($stack instanceof Doctrine_Validator_ErrorStack)) {
throw new Doctrine_Record_Exception('Argument should be an instance of Doctrine_Validator_ErrorStack.');
}
$this->_errorStack = $stack;
} else {
return $this->getErrorStack();
}
}
/**
* Assign the inheritance column values
*
* @return void
*/
public function assignInheritanceValues()
{
$map = $this->_table->inheritanceMap;
foreach ($map as $k => $v) {
$k = $this->_table->getFieldName($k);
$old = $this->get($k, false);
if (((string) $old !== (string) $v || $old === null) && !in_array($k, $this->_modified)) {
$this->set($k, $v);
}
}
}
/**
* setDefaultValues
* sets the default values for records internal data
*
* @param boolean $overwrite whether or not to overwrite the already set values
* @return boolean
*/
public function assignDefaultValues($overwrite = false)
{
if ( ! $this->_table->hasDefaultValues()) {
return false;
}
foreach ($this->_data as $column => $value) {
$default = $this->_table->getDefaultValueOf($column);
if ($default === null) {
continue;
}
if ($value === self::$_null || $overwrite) {
$this->_data[$column] = $default;
$this->_modified[] = $column;
$this->_state = Doctrine_Record::STATE_TDIRTY;
}
}
}
/**
* cleanData
* leaves the $data array only with values whose key is a field inside this
* record and returns the values that were removed from $data. Also converts
* any values of 'null' to objects of type Doctrine_Null.
*
* @param array $data data array to be cleaned
* @return array values cleaned from data
*/
public function cleanData(&$data)
{
$tmp = $data;
$data = array();
foreach ($this->getTable()->getFieldNames() as $fieldName) {
if (isset($tmp[$fieldName])) {
$data[$fieldName] = $tmp[$fieldName];
} else if (array_key_exists($fieldName, $tmp)) {
$data[$fieldName] = null;
} else if ( !isset($this->_data[$fieldName])) {
$data[$fieldName] = self::$_null;
}
unset($tmp[$fieldName]);
}
return $tmp;
}
/**
* hydrate
* hydrates this object from given array
*
* @param array $data
* @param boolean $overwriteLocalChanges whether to overwrite the unsaved (dirty) data
* @return void
*/
public function hydrate(array $data, $overwriteLocalChanges = true)
{
if ($overwriteLocalChanges) {
$this->_values = array_merge($this->_values, $this->cleanData($data));
$this->_data = array_merge($this->_data, $data);
$this->_modified = array();
$this->_oldValues = array();
} else {
$this->_values = array_merge($this->cleanData($data), $this->_values);
$this->_data = array_merge($data, $this->_data);
}
if (!$this->isModified() && $this->isInProxyState()) {
$this->_state = self::STATE_PROXY;
}
}
/**
* prepareIdentifiers
* prepares identifiers for later use
*
* @param boolean $exists whether or not this record exists in persistent data store
* @return void
*/
private function prepareIdentifiers($exists = true)
{
switch ($this->_table->getIdentifierType()) {
case Doctrine_Core::IDENTIFIER_AUTOINC:
case Doctrine_Core::IDENTIFIER_SEQUENCE:
case Doctrine_Core::IDENTIFIER_NATURAL:
$name = $this->_table->getIdentifier();
if (is_array($name)) {
$name = $name[0];
}
if ($exists) {
if (isset($this->_data[$name]) && $this->_data[$name] !== self::$_null) {
$this->_id[$name] = $this->_data[$name];
}
}
break;
case Doctrine_Core::IDENTIFIER_COMPOSITE:
$names = $this->_table->getIdentifier();
foreach ($names as $name) {
if ($this->_data[$name] === self::$_null) {
$this->_id[$name] = null;
} else {
$this->_id[$name] = $this->_data[$name];
}
}
break;
}
}
/**
* serialize
* this method is automatically called when an instance of Doctrine_Record is serialized
*
* @return string
*/
public function serialize()
{
$event = new Doctrine_Event($this, Doctrine_Event::RECORD_SERIALIZE);
$this->preSerialize($event);
$this->getTable()->getRecordListener()->preSerialize($event);
$vars = get_object_vars($this);
if ( ! $this->serializeReferences()) {
unset($vars['_references']);
}
unset($vars['_table']);
unset($vars['_errorStack']);
unset($vars['_filter']);
unset($vars['_node']);
$data = $this->_data;
if ($this->exists()) {
$data = array_merge($data, $this->_id);
}
foreach ($data as $k => $v) {
if ($v instanceof Doctrine_Record && $this->_table->getTypeOf($k) != 'object') {
unset($vars['_data'][$k]);
} elseif ($v === self::$_null) {
unset($vars['_data'][$k]);
} else {
switch ($this->_table->getTypeOf($k)) {
case 'array':
case 'object':
$vars['_data'][$k] = serialize($vars['_data'][$k]);
break;
case 'gzip':
$vars['_data'][$k] = gzcompress($vars['_data'][$k]);
break;
case 'enum':
$vars['_data'][$k] = $this->_table->enumIndex($k, $vars['_data'][$k]);
break;
}
}
}
$str = serialize($vars);
$this->postSerialize($event);
$this->getTable()->getRecordListener()->postSerialize($event);
return $str;
}
/**
* this method is automatically called everytime an instance is unserialized
*
* @param string $serialized Doctrine_Record as serialized string
* @throws Doctrine_Record_Exception if the cleanData operation fails somehow
* @return void
*/
public function unserialize($serialized)
{
$event = new Doctrine_Event($this, Doctrine_Event::RECORD_UNSERIALIZE);
$manager = Doctrine_Manager::getInstance();
$connection = $manager->getConnectionForComponent(get_class($this));
$this->_table = $connection->getTable(get_class($this));
$this->preUnserialize($event);
$this->getTable()->getRecordListener()->preUnserialize($event);
$array = unserialize($serialized);
foreach($array as $k => $v) {
$this->$k = $v;
}
foreach ($this->_data as $k => $v) {
switch ($this->_table->getTypeOf($k)) {
case 'array':
case 'object':
$this->_data[$k] = unserialize($this->_data[$k]);
break;
case 'gzip':
$this->_data[$k] = gzuncompress($this->_data[$k]);
break;
case 'enum':
$this->_data[$k] = $this->_table->enumValue($k, $this->_data[$k]);
break;
}
}
// Remove existing record from the repository and table entity map.
$this->_table->setData($this->_data);
$existing_record = $this->_table->getRecord();
if ($existing_record->exists()) {
$this->_table->getRepository()->evict($existing_record->getOid());
$this->_table->removeRecord($existing_record);
}
// Add the unserialized record to repository and entity map.
$this->_oid = self::$_index;
self::$_index++;
$this->_table->getRepository()->add($this);
$this->_table->addRecord($this);
$this->cleanData($this->_data);
$this->prepareIdentifiers($this->exists());
$this->postUnserialize($event);
$this->getTable()->getRecordListener()->postUnserialize($event);
}
/**
* assigns the state of this record or returns it if called without parameters
*
* @param integer|string $state if set, this method tries to set the record state to $state
* @see Doctrine_Record::STATE_* constants
*
* @throws Doctrine_Record_State_Exception if trying to set an unknown state
* @return null|integer
*/
public function state($state = null)
{
if ($state == null) {
return $this->_state;
}
$err = false;
if (is_integer($state)) {
if ($state >= 1 && $state <= 7) {
$this->_state = $state;
} else {
$err = true;
}
} else if (is_string($state)) {
$upper = strtoupper($state);
$const = 'Doctrine_Record::STATE_' . $upper;
if (defined($const)) {
$this->_state = constant($const);
} else {
$err = true;
}
}
if ($this->_state === Doctrine_Record::STATE_TCLEAN ||
$this->_state === Doctrine_Record::STATE_CLEAN) {
$this->_resetModified();
}
if ($err) {
throw new Doctrine_Record_State_Exception('Unknown record state ' . $state);
}
}
/**
* refresh
* refresh internal data from the database
*
* @param bool $deep If true, fetch also current relations. Caution: this deletes
* any aggregated values you may have queried beforee
*
* @throws Doctrine_Record_Exception When the refresh operation fails (when the database row
* this record represents does not exist anymore)
* @return boolean
*/
public function refresh($deep = false)
{
$id = $this->identifier();
if ( ! is_array($id)) {
$id = array($id);
}
if (empty($id)) {
return false;
}
$id = array_values($id);
$overwrite = $this->getTable()->getAttribute(Doctrine_Core::ATTR_HYDRATE_OVERWRITE);
$this->getTable()->setAttribute(Doctrine_Core::ATTR_HYDRATE_OVERWRITE, true);
if ($deep) {
$query = $this->getTable()->createQuery();
foreach (array_keys($this->_references) as $name) {
$query->leftJoin(get_class($this) . '.' . $name);
}
$query->where(implode(' = ? AND ', (array)$this->getTable()->getIdentifier()) . ' = ?');
$this->clearRelated();
$record = $query->fetchOne($id);
} else {
// Use HYDRATE_ARRAY to avoid clearing object relations
$record = $this->getTable()->find($id, Doctrine_Core::HYDRATE_ARRAY);
if ($record) {
$this->hydrate($record);
}
}
$this->getTable()->setAttribute(Doctrine_Core::ATTR_HYDRATE_OVERWRITE, $overwrite);
if ($record === false) {
throw new Doctrine_Record_Exception('Failed to refresh. Record does not exist.');