Subversion-Projekte lars-tiefland.php_share

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
1 lars 1
<?php
2
/*
3
 *  $Id: Record.php 7673 2010-06-08 20:49:54Z jwage $
4
 *
5
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
12
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
13
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
14
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
15
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
16
 *
17
 * This software consists of voluntary contributions made by many individuals
18
 * and is licensed under the LGPL. For more information, see
19
 * <http://www.doctrine-project.org>.
20
 */
21
 
22
/**
23
 * Doctrine_Record
24
 * All record classes should inherit this super class
25
 *
26
 * @package     Doctrine
27
 * @subpackage  Record
28
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
29
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
30
 * @link        www.doctrine-project.org
31
 * @since       1.0
32
 * @version     $Revision: 7673 $
33
 */
34
abstract class Doctrine_Record extends Doctrine_Record_Abstract implements Countable, IteratorAggregate, Serializable
35
{
36
    /**
37
     * STATE CONSTANTS
38
     */
39
 
40
    /**
41
     * DIRTY STATE
42
     * a Doctrine_Record is in dirty state when its properties are changed
43
     */
44
    const STATE_DIRTY       = 1;
45
 
46
    /**
47
     * TDIRTY STATE
48
     * a Doctrine_Record is in transient dirty state when it is created
49
     * and some of its fields are modified but it is NOT yet persisted into database
50
     */
51
    const STATE_TDIRTY      = 2;
52
 
53
    /**
54
     * CLEAN STATE
55
     * a Doctrine_Record is in clean state when all of its properties are loaded from the database
56
     * and none of its properties are changed
57
     */
58
    const STATE_CLEAN       = 3;
59
 
60
    /**
61
     * PROXY STATE
62
     * a Doctrine_Record is in proxy state when its properties are not fully loaded
63
     */
64
    const STATE_PROXY       = 4;
65
 
66
    /**
67
     * NEW TCLEAN
68
     * a Doctrine_Record is in transient clean state when it is created and none of its fields are modified
69
     */
70
    const STATE_TCLEAN      = 5;
71
 
72
    /**
73
     * LOCKED STATE
74
     * a Doctrine_Record is temporarily locked during deletes and saves
75
     *
76
     * This state is used internally to ensure that circular deletes
77
     * and saves will not cause infinite loops
78
     */
79
    const STATE_LOCKED     = 6;
80
 
81
 	/**
82
 	 * TLOCKED STATE
83
 	 * a Doctrine_Record is temporarily locked (and transient) during deletes and saves
84
 	 *
85
 	 * This state is used internally to ensure that circular deletes
86
 	 * and saves will not cause infinite loops
87
 	 */
88
 	const STATE_TLOCKED     = 7;
89
 
90
 
91
    /**
92
     * @var Doctrine_Node_<TreeImpl>        node object
93
     */
94
    protected $_node;
95
 
96
    /**
97
     * @var integer $_id                    the primary keys of this object
98
     */
99
    protected $_id           = array();
100
 
101
    /**
102
     * each element is one of 3 following types:
103
     * - simple type (int, string) - field has a scalar value
104
     * - null - field has NULL value in DB
105
     * - Doctrine_Null - field value is unknown, it wasn't loaded yet
106
     *
107
     * @var array $_data                    the record data
108
     */
109
    protected $_data         = array();
110
 
111
    /**
112
     * @var array $_values                  the values array, aggregate values and such are mapped into this array
113
     */
114
    protected $_values       = array();
115
 
116
    /**
117
     * @var integer $_state                 the state of this record
118
     * @see STATE_* constants
119
     */
120
    protected $_state;
121
 
122
    /**
123
     * @var array $_lastModified             an array containing field names that were modified in the previous transaction
124
     */
125
    protected $_lastModified = array();
126
 
127
    /**
128
     * @var array $_modified                an array containing field names that have been modified
129
     * @todo Better name? $_modifiedFields?
130
     */
131
    protected $_modified     = array();
132
 
133
    /**
134
     * @var array $_oldValues               an array of the old values from set properties
135
     */
136
    protected $_oldValues   = array();
137
 
138
    /**
139
     * @var Doctrine_Validator_ErrorStack   error stack object
140
     */
141
    protected $_errorStack;
142
 
143
    /**
144
     * @var array $_references              an array containing all the references
145
     */
146
    protected $_references     = array();
147
 
148
    /**
149
     * Doctrine_Collection of objects needing to be deleted on save
150
     *
151
     * @var string
152
     */
153
    protected $_pendingDeletes = array();
154
 
155
    /**
156
     * Array of pending un links in format alias => keys to be executed after save
157
     *
158
     * @var array $_pendingUnlinks
159
     */
160
    protected $_pendingUnlinks = array();
161
 
162
    /**
163
     * Array of custom accessors for cache
164
     *
165
     * @var array
166
     */
167
    protected static $_customAccessors = array();
168
 
169
    /**
170
     * Array of custom mutators for cache
171
     *
172
     * @var array
173
     */
174
    protected static $_customMutators = array();
175
 
176
    /**
177
     * Whether or not to serialize references when a Doctrine_Record is serialized
178
     *
179
     * @var boolean
180
     */
181
    protected $_serializeReferences = false;
182
 
183
    /**
184
     * Array containing the save hooks and events that have been invoked
185
     *
186
     * @var array
187
     */
188
    protected $_invokedSaveHooks = false;
189
 
190
    /**
191
     * @var integer $index                  this index is used for creating object identifiers
192
     */
193
    private static $_index = 1;
194
 
195
    /**
196
     * @var integer $oid                    object identifier, each Record object has a unique object identifier
197
     */
198
    private $_oid;
199
 
200
    /**
201
     * constructor
202
     * @param Doctrine_Table|null $table       a Doctrine_Table object or null,
203
     *                                         if null the table object is retrieved from current connection
204
     *
205
     * @param boolean $isNewEntry              whether or not this record is transient
206
     *
207
     * @throws Doctrine_Connection_Exception   if object is created using the new operator and there are no
208
     *                                         open connections
209
     * @throws Doctrine_Record_Exception       if the cleanData operation fails somehow
210
     */
211
    public function __construct($table = null, $isNewEntry = false)
212
    {
213
        if (isset($table) && $table instanceof Doctrine_Table) {
214
            $this->_table = $table;
215
            $exists = ( ! $isNewEntry);
216
        } else {
217
            // get the table of this class
218
            $class = get_class($this);
219
            $this->_table = Doctrine_Core::getTable($class);
220
            $exists = false;
221
        }
222
 
223
        // Check if the current connection has the records table in its registry
224
        // If not this record is only used for creating table definition and setting up
225
        // relations.
226
        if ( ! $this->_table->getConnection()->hasTable($this->_table->getComponentName())) {
227
            return;
228
        }
229
 
230
        $this->_oid = self::$_index;
231
 
232
        self::$_index++;
233
 
234
        // get the data array
235
        $this->_data = $this->_table->getData();
236
 
237
        // get the column count
238
        $count = count($this->_data);
239
 
240
        $this->_values = $this->cleanData($this->_data);
241
 
242
        $this->prepareIdentifiers($exists);
243
 
244
        if ( ! $exists) {
245
            if ($count > count($this->_values)) {
246
                $this->_state = Doctrine_Record::STATE_TDIRTY;
247
            } else {
248
                $this->_state = Doctrine_Record::STATE_TCLEAN;
249
            }
250
 
251
            // set the default values for this record
252
            $this->assignDefaultValues();
253
        } else {
254
            $this->_state = Doctrine_Record::STATE_CLEAN;
255
 
256
            if ($this->isInProxyState()) {
257
                $this->_state  = Doctrine_Record::STATE_PROXY;
258
            }
259
        }
260
 
261
        $repository = $this->_table->getRepository();
262
 
263
        // Fix for #1682 and #1841.
264
        // Doctrine_Table does not have the repository yet during dummy record creation.
265
        if ($repository) {
266
            $repository->add($this);
267
            $this->construct();
268
        }
269
    }
270
 
271
    /**
272
     * Set whether or not to serialize references.
273
     * This is used by caching since we want to serialize references when caching
274
     * but not when just normally serializing a instance
275
     *
276
     * @param boolean $bool
277
     * @return boolean $bool
278
     */
279
    public function serializeReferences($bool = null)
280
    {
281
        if ( ! is_null($bool)) {
282
            $this->_serializeReferences = $bool;
283
        }
284
        return $this->_serializeReferences;
285
    }
286
 
287
    /**
288
     * the current instance counter used to generate unique ids for php objects. Contains the next identifier.
289
     *
290
     * @return integer
291
     */
292
    public static function _index()
293
    {
294
        return self::$_index;
295
    }
296
 
297
    /**
298
     * setUp
299
     * this method is used for setting up relations and attributes
300
     * it should be implemented by child classes
301
     *
302
     * @return void
303
     */
304
    public function setUp()
305
    { }
306
    /**
307
     * construct
308
     * Empty template method to provide concrete Record classes with the possibility
309
     * to hook into the constructor procedure
310
     *
311
     * @return void
312
     */
313
    public function construct()
314
    { }
315
 
316
    /**
317
     * @see $_oid;
318
     *
319
     * @return integer  the object identifier
320
     */
321
    public function getOid()
322
    {
323
        return $this->_oid;
324
    }
325
 
326
    public function oid()
327
    {
328
        return $this->_oid;
329
    }
330
 
331
    /**
332
     * calls a subclass hook. Idempotent until @see clearInvokedSaveHooks() is called.
333
     *
334
     * <code>
335
     * $this->invokeSaveHooks('pre', 'save');
336
     * </code>
337
     *
338
     * @param string $when           'post' or 'pre'
339
     * @param string $type           serialize, unserialize, save, delete, update, insert, validate, dqlSelect, dqlDelete, hydrate
340
     * @param Doctrine_Event $event  event raised
341
     * @return Doctrine_Event        the event generated using the type, if not specified
342
     */
343
    public function invokeSaveHooks($when, $type, $event = null)
344
    {
345
        $func = $when . ucfirst($type);
346
 
347
        if (is_null($event)) {
348
            $constant = constant('Doctrine_Event::RECORD_' . strtoupper($type));
349
            //echo $func . " - " . 'Doctrine_Event::RECORD_' . strtoupper($type) . "\n";
350
            $event = new Doctrine_Event($this, $constant);
351
        }
352
 
353
        if ( ! isset($this->_invokedSaveHooks[$func])) {
354
            $this->$func($event);
355
            $this->getTable()->getRecordListener()->$func($event);
356
 
357
            $this->_invokedSaveHooks[$func] = $event;
358
        } else {
359
            $event = $this->_invokedSaveHooks[$func];
360
        }
361
 
362
        return $event;
363
    }
364
 
365
    /**
366
     * makes all the already used save hooks available again
367
     */
368
    public function clearInvokedSaveHooks()
369
    {
370
        $this->_invokedSaveHooks = array();
371
    }
372
 
373
    /**
374
     * tests validity of the record using the current data.
375
     *
376
     * @param boolean $deep   run the validation process on the relations
377
     * @param boolean $hooks  invoke save hooks before start
378
     * @return boolean        whether or not this record is valid
379
     */
380
    public function isValid($deep = false, $hooks = true)
381
    {
382
        if ( ! $this->_table->getAttribute(Doctrine_Core::ATTR_VALIDATE)) {
383
            return true;
384
        }
385
 
386
        if ($this->_state == self::STATE_LOCKED || $this->_state == self::STATE_TLOCKED) {
387
            return true;
388
        }
389
 
390
        if ($hooks) {
391
            $this->invokeSaveHooks('pre', 'save');
392
            $this->invokeSaveHooks('pre', $this->exists() ? 'update' : 'insert');
393
        }
394
 
395
        // Clear the stack from any previous errors.
396
        $this->getErrorStack()->clear();
397
 
398
        // Run validation process
399
        $event = new Doctrine_Event($this, Doctrine_Event::RECORD_VALIDATE);
400
        $this->preValidate($event);
401
        $this->getTable()->getRecordListener()->preValidate($event);
402
 
403
        if ( ! $event->skipOperation) {
404
 
405
            $validator = new Doctrine_Validator();
406
            $validator->validateRecord($this);
407
            $this->validate();
408
            if ($this->_state == self::STATE_TDIRTY || $this->_state == self::STATE_TCLEAN) {
409
                $this->validateOnInsert();
410
            } else {
411
                $this->validateOnUpdate();
412
            }
413
        }
414
 
415
        $this->getTable()->getRecordListener()->postValidate($event);
416
        $this->postValidate($event);
417
 
418
        $valid = $this->getErrorStack()->count() == 0 ? true : false;
419
        if ($valid && $deep) {
420
            $stateBeforeLock = $this->_state;
421
            $this->_state = $this->exists() ? self::STATE_LOCKED : self::STATE_TLOCKED;
422
 
423
            foreach ($this->_references as $reference) {
424
                if ($reference instanceof Doctrine_Record) {
425
                    if ( ! $valid = $reference->isValid($deep)) {
426
                        break;
427
                    }
428
                } else if ($reference instanceof Doctrine_Collection) {
429
                    foreach ($reference as $record) {
430
                        if ( ! $valid = $record->isValid($deep)) {
431
                            break;
432
                        }
433
                    }
434
                }
435
            }
436
            $this->_state = $stateBeforeLock;
437
        }
438
 
439
        return $valid;
440
    }
441
 
442
    /**
443
     * Empty template method to provide concrete Record classes with the possibility
444
     * to hook into the validation procedure, doing any custom / specialized
445
     * validations that are neccessary.
446
     */
447
    protected function validate()
448
    { }
449
 
450
    /**
451
     * Empty template method to provide concrete Record classes with the possibility
452
     * to hook into the validation procedure only when the record is going to be
453
     * updated.
454
     */
455
    protected function validateOnUpdate()
456
    { }
457
 
458
    /**
459
     * Empty template method to provide concrete Record classes with the possibility
460
     * to hook into the validation procedure only when the record is going to be
461
     * inserted into the data store the first time.
462
     */
463
    protected function validateOnInsert()
464
    { }
465
 
466
    /**
467
     * Empty template method to provide concrete Record classes with the possibility
468
     * to hook into the serializing procedure.
469
     */
470
    public function preSerialize($event)
471
    { }
472
 
473
    /**
474
     * Empty template method to provide concrete Record classes with the possibility
475
     * to hook into the serializing procedure.
476
     */
477
    public function postSerialize($event)
478
    { }
479
 
480
    /**
481
     * Empty template method to provide concrete Record classes with the possibility
482
     * to hook into the serializing procedure.
483
     */
484
    public function preUnserialize($event)
485
    { }
486
 
487
    /**
488
     * Empty template method to provide concrete Record classes with the possibility
489
     * to hook into the serializing procedure.
490
     */
491
    public function postUnserialize($event)
492
    { }
493
 
494
    /**
495
     * Empty template method to provide concrete Record classes with the possibility
496
     * to hook into the saving procedure.
497
     */
498
    public function preSave($event)
499
    { }
500
 
501
    /**
502
     * Empty template method to provide concrete Record classes with the possibility
503
     * to hook into the saving procedure.
504
     */
505
    public function postSave($event)
506
    { }
507
 
508
    /**
509
     * Empty template method to provide concrete Record classes with the possibility
510
     * to hook into the deletion procedure.
511
     */
512
    public function preDelete($event)
513
    { }
514
 
515
    /**
516
     * Empty template method to provide concrete Record classes with the possibility
517
     * to hook into the deletion procedure.
518
     */
519
    public function postDelete($event)
520
    { }
521
 
522
    /**
523
     * Empty template method to provide concrete Record classes with the possibility
524
     * to hook into the saving procedure only when the record is going to be
525
     * updated.
526
     */
527
    public function preUpdate($event)
528
    { }
529
 
530
    /**
531
     * Empty template method to provide concrete Record classes with the possibility
532
     * to hook into the saving procedure only when the record is going to be
533
     * updated.
534
     */
535
    public function postUpdate($event)
536
    { }
537
 
538
    /**
539
     * Empty template method to provide concrete Record classes with the possibility
540
     * to hook into the saving procedure only when the record is going to be
541
     * inserted into the data store the first time.
542
     */
543
    public function preInsert($event)
544
    { }
545
 
546
    /**
547
     * Empty template method to provide concrete Record classes with the possibility
548
     * to hook into the saving procedure only when the record is going to be
549
     * inserted into the data store the first time.
550
     */
551
    public function postInsert($event)
552
    { }
553
 
554
    /**
555
     * Empty template method to provide concrete Record classes with the possibility
556
     * to hook into the validation procedure. Useful for cleaning up data before
557
     * validating it.
558
     */
559
    public function preValidate($event)
560
    { }
561
    /**
562
     * Empty template method to provide concrete Record classes with the possibility
563
     * to hook into the validation procedure.
564
     */
565
    public function postValidate($event)
566
    { }
567
 
568
    /**
569
     * Empty template method to provide Record classes with the ability to alter DQL select
570
     * queries at runtime
571
     */
572
    public function preDqlSelect($event)
573
    { }
574
 
575
    /**
576
     * Empty template method to provide Record classes with the ability to alter DQL update
577
     * queries at runtime
578
     */
579
    public function preDqlUpdate($event)
580
    { }
581
 
582
    /**
583
     * Empty template method to provide Record classes with the ability to alter DQL delete
584
     * queries at runtime
585
     */
586
    public function preDqlDelete($event)
587
    { }
588
 
589
    /**
590
     * Empty template method to provide Record classes with the ability to alter hydration
591
     * before it runs
592
     */
593
    public function preHydrate($event)
594
    { }
595
 
596
    /**
597
     * Empty template method to provide Record classes with the ability to alter hydration
598
     * after it runs
599
     */
600
    public function postHydrate($event)
601
    { }
602
 
603
    /**
604
     * Get the record error stack as a human readable string.
605
     * Useful for outputting errors to user via web browser
606
     *
607
     * @return string $message
608
     */
609
    public function getErrorStackAsString()
610
    {
611
        $errorStack = $this->getErrorStack();
612
 
613
        if (count($errorStack)) {
614
            $message = sprintf("Validation failed in class %s\n\n", get_class($this));
615
 
616
            $message .= "  " . count($errorStack) . " field" . (count($errorStack) > 1 ?  's' : null) . " had validation error" . (count($errorStack) > 1 ?  's' : null) . ":\n\n";
617
            foreach ($errorStack as $field => $errors) {
618
                $message .= "    * " . count($errors) . " validator" . (count($errors) > 1 ?  's' : null) . " failed on $field (" . implode(", ", $errors) . ")\n";
619
            }
620
            return $message;
621
        } else {
622
            return false;
623
        }
624
    }
625
 
626
    /**
627
     * retrieves the ErrorStack. To be called after a failed validation attempt (@see isValid()).
628
     *
629
     * @return Doctrine_Validator_ErrorStack    returns the errorStack associated with this record
630
     */
631
    public function getErrorStack()
632
    {
633
        if ( ! $this->_errorStack) {
634
            $this->_errorStack = new Doctrine_Validator_ErrorStack(get_class($this));
635
        }
636
 
637
        return $this->_errorStack;
638
    }
639
 
640
    /**
641
     * assigns the ErrorStack or returns it if called without parameters
642
     *
643
     * @param Doctrine_Validator_ErrorStack          errorStack to be assigned for this record
644
     * @return void|Doctrine_Validator_ErrorStack    returns the errorStack associated with this record
645
     */
646
    public function errorStack($stack = null)
647
    {
648
        if ($stack !== null) {
649
            if ( ! ($stack instanceof Doctrine_Validator_ErrorStack)) {
650
               throw new Doctrine_Record_Exception('Argument should be an instance of Doctrine_Validator_ErrorStack.');
651
            }
652
            $this->_errorStack = $stack;
653
        } else {
654
            return $this->getErrorStack();
655
        }
656
    }
657
 
658
    /**
659
     * Assign the inheritance column values
660
     *
661
     * @return void
662
     */
663
    public function assignInheritanceValues()
664
    {
665
        $map = $this->_table->inheritanceMap;
666
        foreach ($map as $k => $v) {
667
            $k = $this->_table->getFieldName($k);
668
            $old = $this->get($k, false);
669
 
670
            if (((string) $old !== (string) $v || $old === null) && !in_array($k, $this->_modified)) {
671
                $this->set($k, $v);
672
            }
673
        }
674
    }
675
 
676
    /**
677
     * setDefaultValues
678
     * sets the default values for records internal data
679
     *
680
     * @param boolean $overwrite                whether or not to overwrite the already set values
681
     * @return boolean
682
     */
683
    public function assignDefaultValues($overwrite = false)
684
    {
685
        if ( ! $this->_table->hasDefaultValues()) {
686
            return false;
687
        }
688
        foreach ($this->_data as $column => $value) {
689
            $default = $this->_table->getDefaultValueOf($column);
690
 
691
            if ($default === null) {
692
                continue;
693
            }
694
 
695
            if ($value === self::$_null || $overwrite) {
696
                $this->_data[$column] = $default;
697
                $this->_modified[]    = $column;
698
                $this->_state = Doctrine_Record::STATE_TDIRTY;
699
            }
700
        }
701
    }
702
 
703
    /**
704
     * cleanData
705
     * leaves the $data array only with values whose key is a field inside this
706
     * record and returns the values that were removed from $data.  Also converts
707
     * any values of 'null' to objects of type Doctrine_Null.
708
     *
709
     * @param array $data   data array to be cleaned
710
     * @return array        values cleaned from data
711
     */
712
    public function cleanData(&$data)
713
    {
714
        $tmp = $data;
715
        $data = array();
716
 
717
        foreach ($this->getTable()->getFieldNames() as $fieldName) {
718
            if (isset($tmp[$fieldName])) {
719
                $data[$fieldName] = $tmp[$fieldName];
720
            } else if (array_key_exists($fieldName, $tmp)) {
721
                $data[$fieldName] = null;
722
            } else if ( !isset($this->_data[$fieldName])) {
723
                $data[$fieldName] = self::$_null;
724
            }
725
            unset($tmp[$fieldName]);
726
        }
727
 
728
        return $tmp;
729
    }
730
 
731
    /**
732
     * hydrate
733
     * hydrates this object from given array
734
     *
735
     * @param array $data
736
     * @param boolean $overwriteLocalChanges  whether to overwrite the unsaved (dirty) data
737
     * @return void
738
     */
739
    public function hydrate(array $data, $overwriteLocalChanges = true)
740
    {
741
        if ($overwriteLocalChanges) {
742
            $this->_values = array_merge($this->_values, $this->cleanData($data));
743
            $this->_data = array_merge($this->_data, $data);
744
            $this->_modified = array();
745
            $this->_oldValues = array();
746
        } else {
747
            $this->_values = array_merge($this->cleanData($data), $this->_values);
748
            $this->_data = array_merge($data, $this->_data);
749
        }
750
 
751
        if (!$this->isModified() && $this->isInProxyState()) {
752
            $this->_state = self::STATE_PROXY;
753
        }
754
    }
755
 
756
    /**
757
     * prepareIdentifiers
758
     * prepares identifiers for later use
759
     *
760
     * @param boolean $exists               whether or not this record exists in persistent data store
761
     * @return void
762
     */
763
    private function prepareIdentifiers($exists = true)
764
    {
765
        switch ($this->_table->getIdentifierType()) {
766
            case Doctrine_Core::IDENTIFIER_AUTOINC:
767
            case Doctrine_Core::IDENTIFIER_SEQUENCE:
768
            case Doctrine_Core::IDENTIFIER_NATURAL:
769
                $name = $this->_table->getIdentifier();
770
                if (is_array($name)) {
771
                    $name = $name[0];
772
                }
773
                if ($exists) {
774
                    if (isset($this->_data[$name]) && $this->_data[$name] !== self::$_null) {
775
                        $this->_id[$name] = $this->_data[$name];
776
                    }
777
                }
778
                break;
779
            case Doctrine_Core::IDENTIFIER_COMPOSITE:
780
                $names = $this->_table->getIdentifier();
781
 
782
                foreach ($names as $name) {
783
                    if ($this->_data[$name] === self::$_null) {
784
                        $this->_id[$name] = null;
785
                    } else {
786
                        $this->_id[$name] = $this->_data[$name];
787
                    }
788
                }
789
                break;
790
        }
791
    }
792
 
793
    /**
794
     * serialize
795
     * this method is automatically called when an instance of Doctrine_Record is serialized
796
     *
797
     * @return string
798
     */
799
    public function serialize()
800
    {
801
        $event = new Doctrine_Event($this, Doctrine_Event::RECORD_SERIALIZE);
802
 
803
        $this->preSerialize($event);
804
        $this->getTable()->getRecordListener()->preSerialize($event);
805
 
806
        $vars = get_object_vars($this);
807
 
808
        if ( ! $this->serializeReferences()) {
809
            unset($vars['_references']);
810
        }
811
        unset($vars['_table']);
812
        unset($vars['_errorStack']);
813
        unset($vars['_filter']);
814
        unset($vars['_node']);
815
 
816
        $data = $this->_data;
817
        if ($this->exists()) {
818
            $data = array_merge($data, $this->_id);
819
        }
820
 
821
        foreach ($data as $k => $v) {
822
            if ($v instanceof Doctrine_Record && $this->_table->getTypeOf($k) != 'object') {
823
                unset($vars['_data'][$k]);
824
            } elseif ($v === self::$_null) {
825
                unset($vars['_data'][$k]);
826
            } else {
827
                switch ($this->_table->getTypeOf($k)) {
828
                    case 'array':
829
                    case 'object':
830
                        $vars['_data'][$k] = serialize($vars['_data'][$k]);
831
                        break;
832
                    case 'gzip':
833
                        $vars['_data'][$k] = gzcompress($vars['_data'][$k]);
834
                        break;
835
                    case 'enum':
836
                        $vars['_data'][$k] = $this->_table->enumIndex($k, $vars['_data'][$k]);
837
                        break;
838
                }
839
            }
840
        }
841
 
842
        $str = serialize($vars);
843
 
844
        $this->postSerialize($event);
845
        $this->getTable()->getRecordListener()->postSerialize($event);
846
 
847
        return $str;
848
    }
849
 
850
    /**
851
     * this method is automatically called everytime an instance is unserialized
852
     *
853
     * @param string $serialized                Doctrine_Record as serialized string
854
     * @throws Doctrine_Record_Exception        if the cleanData operation fails somehow
855
     * @return void
856
     */
857
    public function unserialize($serialized)
858
    {
859
        $event = new Doctrine_Event($this, Doctrine_Event::RECORD_UNSERIALIZE);
860
 
861
        $manager    = Doctrine_Manager::getInstance();
862
        $connection = $manager->getConnectionForComponent(get_class($this));
863
 
864
        $this->_table = $connection->getTable(get_class($this));
865
 
866
        $this->preUnserialize($event);
867
        $this->getTable()->getRecordListener()->preUnserialize($event);
868
 
869
        $array = unserialize($serialized);
870
 
871
        foreach($array as $k => $v) {
872
            $this->$k = $v;
873
        }
874
 
875
        foreach ($this->_data as $k => $v) {
876
            switch ($this->_table->getTypeOf($k)) {
877
                case 'array':
878
                case 'object':
879
                    $this->_data[$k] = unserialize($this->_data[$k]);
880
                    break;
881
                case 'gzip':
882
                    $this->_data[$k] = gzuncompress($this->_data[$k]);
883
                    break;
884
                case 'enum':
885
                    $this->_data[$k] = $this->_table->enumValue($k, $this->_data[$k]);
886
                    break;
887
 
888
            }
889
        }
890
 
891
        // Remove existing record from the repository and table entity map.
892
        $this->_table->setData($this->_data);
893
        $existing_record = $this->_table->getRecord();
894
        if ($existing_record->exists()) {
895
            $this->_table->getRepository()->evict($existing_record->getOid());
896
            $this->_table->removeRecord($existing_record);
897
        }
898
 
899
        // Add the unserialized record to repository and entity map.
900
        $this->_oid = self::$_index;
901
        self::$_index++;
902
        $this->_table->getRepository()->add($this);
903
        $this->_table->addRecord($this);
904
 
905
        $this->cleanData($this->_data);
906
 
907
        $this->prepareIdentifiers($this->exists());
908
 
909
        $this->postUnserialize($event);
910
        $this->getTable()->getRecordListener()->postUnserialize($event);
911
    }
912
 
913
    /**
914
     * assigns the state of this record or returns it if called without parameters
915
     *
916
     * @param integer|string $state                 if set, this method tries to set the record state to $state
917
     * @see Doctrine_Record::STATE_* constants
918
     *
919
     * @throws Doctrine_Record_State_Exception      if trying to set an unknown state
920
     * @return null|integer
921
     */
922
    public function state($state = null)
923
    {
924
        if ($state == null) {
925
            return $this->_state;
926
        }
927
 
928
        $err = false;
929
        if (is_integer($state)) {
930
            if ($state >= 1 && $state <= 7) {
931
                $this->_state = $state;
932
            } else {
933
                $err = true;
934
            }
935
        } else if (is_string($state)) {
936
            $upper = strtoupper($state);
937
 
938
            $const = 'Doctrine_Record::STATE_' . $upper;
939
            if (defined($const)) {
940
                $this->_state = constant($const);
941
            } else {
942
                $err = true;
943
            }
944
        }
945
 
946
        if ($this->_state === Doctrine_Record::STATE_TCLEAN ||
947
                $this->_state === Doctrine_Record::STATE_CLEAN) {
948
            $this->_resetModified();
949
        }
950
 
951
        if ($err) {
952
            throw new Doctrine_Record_State_Exception('Unknown record state ' . $state);
953
        }
954
    }
955
 
956
    /**
957
     * refresh
958
     * refresh internal data from the database
959
     *
960
     * @param bool $deep                        If true, fetch also current relations. Caution: this deletes
961
     *                                          any aggregated values you may have queried beforee
962
     *
963
     * @throws Doctrine_Record_Exception        When the refresh operation fails (when the database row
964
     *                                          this record represents does not exist anymore)
965
     * @return boolean
966
     */
967
    public function refresh($deep = false)
968
    {
969
        $id = $this->identifier();
970
        if ( ! is_array($id)) {
971
            $id = array($id);
972
        }
973
        if (empty($id)) {
974
            return false;
975
        }
976
        $id = array_values($id);
977
 
978
        $overwrite = $this->getTable()->getAttribute(Doctrine_Core::ATTR_HYDRATE_OVERWRITE);
979
        $this->getTable()->setAttribute(Doctrine_Core::ATTR_HYDRATE_OVERWRITE, true);
980
 
981
        if ($deep) {
982
            $query = $this->getTable()->createQuery();
983
            foreach (array_keys($this->_references) as $name) {
984
                $query->leftJoin(get_class($this) . '.' . $name);
985
            }
986
            $query->where(implode(' = ? AND ', (array)$this->getTable()->getIdentifier()) . ' = ?');
987
            $this->clearRelated();
988
            $record = $query->fetchOne($id);
989
        } else {
990
            // Use HYDRATE_ARRAY to avoid clearing object relations
991
            $record = $this->getTable()->find($id, Doctrine_Core::HYDRATE_ARRAY);
992
            if ($record) {
993
                $this->hydrate($record);
994
            }
995
        }
996
 
997
        $this->getTable()->setAttribute(Doctrine_Core::ATTR_HYDRATE_OVERWRITE, $overwrite);
998
 
999
        if ($record === false) {
1000
            throw new Doctrine_Record_Exception('Failed to refresh. Record does not exist.');
1001
        }
1002
 
1003
        $this->_resetModified();
1004
 
1005
        $this->prepareIdentifiers();
1006
 
1007
        $this->_state = Doctrine_Record::STATE_CLEAN;
1008
 
1009
        return $this;
1010
    }
1011
 
1012
    /**
1013
     * refresh
1014
     * refresh data of related objects from the database
1015
     *
1016
     * @param string $name              name of a related component.
1017
     *                                  if set, this method only refreshes the specified related component
1018
     *
1019
     * @return Doctrine_Record          this object
1020
     */
1021
    public function refreshRelated($name = null)
1022
    {
1023
        if (is_null($name)) {
1024
            foreach ($this->_table->getRelations() as $rel) {
1025
                $alias = $rel->getAlias();
1026
                unset($this->_references[$alias]);
1027
                $reference = $rel->fetchRelatedFor($this);
1028
                if ($reference instanceof Doctrine_Collection) {
1029
                    $this->_references[$alias] = $reference;
1030
                } else if ($reference instanceof Doctrine_Record) {
1031
                    if ($reference->exists()) {
1032
                        $this->_references[$alias] = $reference;
1033
                    } else {
1034
                        $reference->free();
1035
                    }
1036
                }
1037
            }
1038
        } else {
1039
            unset($this->_references[$name]);
1040
            $rel = $this->_table->getRelation($name);
1041
            $reference = $rel->fetchRelatedFor($this);
1042
            if ($reference instanceof Doctrine_Collection) {
1043
                $this->_references[$name] = $reference;
1044
            } else if ($reference instanceof Doctrine_Record) {
1045
                if ($reference->exists()) {
1046
                    $this->_references[$name] = $reference;
1047
                } else {
1048
                    $reference->free();
1049
                }
1050
            }
1051
        }
1052
    }
1053
 
1054
    /**
1055
     * Clear a related reference or all references
1056
     *
1057
     * @param string $name The relationship reference to clear
1058
     * @return void
1059
     */
1060
    public function clearRelated($name = null)
1061
    {
1062
        if (is_null($name)) {
1063
            $this->_references = array();
1064
        } else {
1065
            unset($this->_references[$name]);
1066
        }
1067
    }
1068
 
1069
    /**
1070
     * Check if a related relationship exists. Will lazily load the relationship
1071
     * in order to check. If the reference didn't already exist and it doesn't
1072
     * exist in the database, the related reference will be cleared immediately.
1073
     *
1074
     * @param string $name
1075
     * @return boolean Whether or not the related relationship exists
1076
     */
1077
    public function relatedExists($name)
1078
    {
1079
        if ($this->hasReference($name) && $this->_references[$name] !== self::$_null) {
1080
            return true;
1081
        }
1082
 
1083
        $reference = $this->$name;
1084
        if ($reference instanceof Doctrine_Record) {
1085
            $exists = $reference->exists();
1086
        } elseif ($reference instanceof Doctrine_Collection) {
1087
            throw new Doctrine_Record_Exception(
1088
                'You can only call relatedExists() on a relationship that '.
1089
                'returns an instance of Doctrine_Record'
1090
            );
1091
        } else {
1092
            $exists = false;
1093
        }
1094
 
1095
        if (!$exists) {
1096
            $this->clearRelated($name);
1097
        }
1098
 
1099
        return $exists;
1100
    }
1101
 
1102
    /**
1103
     * returns the table object for this record.
1104
     *
1105
     * @return Doctrine_Table        a Doctrine_Table object
1106
     */
1107
    public function getTable()
1108
    {
1109
        return $this->_table;
1110
    }
1111
 
1112
    /**
1113
     * return all the internal data (columns)
1114
     *
1115
     * @return array                        an array containing all the properties
1116
     */
1117
    public function getData()
1118
    {
1119
        return $this->_data;
1120
    }
1121
 
1122
    /**
1123
     * returns the value of a property (column). If the property is not yet loaded
1124
     * this method does NOT load it.
1125
     *
1126
     * @param $name                         name of the property
1127
     * @throws Doctrine_Record_Exception    if trying to get an unknown property
1128
     * @return mixed
1129
     */
1130
    public function rawGet($fieldName)
1131
    {
1132
        if ( ! array_key_exists($fieldName, $this->_data)) {
1133
            throw new Doctrine_Record_Exception('Unknown property '. $fieldName);
1134
        }
1135
        if ($this->_data[$fieldName] === self::$_null) {
1136
            return null;
1137
        }
1138
 
1139
        return $this->_data[$fieldName];
1140
    }
1141
 
1142
    /**
1143
     * loads all the uninitialized properties from the database.
1144
     * Used to move a record from PROXY to CLEAN/DIRTY state.
1145
     *
1146
     * @param array $data  overwriting data to load in the record. Instance is hydrated from the table if not specified.
1147
     * @return boolean
1148
     */
1149
    public function load(array $data = array())
1150
    {
1151
        // only load the data from database if the Doctrine_Record is in proxy state
1152
        if ($this->exists() && $this->isInProxyState()) {
1153
            $id = $this->identifier();
1154
 
1155
            if ( ! is_array($id)) {
1156
                $id = array($id);
1157
            }
1158
 
1159
            if (empty($id)) {
1160
                return false;
1161
            }
1162
 
1163
            $table = $this->getTable();
1164
            $data = empty($data) ? $table->find($id, Doctrine_Core::HYDRATE_ARRAY) : $data;
1165
 
1166
            if (is_array($data)) {
1167
                foreach ($data as $field => $value) {
1168
                    if ($table->hasField($field) && ( ! array_key_exists($field, $this->_data) || $this->_data[$field] === self::$_null)) {
1169
                       $this->_data[$field] = $value;
1170
                   }
1171
                }
1172
            }
1173
 
1174
            if ($this->isModified()) {
1175
                $this->_state = Doctrine_Record::STATE_DIRTY;
1176
            } else if (!$this->isInProxyState()) {
1177
                $this->_state = Doctrine_Record::STATE_CLEAN;
1178
            }
1179
 
1180
            return true;
1181
        }
1182
 
1183
        return false;
1184
    }
1185
 
1186
    /**
1187
     * indicates whether record has any not loaded fields
1188
     *
1189
     * @return boolean
1190
     */
1191
    public function isInProxyState()
1192
    {
1193
        $count = 0;
1194
        foreach ($this->_data as $value) {
1195
            if ($value !== self::$_null) {
1196
                $count++;
1197
            }
1198
        }
1199
        if ($count < $this->_table->getColumnCount()) {
1200
            return true;
1201
        }
1202
        return false;
1203
    }
1204
 
1205
    /**
1206
     * sets a fieldname to have a custom accessor or check if a field has a custom
1207
     * accessor defined (when called without $accessor parameter).
1208
     *
1209
     * @param string $fieldName
1210
     * @param string $accessor
1211
     * @return boolean
1212
     */
1213
    public function hasAccessor($fieldName, $accessor = null)
1214
    {
1215
        $componentName = $this->_table->getComponentName();
1216
        if ($accessor) {
1217
            self::$_customAccessors[$componentName][$fieldName] = $accessor;
1218
        } else {
1219
            return (isset(self::$_customAccessors[$componentName][$fieldName]) && self::$_customAccessors[$componentName][$fieldName]);
1220
        }
1221
    }
1222
 
1223
    /**
1224
     * clears the accessor for a field name
1225
     *
1226
     * @param string $fieldName
1227
     * @return void
1228
     */
1229
    public function clearAccessor($fieldName)
1230
    {
1231
        $componentName = $this->_table->getComponentName();
1232
        unset(self::$_customAccessors[$componentName][$fieldName]);
1233
    }
1234
 
1235
    /**
1236
     * gets the custom accessor for a field name
1237
     *
1238
     * @param string $fieldName
1239
     * @return string $accessor
1240
     */
1241
    public function getAccessor($fieldName)
1242
    {
1243
        if ($this->hasAccessor($fieldName)) {
1244
            $componentName = $this->_table->getComponentName();
1245
            return self::$_customAccessors[$componentName][$fieldName];
1246
        }
1247
    }
1248
 
1249
    /**
1250
     * gets all accessors for this component instance
1251
     *
1252
     * @return array $accessors
1253
     */
1254
    public function getAccessors()
1255
    {
1256
        $componentName = $this->_table->getComponentName();
1257
        return isset(self::$_customAccessors[$componentName]) ? self::$_customAccessors[$componentName] : array();
1258
    }
1259
 
1260
    /**
1261
     * sets a fieldname to have a custom mutator or check if a field has a custom
1262
     * mutator defined (when called without the $mutator parameter)
1263
     *
1264
     * @param string $fieldName
1265
     * @param string $mutator
1266
     * @return boolean
1267
     */
1268
    public function hasMutator($fieldName, $mutator = null)
1269
    {
1270
        $componentName = $this->_table->getComponentName();
1271
        if ($mutator) {
1272
            self::$_customMutators[$componentName][$fieldName] = $mutator;
1273
        } else {
1274
            return (isset(self::$_customMutators[$componentName][$fieldName]) && self::$_customMutators[$componentName][$fieldName]);
1275
        }
1276
    }
1277
 
1278
    /**
1279
     * gets the custom mutator for a field name
1280
     *
1281
     * @param string $fieldname
1282
     * @return string
1283
     */
1284
    public function getMutator($fieldName)
1285
    {
1286
        if ($this->hasMutator($fieldName)) {
1287
            $componentName = $this->_table->getComponentName();
1288
            return self::$_customMutators[$componentName][$fieldName];
1289
        }
1290
    }
1291
 
1292
    /**
1293
     * clears the custom mutator for a field name
1294
     *
1295
     * @param string $fieldName
1296
     * @return void
1297
     */
1298
    public function clearMutator($fieldName)
1299
    {
1300
        $componentName = $this->_table->getComponentName();
1301
        unset(self::$_customMutators[$componentName][$fieldName]);
1302
    }
1303
 
1304
    /**
1305
     * gets all custom mutators for this component instance
1306
     *
1307
     * @return array $mutators
1308
     */
1309
    public function getMutators()
1310
    {
1311
        $componentName = $this->_table->getComponentName();
1312
        return self::$_customMutators[$componentName];
1313
    }
1314
 
1315
    /**
1316
     * Set a fieldname to have a custom accessor and mutator
1317
     *
1318
     * @param string $fieldname
1319
     * @param string $accessor
1320
     * @param string $mutator
1321
     */
1322
    public function hasAccessorMutator($fieldName, $accessor, $mutator)
1323
    {
1324
        $this->hasAccessor($fieldName, $accessor);
1325
        $this->hasMutator($fieldName, $mutator);
1326
    }
1327
 
1328
    /**
1329
     * returns a value of a property or a related component
1330
     *
1331
     * @param mixed $fieldName                  name of the property or related component
1332
     * @param boolean $load                     whether or not to invoke the loading procedure
1333
     * @throws Doctrine_Record_Exception        if trying to get a value of unknown property / related component
1334
     * @return mixed
1335
     */
1336
    public function get($fieldName, $load = true)
1337
    {
1338
        if ($this->_table->getAttribute(Doctrine_Core::ATTR_AUTO_ACCESSOR_OVERRIDE) || $this->hasAccessor($fieldName)) {
1339
            $componentName = $this->_table->getComponentName();
1340
 
1341
            $accessor = $this->hasAccessor($fieldName)
1342
                ? $this->getAccessor($fieldName)
1343
                : 'get' . Doctrine_Inflector::classify($fieldName);
1344
 
1345
            if ($this->hasAccessor($fieldName) || method_exists($this, $accessor)) {
1346
                $this->hasAccessor($fieldName, $accessor);
1347
                return $this->$accessor($load, $fieldName);
1348
            }
1349
        }
1350
        return $this->_get($fieldName, $load);
1351
    }
1352
 
1353
    protected function _get($fieldName, $load = true)
1354
    {
1355
        $value = self::$_null;
1356
 
1357
        if (array_key_exists($fieldName, $this->_values)) {
1358
            return $this->_values[$fieldName];
1359
        }
1360
 
1361
        if (array_key_exists($fieldName, $this->_data)) {
1362
            // check if the value is the Doctrine_Null object located in self::$_null)
1363
            if ($this->_data[$fieldName] === self::$_null && $load) {
1364
                $this->load();
1365
            }
1366
 
1367
            if ($this->_data[$fieldName] === self::$_null) {
1368
                $value = null;
1369
            } else {
1370
                $value = $this->_data[$fieldName];
1371
            }
1372
 
1373
            return $value;
1374
        }
1375
 
1376
        try {
1377
            if ( ! isset($this->_references[$fieldName])) {
1378
                if ($load) {
1379
                    $rel = $this->_table->getRelation($fieldName);
1380
                    $this->_references[$fieldName] = $rel->fetchRelatedFor($this);
1381
                } else {
1382
                    $this->_references[$fieldName] = null;
1383
                }
1384
            }
1385
 
1386
            if ($this->_references[$fieldName] === self::$_null) {
1387
                return null;
1388
            }
1389
 
1390
            return $this->_references[$fieldName];
1391
        } catch (Doctrine_Table_Exception $e) {
1392
            $success = false;
1393
            foreach ($this->_table->getFilters() as $filter) {
1394
                try {
1395
                    $value = $filter->filterGet($this, $fieldName);
1396
                    $success = true;
1397
                } catch (Doctrine_Exception $e) {}
1398
            }
1399
            if ($success) {
1400
                return $value;
1401
            } else {
1402
                throw $e;
1403
            }
1404
        }
1405
    }
1406
 
1407
    /**
1408
     * sets a value that will be managed as if it were a field by magic accessor and mutators, @see get() and @see set().
1409
     * Normally used by Doctrine for the mapping of aggregate values.
1410
     *
1411
     * @param string $name                  the name of the mapped value
1412
     * @param mixed $value                  mixed value to be mapped
1413
     * @return void
1414
     */
1415
    public function mapValue($name, $value = null)
1416
    {
1417
        $this->_values[$name] = $value;
1418
    }
1419
 
1420
    /**
1421
     * Tests whether a mapped value exists
1422
     *
1423
     * @param string $name  the name of the property
1424
     * @return boolean
1425
     */
1426
    public function hasMappedValue($name)
1427
    {
1428
        return array_key_exists($name, $this->_values);
1429
    }
1430
 
1431
    /**
1432
     * alters mapped values, properties and related components.
1433
     *
1434
     * @param mixed $name                   name of the property or reference
1435
     * @param mixed $value                  value of the property or reference
1436
     * @param boolean $load                 whether or not to refresh / load the uninitialized record data
1437
     *
1438
     * @throws Doctrine_Record_Exception    if trying to set a value for unknown property / related component
1439
     * @throws Doctrine_Record_Exception    if trying to set a value of wrong type for related component
1440
     *
1441
     * @return Doctrine_Record
1442
     */
1443
    public function set($fieldName, $value, $load = true)
1444
    {
1445
        if ($this->_table->getAttribute(Doctrine_Core::ATTR_AUTO_ACCESSOR_OVERRIDE) || $this->hasMutator($fieldName)) {
1446
            $componentName = $this->_table->getComponentName();
1447
            $mutator = $this->hasMutator($fieldName)
1448
                ? $this->getMutator($fieldName):
1449
                'set' . Doctrine_Inflector::classify($fieldName);
1450
 
1451
            if ($this->hasMutator($fieldName) || method_exists($this, $mutator)) {
1452
                $this->hasMutator($fieldName, $mutator);
1453
                return $this->$mutator($value, $load, $fieldName);
1454
            }
1455
        }
1456
        return $this->_set($fieldName, $value, $load);
1457
    }
1458
 
1459
    protected function _set($fieldName, $value, $load = true)
1460
    {
1461
        if (array_key_exists($fieldName, $this->_values)) {
1462
            $this->_values[$fieldName] = $value;
1463
        } else if (array_key_exists($fieldName, $this->_data)) {
1464
            $type = $this->_table->getTypeOf($fieldName);
1465
            if ($value instanceof Doctrine_Record) {
1466
                $id = $value->getIncremented();
1467
 
1468
                if ($id !== null && $type !== 'object') {
1469
                    $value = $id;
1470
                }
1471
            }
1472
 
1473
            if ($load) {
1474
                $old = $this->get($fieldName, $load);
1475
            } else {
1476
                $old = $this->_data[$fieldName];
1477
            }
1478
 
1479
            if ($this->_isValueModified($type, $old, $value)) {
1480
                if ($value === null) {
1481
                    $value = $this->_table->getDefaultValueOf($fieldName);
1482
                }
1483
                $this->_data[$fieldName] = $value;
1484
                $this->_modified[] = $fieldName;
1485
                $this->_oldValues[$fieldName] = $old;
1486
 
1487
                switch ($this->_state) {
1488
                    case Doctrine_Record::STATE_CLEAN:
1489
                    case Doctrine_Record::STATE_PROXY:
1490
                        $this->_state = Doctrine_Record::STATE_DIRTY;
1491
                        break;
1492
                    case Doctrine_Record::STATE_TCLEAN:
1493
                        $this->_state = Doctrine_Record::STATE_TDIRTY;
1494
                        break;
1495
                }
1496
            }
1497
        } else {
1498
            try {
1499
                $this->coreSetRelated($fieldName, $value);
1500
            } catch (Doctrine_Table_Exception $e) {
1501
                $success = false;
1502
                foreach ($this->_table->getFilters() as $filter) {
1503
                    try {
1504
                        $value = $filter->filterSet($this, $fieldName, $value);
1505
                        $success = true;
1506
                    } catch (Doctrine_Exception $e) {}
1507
                }
1508
                if ($success) {
1509
                    return $value;
1510
                } else {
1511
                    throw $e;
1512
                }
1513
            }
1514
        }
1515
 
1516
        return $this;
1517
    }
1518
 
1519
    /**
1520
     * Check if a value has changed according to Doctrine
1521
     * Doctrine is loose with type checking in the same ways PHP is for consistancy of behavior
1522
     *
1523
     * This function basically says if what is being set is of Doctrine type boolean and something
1524
     * like current_value == 1 && new_value = true would not be considered modified
1525
     *
1526
     * Simply doing $old !== $new will return false for boolean columns would mark the field as modified
1527
     * and change it in the database when it is not necessary
1528
     *
1529
     * @param string $type  Doctrine type of the column
1530
     * @param string $old   Old value
1531
     * @param string $new   New value
1532
     * @return boolean $modified  Whether or not Doctrine considers the value modified
1533
     */
1534
    protected function _isValueModified($type, $old, $new)
1535
    {
1536
        if ($new instanceof Doctrine_Expression) {
1537
            return true;
1538
        }
1539
 
1540
        if ($type == 'boolean' && (is_bool($old) || is_numeric($old)) && (is_bool($new) || is_numeric($new)) && $old == $new) {
1541
            return false;
1542
        } else if (in_array($type, array('decimal', 'float')) && is_numeric($old) && is_numeric($new)) {
1543
            return $old * 100 != $new * 100;
1544
        } else if (in_array($type, array('integer', 'int')) && is_numeric($old) && is_numeric($new)) {
1545
            return $old != $new;
1546
        } else if ($type == 'timestamp' || $type == 'date') {
1547
            $oldStrToTime = strtotime($old);
1548
            $newStrToTime = strtotime($new);
1549
            if ($oldStrToTime && $newStrToTime) {
1550
                return $oldStrToTime !== $newStrToTime;
1551
            } else {
1552
                return $old !== $new;
1553
            }
1554
        } else {
1555
            return $old !== $new;
1556
        }
1557
    }
1558
 
1559
    /**
1560
     * Places a related component in the object graph.
1561
     *
1562
     * This method inserts a related component instance in this record
1563
     * relations, populating the foreign keys accordingly.
1564
     *
1565
     * @param string $name                                  related component alias in the relation
1566
     * @param Doctrine_Record|Doctrine_Collection $value    object to be linked as a related component
1567
     * @todo Refactor. What about composite keys?
1568
     */
1569
    public function coreSetRelated($name, $value)
1570
    {
1571
        $rel = $this->_table->getRelation($name);
1572
 
1573
        if ($value === null) {
1574
            $value = self::$_null;
1575
        }
1576
 
1577
        // one-to-many or one-to-one relation
1578
        if ($rel instanceof Doctrine_Relation_ForeignKey || $rel instanceof Doctrine_Relation_LocalKey) {
1579
            if ( ! $rel->isOneToOne()) {
1580
                // one-to-many relation found
1581
                if ( ! ($value instanceof Doctrine_Collection)) {
1582
                    throw new Doctrine_Record_Exception("Couldn't call Doctrine_Core::set(), second argument should be an instance of Doctrine_Collection when setting one-to-many references.");
1583
                }
1584
 
1585
                if (isset($this->_references[$name])) {
1586
                    $this->_references[$name]->setData($value->getData());
1587
 
1588
                    return $this;
1589
                }
1590
            } else {
1591
                $localFieldName = $this->_table->getFieldName($rel->getLocal());
1592
 
1593
                if ($value !== self::$_null) {
1594
                    $relatedTable = $rel->getTable();
1595
                    $foreignFieldName = $relatedTable->getFieldName($rel->getForeign());
1596
                }
1597
 
1598
                // one-to-one relation found
1599
                if ( ! ($value instanceof Doctrine_Record) && ! ($value instanceof Doctrine_Null)) {
1600
                    throw new Doctrine_Record_Exception("Couldn't call Doctrine_Core::set(), second argument should be an instance of Doctrine_Record or Doctrine_Null when setting one-to-one references.");
1601
                }
1602
 
1603
                if ($rel instanceof Doctrine_Relation_LocalKey) {
1604
                    if ($value !== self::$_null &&  ! empty($foreignFieldName) && $foreignFieldName != $value->getTable()->getIdentifier()) {
1605
                        $this->set($localFieldName, $value->rawGet($foreignFieldName), false);
1606
                    } else {
1607
                        // FIX: Ticket #1280 fits in this situation
1608
                        $this->set($localFieldName, $value, false);
1609
                    }
1610
                } elseif ($value !== self::$_null) {
1611
                    // We should only be able to reach $foreignFieldName if we have a Doctrine_Record on hands
1612
                    $value->set($foreignFieldName, $this, false);
1613
                }
1614
            }
1615
        } else if ($rel instanceof Doctrine_Relation_Association) {
1616
            // join table relation found
1617
            if ( ! ($value instanceof Doctrine_Collection)) {
1618
                throw new Doctrine_Record_Exception("Couldn't call Doctrine_Core::set(), second argument should be an instance of Doctrine_Collection when setting many-to-many references.");
1619
            }
1620
        }
1621
 
1622
        $this->_references[$name] = $value;
1623
    }
1624
 
1625
    /**
1626
     * test whether a field (column, mapped value, related component, accessor) is accessible by @see get()
1627
     *
1628
     * @param string $fieldName
1629
     * @return boolean
1630
     */
1631
    public function contains($fieldName)
1632
    {
1633
        if (array_key_exists($fieldName, $this->_data)) {
1634
            // this also returns true if the field is a Doctrine_Null.
1635
            // imho this is not correct behavior.
1636
            return true;
1637
        }
1638
        if (isset($this->_id[$fieldName])) {
1639
            return true;
1640
        }
1641
        if (isset($this->_values[$fieldName])) {
1642
            return true;
1643
        }
1644
        if (isset($this->_references[$fieldName]) &&
1645
            $this->_references[$fieldName] !== self::$_null) {
1646
 
1647
            return true;
1648
        }
1649
        return false;
1650
    }
1651
 
1652
    /**
1653
     * deletes a column or a related component.
1654
     * @param string $name
1655
     * @return void
1656
     */
1657
    public function __unset($name)
1658
    {
1659
        if (array_key_exists($name, $this->_data)) {
1660
            $this->_data[$name] = array();
1661
        } else if (isset($this->_references[$name])) {
1662
            if ($this->_references[$name] instanceof Doctrine_Record) {
1663
                $this->_pendingDeletes[] = $this->$name;
1664
                $this->_references[$name] = self::$_null;
1665
            } elseif ($this->_references[$name] instanceof Doctrine_Collection) {
1666
                $this->_pendingDeletes[] = $this->$name;
1667
                $this->_references[$name]->setData(array());
1668
            }
1669
        }
1670
    }
1671
 
1672
    /**
1673
     * returns Doctrine_Record instances which need to be deleted on save
1674
     *
1675
     * @return array
1676
     */
1677
    public function getPendingDeletes()
1678
    {
1679
        return $this->_pendingDeletes;
1680
    }
1681
 
1682
    /**
1683
     * returns Doctrine_Record instances which need to be unlinked (deleting the relation) on save
1684
     *
1685
     * @return array $pendingUnlinks
1686
     */
1687
    public function getPendingUnlinks()
1688
    {
1689
        return $this->_pendingUnlinks;
1690
    }
1691
 
1692
    /**
1693
     * resets pending record unlinks
1694
     *
1695
     * @return void
1696
     */
1697
    public function resetPendingUnlinks()
1698
    {
1699
        $this->_pendingUnlinks = array();
1700
    }
1701
 
1702
    /**
1703
     * applies the changes made to this object into database
1704
     * this method is smart enough to know if any changes are made
1705
     * and whether to use INSERT or UPDATE statement
1706
     *
1707
     * this method also saves the related components
1708
     *
1709
     * @param Doctrine_Connection $conn     optional connection parameter
1710
     * @throws Exception                    if record is not valid and validation is active
1711
     * @return void
1712
     */
1713
    public function save(Doctrine_Connection $conn = null)
1714
    {
1715
        if ($conn === null) {
1716
            $conn = $this->_table->getConnection();
1717
        }
1718
        $conn->unitOfWork->saveGraph($this);
1719
    }
1720
 
1721
    /**
1722
     * tries to save the object and all its related components.
1723
     * In contrast to Doctrine_Record::save(), this method does not
1724
     * throw an exception when validation fails but returns TRUE on
1725
     * success or FALSE on failure.
1726
     *
1727
     * @param Doctrine_Connection $conn                 optional connection parameter
1728
     * @return TRUE if the record was saved sucessfully without errors, FALSE otherwise.
1729
     */
1730
    public function trySave(Doctrine_Connection $conn = null) {
1731
        try {
1732
            $this->save($conn);
1733
            return true;
1734
        } catch (Doctrine_Validator_Exception $ignored) {
1735
            return false;
1736
        }
1737
    }
1738
 
1739
    /**
1740
     * executes a SQL REPLACE query. A REPLACE query is identical to a INSERT
1741
     * query, except that if there is already a row in the table with the same
1742
     * key field values, the REPLACE query just updates its values instead of
1743
     * inserting a new row.
1744
     *
1745
     * The REPLACE type of query does not make part of the SQL standards. Since
1746
     * practically only MySQL and SQLIte implement it natively, this type of
1747
     * query isemulated through this method for other DBMS using standard types
1748
     * of queries inside a transaction to assure the atomicity of the operation.
1749
     *
1750
     * @param Doctrine_Connection $conn             optional connection parameter
1751
     * @throws Doctrine_Connection_Exception        if some of the key values was null
1752
     * @throws Doctrine_Connection_Exception        if there were no key fields
1753
     * @throws Doctrine_Connection_Exception        if something fails at database level
1754
     * @return integer                              number of rows affected
1755
     */
1756
    public function replace(Doctrine_Connection $conn = null)
1757
    {
1758
        if ($conn === null) {
1759
            $conn = $this->_table->getConnection();
1760
        }
1761
        return $conn->unitOfWork->saveGraph($this, true);
1762
    }
1763
 
1764
    /**
1765
     * retrieves an array of modified fields and associated new values.
1766
     *
1767
     * @param boolean $old      pick the old values (instead of the new ones)
1768
     * @param boolean $last     pick only lastModified values (@see getLastModified())
1769
     * @return array $a
1770
     */
1771
    public function getModified($old = false, $last = false)
1772
    {
1773
        $a = array();
1774
 
1775
        $modified = $last ? $this->_lastModified:$this->_modified;
1776
        foreach ($modified as $fieldName) {
1777
            if ($old) {
1778
                $a[$fieldName] = isset($this->_oldValues[$fieldName])
1779
                    ? $this->_oldValues[$fieldName]
1780
                    : $this->getTable()->getDefaultValueOf($fieldName);
1781
            } else {
1782
                $a[$fieldName] = $this->_data[$fieldName];
1783
            }
1784
        }
1785
        return $a;
1786
    }
1787
 
1788
    /**
1789
     * returns an array of the modified fields from the last transaction.
1790
     *
1791
     * @param boolean $old      pick the old values (instead of the new ones)
1792
     * @return array
1793
     */
1794
    public function getLastModified($old = false)
1795
    {
1796
        return $this->getModified($old, true);
1797
    }
1798
 
1799
    /**
1800
     * Retrieves data prepared for a sql transaction.
1801
     *
1802
     * Returns an array of modified fields and values with data preparation;
1803
     * adds column aggregation inheritance and converts Records into primary
1804
     * key values.
1805
     *
1806
     * @param array $array
1807
     * @return array
1808
     * @todo What about a little bit more expressive name? getPreparedData?
1809
     */
1810
    public function getPrepared(array $array = array())
1811
    {
1812
        $a = array();
1813
 
1814
        if (empty($array)) {
1815
            $modifiedFields = $this->_modified;
1816
        }
1817
 
1818
        foreach ($modifiedFields as $field) {
1819
            $type = $this->_table->getTypeOf($field);
1820
 
1821
            if ($this->_data[$field] === self::$_null) {
1822
                $a[$field] = null;
1823
                continue;
1824
            }
1825
 
1826
            switch ($type) {
1827
                case 'array':
1828
                case 'object':
1829
                    $a[$field] = serialize($this->_data[$field]);
1830
                    break;
1831
                case 'gzip':
1832
                    $a[$field] = gzcompress($this->_data[$field],5);
1833
                    break;
1834
                case 'boolean':
1835
                    $a[$field] = $this->getTable()->getConnection()->convertBooleans($this->_data[$field]);
1836
                break;
1837
                case 'set':
1838
                    if (is_array($this->_data[$field])) {
1839
                        $a[$field] = implode(',', $this->_data[$field]);
1840
                    } else {
1841
                        $a[$field] = $this->_data[$field];
1842
                    }
1843
                break;
1844
                default:
1845
                    if ($this->_data[$field] instanceof Doctrine_Record) {
1846
                        $a[$field] = $this->_data[$field]->getIncremented();
1847
                        if ($a[$field] !== null) {
1848
                            $this->_data[$field] = $a[$field];
1849
                        }
1850
                    } else {
1851
                        $a[$field] = $this->_data[$field];
1852
                    }
1853
                    /** TODO:
1854
                    if ($this->_data[$v] === null) {
1855
                        throw new Doctrine_Record_Exception('Unexpected null value.');
1856
                    }
1857
                    */
1858
            }
1859
        }
1860
 
1861
        return $a;
1862
    }
1863
 
1864
    /**
1865
     * implements Countable interface
1866
     *
1867
     * @return integer          the number of columns in this record
1868
     */
1869
    public function count()
1870
    {
1871
        return count($this->_data);
1872
    }
1873
 
1874
    /**
1875
     * alias for @see count()
1876
     *
1877
     * @return integer          the number of columns in this record
1878
     */
1879
    public function columnCount()
1880
    {
1881
        return $this->count();
1882
    }
1883
 
1884
    /**
1885
     * returns the record representation as an array
1886
     *
1887
     * @link http://www.doctrine-project.org/documentation/manual/1_1/en/working-with-models
1888
     * @param boolean $deep         whether to include relations
1889
     * @param boolean $prefixKey    not used
1890
     * @return array
1891
     */
1892
    public function toArray($deep = true, $prefixKey = false)
1893
    {
1894
        if ($this->_state == self::STATE_LOCKED || $this->_state == self::STATE_TLOCKED) {
1895
            return false;
1896
        }
1897
 
1898
        $stateBeforeLock = $this->_state;
1899
        $this->_state = $this->exists() ? self::STATE_LOCKED : self::STATE_TLOCKED;
1900
 
1901
        $a = array();
1902
 
1903
        foreach ($this as $column => $value) {
1904
            if ($value === self::$_null || is_object($value)) {
1905
                $value = null;
1906
            }
1907
 
1908
            $columnValue = $this->get($column, false);
1909
 
1910
            if ($columnValue instanceof Doctrine_Record) {
1911
                $a[$column] = $columnValue->getIncremented();
1912
            } else {
1913
                $a[$column] = $columnValue;
1914
            }
1915
        }
1916
 
1917
        if ($this->_table->getIdentifierType() ==  Doctrine_Core::IDENTIFIER_AUTOINC) {
1918
            $i      = $this->_table->getIdentifier();
1919
            $a[$i]  = $this->getIncremented();
1920
        }
1921
 
1922
        if ($deep) {
1923
            foreach ($this->_references as $key => $relation) {
1924
                if ( ! $relation instanceof Doctrine_Null) {
1925
                    $a[$key] = $relation->toArray($deep, $prefixKey);
1926
                }
1927
            }
1928
        }
1929
 
1930
        // [FIX] Prevent mapped Doctrine_Records from being displayed fully
1931
        foreach ($this->_values as $key => $value) {
1932
            $a[$key] = ($value instanceof Doctrine_Record || $value instanceof Doctrine_Collection)
1933
                ? $value->toArray($deep, $prefixKey) : $value;
1934
        }
1935
 
1936
        $this->_state = $stateBeforeLock;
1937
 
1938
        return $a;
1939
    }
1940
 
1941
    /**
1942
     * merges this record with an array of values
1943
     * or with another existing instance of this object
1944
     *
1945
     * @see fromArray()
1946
     * @link http://www.doctrine-project.org/documentation/manual/1_1/en/working-with-models
1947
     * @param string $array  array of data to merge, see link for documentation
1948
     * @param bool   $deep   whether or not to merge relations
1949
     * @return void
1950
     */
1951
    public function merge($data, $deep = true)
1952
    {
1953
        if ($data instanceof $this) {
1954
            $array = $data->toArray($deep);
1955
        } else if (is_array($data)) {
1956
            $array = $data;
1957
        }
1958
 
1959
        return $this->fromArray($array, $deep);
1960
    }
1961
 
1962
    /**
1963
     * imports data from a php array
1964
     *
1965
     * @link http://www.doctrine-project.org/documentation/manual/1_1/en/working-with-models
1966
     * @param string $array  array of data, see link for documentation
1967
     * @param bool   $deep   whether or not to act on relations
1968
     * @return void
1969
     */
1970
    public function fromArray(array $array, $deep = true)
1971
    {
1972
        $refresh = false;
1973
        foreach ($array as $key => $value) {
1974
            if ($key == '_identifier') {
1975
                $refresh = true;
1976
                $this->assignIdentifier($value);
1977
                continue;
1978
            }
1979
 
1980
            if ($deep && $this->getTable()->hasRelation($key)) {
1981
                if ( ! $this->$key) {
1982
                    $this->refreshRelated($key);
1983
                }
1984
 
1985
                if (is_array($value)) {
1986
                    if (isset($value[0]) && ! is_array($value[0])) {
1987
                        $this->unlink($key, array(), false);
1988
                        $this->link($key, $value, false);
1989
                    } else {
1990
                        $this->$key->fromArray($value, $deep);
1991
                    }
1992
                }
1993
            } else if ($this->getTable()->hasField($key) || array_key_exists($key, $this->_values)) {
1994
                $this->set($key, $value);
1995
            } else {
1996
                $method = 'set' . Doctrine_Inflector::classify($key);
1997
 
1998
                try {
1999
                    if (is_callable(array($this, $method))) {
2000
                        $this->$method($value);
2001
                    }
2002
                } catch (Doctrine_Record_Exception $e) {}
2003
            }
2004
        }
2005
 
2006
        if ($refresh) {
2007
            $this->refresh();
2008
        }
2009
    }
2010
 
2011
    /**
2012
     * synchronizes a Doctrine_Record instance and its relations with data from an array
2013
     *
2014
     * it expects an array representation of a Doctrine_Record similar to the return
2015
     * value of the toArray() method. If the array contains relations it will create
2016
     * those that don't exist, update the ones that do, and delete the ones missing
2017
     * on the array but available on the Doctrine_Record (unlike @see fromArray() that
2018
     * does not touch what it is not in $array)
2019
     *
2020
     * @param array $array representation of a Doctrine_Record
2021
     * @param bool   $deep   whether or not to act on relations
2022
     */
2023
    public function synchronizeWithArray(array $array, $deep = true)
2024
    {
2025
        $refresh = false;
2026
        foreach ($array as $key => $value) {
2027
            if ($key == '_identifier') {
2028
                $refresh = true;
2029
                $this->assignIdentifier($value);
2030
                continue;
2031
            }
2032
 
2033
            if ($deep && $this->getTable()->hasRelation($key)) {
2034
                if ( ! $this->$key) {
2035
                    $this->refreshRelated($key);
2036
                }
2037
 
2038
                if (is_array($value)) {
2039
                    if (isset($value[0]) && ! is_array($value[0])) {
2040
                        $this->unlink($key, array(), false);
2041
                        $this->link($key, $value, false);
2042
                    } else {
2043
                        $this->$key->synchronizeWithArray($value);
2044
                        $this->$key = $this->$key;
2045
                    }
2046
                }
2047
            } else if ($this->getTable()->hasField($key) || array_key_exists($key, $this->_values)) {
2048
                $this->set($key, $value);
2049
            }
2050
        }
2051
 
2052
        // Eliminate relationships missing in the $array
2053
        foreach ($this->_references as $name => $relation) {
2054
	        $rel = $this->getTable()->getRelation($name);
2055
 
2056
            if ( ! $rel->isRefClass() && ! isset($array[$name]) && ( ! $rel->isOneToOne() || ! isset($array[$rel->getLocalFieldName()]))) {
2057
                unset($this->$name);
2058
            }
2059
        }
2060
 
2061
        if ($refresh) {
2062
            $this->refresh();
2063
        }
2064
    }
2065
 
2066
    /**
2067
     * exports instance to a chosen format
2068
     *
2069
     * @param string $type  format type: array, xml, yml, json
2070
     * @param string $deep  whether or not to export all relationships
2071
     * @return string       representation as $type format. Array is $type is array
2072
     */
2073
    public function exportTo($type, $deep = true)
2074
    {
2075
        if ($type == 'array') {
2076
            return $this->toArray($deep);
2077
        } else {
2078
            return Doctrine_Parser::dump($this->toArray($deep, true), $type);
2079
        }
2080
    }
2081
 
2082
    /**
2083
     * imports data from a chosen format in the current instance
2084
     *
2085
     * @param string $type  Format type: xml, yml, json
2086
     * @param string $data  Data to be parsed and imported
2087
     * @return void
2088
     */
2089
    public function importFrom($type, $data, $deep = true)
2090
    {
2091
        if ($type == 'array') {
2092
            return $this->fromArray($data, $deep);
2093
        } else {
2094
            return $this->fromArray(Doctrine_Parser::load($data, $type), $deep);
2095
        }
2096
    }
2097
 
2098
    /**
2099
     * returns true if this record is saved in the database, otherwise false (it is transient)
2100
     *
2101
     * @return boolean
2102
     */
2103
    public function exists()
2104
    {
2105
        return ($this->_state !== Doctrine_Record::STATE_TCLEAN  &&
2106
                $this->_state !== Doctrine_Record::STATE_TDIRTY  &&
2107
                $this->_state !== Doctrine_Record::STATE_TLOCKED &&
2108
                $this->_state !== null);
2109
    }
2110
 
2111
    /**
2112
     * returns true if this record was modified, otherwise false
2113
     *
2114
     * @param boolean $deep     whether to process also the relations for changes
2115
     * @return boolean
2116
     */
2117
    public function isModified($deep = false)
2118
    {
2119
        $modified = ($this->_state === Doctrine_Record::STATE_DIRTY ||
2120
                $this->_state === Doctrine_Record::STATE_TDIRTY);
2121
        if ( ! $modified && $deep) {
2122
            if ($this->_state == self::STATE_LOCKED || $this->_state == self::STATE_TLOCKED) {
2123
                return false;
2124
            }
2125
 
2126
            $stateBeforeLock = $this->_state;
2127
            $this->_state = $this->exists() ? self::STATE_LOCKED : self::STATE_TLOCKED;
2128
 
2129
            foreach ($this->_references as $reference) {
2130
                if ($reference instanceof Doctrine_Record) {
2131
                    if ($modified = $reference->isModified($deep)) {
2132
                        break;
2133
                    }
2134
                } else if ($reference instanceof Doctrine_Collection) {
2135
                    foreach ($reference as $record) {
2136
                        if ($modified = $record->isModified($deep)) {
2137
                            break 2;
2138
                        }
2139
                    }
2140
                }
2141
            }
2142
            $this->_state = $stateBeforeLock;
2143
        }
2144
        return $modified;
2145
    }
2146
 
2147
    /**
2148
     * checks existence of properties and related components
2149
     * @param mixed $fieldName   name of the property or reference
2150
     * @return boolean
2151
     */
2152
    public function hasRelation($fieldName)
2153
    {
2154
        if (isset($this->_data[$fieldName]) || isset($this->_id[$fieldName])) {
2155
            return true;
2156
        }
2157
        return $this->_table->hasRelation($fieldName);
2158
    }
2159
 
2160
    /**
2161
     * implements IteratorAggregate interface
2162
     * @return Doctrine_Record_Iterator     iterator through data
2163
     */
2164
    public function getIterator()
2165
    {
2166
        return new Doctrine_Record_Iterator($this);
2167
    }
2168
 
2169
    /**
2170
     * deletes this data access object and all the related composites
2171
     * this operation is isolated by a transaction
2172
     *
2173
     * this event can be listened by the onPreDelete and onDelete listeners
2174
     *
2175
     * @return boolean      true if successful
2176
     */
2177
    public function delete(Doctrine_Connection $conn = null)
2178
    {
2179
        if ($conn == null) {
2180
            $conn = $this->_table->getConnection();
2181
        }
2182
        return $conn->unitOfWork->delete($this);
2183
    }
2184
 
2185
    /**
2186
     * generates a copy of this object. Returns an instance of the same class of $this.
2187
     *
2188
     * @param boolean $deep     whether to duplicates the objects targeted by the relations
2189
     * @return Doctrine_Record
2190
     */
2191
    public function copy($deep = false)
2192
    {
2193
        $data = $this->_data;
2194
        $idtype = $this->_table->getIdentifierType();
2195
        if ($idtype === Doctrine_Core::IDENTIFIER_AUTOINC || $idtype === Doctrine_Core::IDENTIFIER_SEQUENCE) {
2196
            $id = $this->_table->getIdentifier();
2197
 
2198
            unset($data[$id]);
2199
        }
2200
 
2201
        $ret = $this->_table->create($data);
2202
        $modified = array();
2203
 
2204
        foreach ($data as $key => $val) {
2205
            if ( ! ($val instanceof Doctrine_Null)) {
2206
                $ret->_modified[] = $key;
2207
            }
2208
        }
2209
 
2210
        if ($deep) {
2211
            foreach ($this->_references as $key => $value) {
2212
                if ($value instanceof Doctrine_Collection) {
2213
                    foreach ($value as $valueKey => $record) {
2214
                        $ret->{$key}[$valueKey] = $record->copy($deep);
2215
                    }
2216
                } else if ($value instanceof Doctrine_Record) {
2217
                    $ret->set($key, $value->copy($deep));
2218
                }
2219
            }
2220
        }
2221
 
2222
        return $ret;
2223
    }
2224
 
2225
    /**
2226
     * assigns an identifier to the instance, for database storage
2227
     *
2228
     * @param mixed $id     a key value or an array of keys
2229
     * @return void
2230
     */
2231
    public function assignIdentifier($id = false)
2232
    {
2233
        if ($id === false) {
2234
            $this->_id       = array();
2235
            $this->_data     = $this->cleanData($this->_data);
2236
            $this->_state    = Doctrine_Record::STATE_TCLEAN;
2237
            $this->_resetModified();
2238
        } elseif ($id === true) {
2239
            $this->prepareIdentifiers(true);
2240
            $this->_state    = Doctrine_Record::STATE_CLEAN;
2241
            $this->_resetModified();
2242
        } else {
2243
            if (is_array($id)) {
2244
                foreach ($id as $fieldName => $value) {
2245
                    $this->_id[$fieldName] = $value;
2246
                    $this->_data[$fieldName] = $value;
2247
                }
2248
            } else {
2249
                $name = $this->_table->getIdentifier();
2250
                $this->_id[$name] = $id;
2251
                $this->_data[$name] = $id;
2252
            }
2253
            $this->_state = Doctrine_Record::STATE_CLEAN;
2254
            $this->_resetModified();
2255
        }
2256
    }
2257
 
2258
    /**
2259
     * returns the primary keys of this object
2260
     *
2261
     * @return array
2262
     */
2263
    public function identifier()
2264
    {
2265
        return $this->_id;
2266
    }
2267
 
2268
    /**
2269
     * returns the value of autoincremented primary key of this object (if any)
2270
     *
2271
     * @return integer
2272
     * @todo Better name?
2273
     */
2274
    final public function getIncremented()
2275
    {
2276
        $id = current($this->_id);
2277
        if ($id === false) {
2278
            return null;
2279
        }
2280
 
2281
        return $id;
2282
    }
2283
 
2284
    /**
2285
     * getLast
2286
     * this method is used internally by Doctrine_Query
2287
     * it is needed to provide compatibility between
2288
     * records and collections
2289
     *
2290
     * @return Doctrine_Record
2291
     */
2292
    public function getLast()
2293
    {
2294
        return $this;
2295
    }
2296
 
2297
    /**
2298
     * tests whether a relation is set
2299
     * @param string $name  relation alias
2300
     * @return boolean
2301
     */
2302
    public function hasReference($name)
2303
    {
2304
        return isset($this->_references[$name]);
2305
    }
2306
 
2307
    /**
2308
     * gets a related component
2309
     *
2310
     * @param string $name
2311
     * @return Doctrine_Record|Doctrine_Collection
2312
     */
2313
    public function reference($name)
2314
    {
2315
        if (isset($this->_references[$name])) {
2316
            return $this->_references[$name];
2317
        }
2318
    }
2319
 
2320
    /**
2321
     * gets a related component and fails if it does not exist
2322
     *
2323
     * @param string $name
2324
     * @throws Doctrine_Record_Exception        if trying to get an unknown related component
2325
     */
2326
    public function obtainReference($name)
2327
    {
2328
        if (isset($this->_references[$name])) {
2329
            return $this->_references[$name];
2330
        }
2331
        throw new Doctrine_Record_Exception("Unknown reference $name");
2332
    }
2333
 
2334
    /**
2335
     * get all related components
2336
     * @return array    various Doctrine_Collection or Doctrine_Record instances
2337
     */
2338
    public function getReferences()
2339
    {
2340
        return $this->_references;
2341
    }
2342
 
2343
    /**
2344
     * set a related component
2345
     *
2346
     * @param string $alias
2347
     * @param Doctrine_Access $coll
2348
     */
2349
    final public function setRelated($alias, Doctrine_Access $coll)
2350
    {
2351
        $this->_references[$alias] = $coll;
2352
    }
2353
 
2354
    /**
2355
     * loadReference
2356
     * loads a related component
2357
     *
2358
     * @throws Doctrine_Table_Exception             if trying to load an unknown related component
2359
     * @param string $name                          alias of the relation
2360
     * @return void
2361
     */
2362
    public function loadReference($name)
2363
    {
2364
        $rel = $this->_table->getRelation($name);
2365
        $this->_references[$name] = $rel->fetchRelatedFor($this);
2366
    }
2367
 
2368
    /**
2369
     * call
2370
     *
2371
     * @param string|array $callback    valid callback
2372
     * @param string $column            column name
2373
     * @param mixed arg1 ... argN       optional callback arguments
2374
     * @return Doctrine_Record provides a fluent interface
2375
     */
2376
    public function call($callback, $column)
2377
    {
2378
        $args = func_get_args();
2379
        array_shift($args);
2380
 
2381
        if (isset($args[0])) {
2382
            $fieldName = $args[0];
2383
            $args[0] = $this->get($fieldName);
2384
 
2385
            $newvalue = call_user_func_array($callback, $args);
2386
 
2387
            $this->_data[$fieldName] = $newvalue;
2388
        }
2389
        return $this;
2390
    }
2391
 
2392
    /**
2393
     * getter for node associated with this record
2394
     *
2395
     * @return Doctrine_Node    false if component is not a Tree
2396
     */
2397
    public function getNode()
2398
    {
2399
        if ( ! $this->_table->isTree()) {
2400
            return false;
2401
        }
2402
 
2403
        if ( ! isset($this->_node)) {
2404
            $this->_node = Doctrine_Node::factory($this,
2405
                                              $this->getTable()->getOption('treeImpl'),
2406
                                              $this->getTable()->getOption('treeOptions')
2407
                                              );
2408
        }
2409
 
2410
        return $this->_node;
2411
    }
2412
 
2413
    public function unshiftFilter(Doctrine_Record_Filter $filter)
2414
    {
2415
        return $this->_table->unshiftFilter($filter);
2416
    }
2417
 
2418
    /**
2419
     * unlink
2420
     * removes links from this record to given records
2421
     * if no ids are given, it removes all links
2422
     *
2423
     * @param string $alias     related component alias
2424
     * @param array $ids        the identifiers of the related records
2425
     * @param boolean $now      whether or not to execute now or set as pending unlinks
2426
     * @return Doctrine_Record  this object (fluent interface)
2427
     */
2428
    public function unlink($alias, $ids = array(), $now = false)
2429
    {
2430
        $ids = (array) $ids;
2431
 
2432
        // fix for #1622
2433
        if ( ! isset($this->_references[$alias]) && $this->hasRelation($alias)) {
2434
            $this->loadReference($alias);
2435
        }
2436
 
2437
        $allIds = array();
2438
        if (isset($this->_references[$alias])) {
2439
            if ($this->_references[$alias] instanceof Doctrine_Record) {
2440
                $allIds[] = $this->_references[$alias]->identifier();
2441
                if (in_array($this->_references[$alias]->identifier(), $ids) || empty($ids)) {
2442
                    unset($this->_references[$alias]);
2443
                }
2444
            } else {
2445
                $allIds = $this->get($alias)->getPrimaryKeys();
2446
                foreach ($this->_references[$alias] as $k => $record) {
2447
                    if (in_array(current($record->identifier()), $ids) || empty($ids)) {
2448
                        $this->_references[$alias]->remove($k);
2449
                    }
2450
                }
2451
            }
2452
        }
2453
 
2454
        if ( ! $this->exists() || $now === false) {
2455
            if ( ! $ids) {
2456
                $ids = $allIds;
2457
            }
2458
            foreach ($ids as $id) {
2459
                $this->_pendingUnlinks[$alias][$id] = true;
2460
            }
2461
            return $this;
2462
        } else {
2463
            return $this->unlinkInDb($alias, $ids);
2464
        }
2465
    }
2466
 
2467
    /**
2468
     * unlink now the related components, querying the db
2469
     * @param string $alias     related component alias
2470
     * @param array $ids        the identifiers of the related records
2471
     * @return Doctrine_Record  this object (fluent interface)
2472
     */
2473
    public function unlinkInDb($alias, $ids = array())
2474
    {
2475
        $rel = $this->getTable()->getRelation($alias);
2476
 
2477
        if ($rel instanceof Doctrine_Relation_Association) {
2478
            $q = $rel->getAssociationTable()
2479
                ->createQuery()
2480
                ->delete()
2481
                ->where($rel->getLocal() . ' = ?', array_values($this->identifier()));
2482
 
2483
            if (count($ids) > 0) {
2484
                $q->whereIn($rel->getForeign(), $ids);
2485
            }
2486
 
2487
            $q->execute();
2488
        } else if ($rel instanceof Doctrine_Relation_ForeignKey) {
2489
            $q = $rel->getTable()->createQuery()
2490
                ->update()
2491
                ->set($rel->getForeign(), '?', array(null))
2492
                ->addWhere($rel->getForeign() . ' = ?', array_values($this->identifier()));
2493
 
2494
            if (count($ids) > 0) {
2495
                $q->whereIn($rel->getTable()->getIdentifier(), $ids);
2496
            }
2497
 
2498
            $q->execute();
2499
        }
2500
        return $this;
2501
    }
2502
 
2503
    /**
2504
     * creates links from this record to given records
2505
     *
2506
     * @param string $alias     related component alias
2507
     * @param array $ids        the identifiers of the related records
2508
     * @param boolean $now      wether or not to execute now or set pending
2509
     * @return Doctrine_Record  this object (fluent interface)
2510
     */
2511
    public function link($alias, $ids, $now = false)
2512
    {
2513
        $ids = (array) $ids;
2514
 
2515
        if ( ! count($ids)) {
2516
            return $this;
2517
        }
2518
 
2519
        if ( ! $this->exists() || $now === false) {
2520
            $relTable = $this->getTable()->getRelation($alias)->getTable();
2521
            $records = $relTable->createQuery()
2522
                ->whereIn($relTable->getIdentifier(), $ids)
2523
                ->execute();
2524
 
2525
            foreach ($records as $record) {
2526
                if ($this->$alias instanceof Doctrine_Record) {
2527
                    $this->set($alias, $record);
2528
                } else {
2529
                    if ($c = $this->get($alias)) {
2530
                        $c->add($record);
2531
                    } else {
2532
                        $this->set($alias, $record);
2533
                    }
2534
                }
2535
            }
2536
 
2537
            foreach ($ids as $id) {
2538
                if (isset($this->_pendingUnlinks[$alias][$id])) {
2539
                    unset($this->_pendingUnlinks[$alias][$id]);
2540
                }
2541
            }
2542
 
2543
            return $this;
2544
        } else {
2545
            return $this->linkInDb($alias, $ids);
2546
        }
2547
    }
2548
 
2549
    /**
2550
     * creates links from this record to given records now, querying the db
2551
     *
2552
     * @param string $alias     related component alias
2553
     * @param array $ids        the identifiers of the related records
2554
     * @return Doctrine_Record  this object (fluent interface)
2555
     */
2556
    public function linkInDb($alias, $ids)
2557
    {
2558
        $identifier = array_values($this->identifier());
2559
        $identifier = array_shift($identifier);
2560
 
2561
        $rel = $this->getTable()->getRelation($alias);
2562
 
2563
        if ($rel instanceof Doctrine_Relation_Association) {
2564
            $modelClassName = $rel->getAssociationTable()->getComponentName();
2565
            $localFieldName = $rel->getLocalFieldName();
2566
            $localFieldDef  = $rel->getAssociationTable()->getColumnDefinition($localFieldName);
2567
 
2568
            if ($localFieldDef['type'] == 'integer') {
2569
                $identifier = (integer) $identifier;
2570
            }
2571
 
2572
            $foreignFieldName = $rel->getForeignFieldName();
2573
            $foreignFieldDef  = $rel->getAssociationTable()->getColumnDefinition($foreignFieldName);
2574
 
2575
            if ($foreignFieldDef['type'] == 'integer') {
2576
                foreach ($ids as $i => $id) {
2577
                    $ids[$i] = (integer) $id;
2578
                }
2579
            }
2580
 
2581
            foreach ($ids as $id) {
2582
                $record = new $modelClassName;
2583
                $record[$localFieldName] = $identifier;
2584
                $record[$foreignFieldName] = $id;
2585
                $record->save();
2586
            }
2587
        } else if ($rel instanceof Doctrine_Relation_ForeignKey) {
2588
            $q = $rel->getTable()
2589
                ->createQuery()
2590
                ->update()
2591
                ->set($rel->getForeign(), '?', array_values($this->identifier()));
2592
 
2593
            if (count($ids) > 0) {
2594
                $q->whereIn($rel->getTable()->getIdentifier(), $ids);
2595
            }
2596
 
2597
            $q->execute();
2598
        } else if ($rel instanceof Doctrine_Relation_LocalKey) {
2599
            $q = $this->getTable()
2600
                ->createQuery()
2601
                ->update()
2602
                ->set($rel->getLocalFieldName(), '?', $ids);
2603
 
2604
            if (count($ids) > 0) {
2605
                $q->whereIn($rel->getTable()->getIdentifier(), array_values($this->identifier()));
2606
            }
2607
 
2608
            $q->execute();
2609
        }
2610
 
2611
        return $this;
2612
    }
2613
 
2614
    /**
2615
     * Reset the modified array and store the old array in lastModified so it
2616
     * can be accessed by users after saving a record, since the modified array
2617
     * is reset after the object is saved.
2618
     *
2619
     * @return void
2620
     */
2621
    protected function _resetModified()
2622
    {
2623
        if ( ! empty($this->_modified)) {
2624
            $this->_lastModified = $this->_modified;
2625
            $this->_modified = array();
2626
        }
2627
    }
2628
 
2629
    /**
2630
     * magic method used for method overloading
2631
     *
2632
     * the function of this method is to try to find a given method from the templates (behaviors)
2633
     * the record is using, and if found, execute it. Note that already existing methods would not be
2634
     * overloaded.
2635
     *
2636
     * So, in sense, this method replicates the usage of mixins (as seen in some programming languages)
2637
     *
2638
     * @param string $method        name of the method
2639
     * @param array $args           method arguments
2640
     * @return mixed                the return value of the given method
2641
     */
2642
    public function __call($method, $args)
2643
    {
2644
        if (($template = $this->_table->getMethodOwner($method)) !== false) {
2645
            $template->setInvoker($this);
2646
            return call_user_func_array(array($template, $method), $args);
2647
        }
2648
 
2649
        foreach ($this->_table->getTemplates() as $template) {
2650
            if (is_callable(array($template, $method))) {
2651
                $template->setInvoker($this);
2652
                $this->_table->setMethodOwner($method, $template);
2653
 
2654
                return call_user_func_array(array($template, $method), $args);
2655
            }
2656
        }
2657
 
2658
        throw new Doctrine_Record_UnknownPropertyException(sprintf('Unknown method %s::%s', get_class($this), $method));
2659
    }
2660
 
2661
    /**
2662
     * used to delete node from tree - MUST BE USE TO DELETE RECORD IF TABLE ACTS AS TREE
2663
     *
2664
     */
2665
    public function deleteNode()
2666
    {
2667
        $this->getNode()->delete();
2668
    }
2669
 
2670
    /**
2671
     * Helps freeing the memory occupied by the entity.
2672
     * Cuts all references the entity has to other entities and removes the entity
2673
     * from the instance pool.
2674
     * Note: The entity is no longer useable after free() has been called. Any operations
2675
     * done with the entity afterwards can lead to unpredictable results.
2676
     * @param boolean $deep     whether to free also the related components
2677
     */
2678
    public function free($deep = false)
2679
    {
2680
        if ($this->_state != self::STATE_LOCKED && $this->_state != self::STATE_TLOCKED) {
2681
            $this->_state = $this->exists() ? self::STATE_LOCKED : self::STATE_TLOCKED;
2682
 
2683
            $this->_table->getRepository()->evict($this->_oid);
2684
            $this->_table->removeRecord($this);
2685
            $this->_data = array();
2686
            $this->_id = array();
2687
 
2688
            if ($deep) {
2689
                foreach ($this->_references as $name => $reference) {
2690
                    if ( ! ($reference instanceof Doctrine_Null)) {
2691
                        $reference->free($deep);
2692
                    }
2693
                }
2694
            }
2695
 
2696
            $this->_references = array();
2697
        }
2698
    }
2699
 
2700
    /**
2701
     * __toString alias
2702
     *
2703
     * @return string
2704
     */
2705
    public function toString()
2706
    {
2707
        return Doctrine_Core::dump(get_object_vars($this));
2708
    }
2709
 
2710
    /**
2711
     * magic method
2712
     * @return string representation of this object
2713
     */
2714
    public function __toString()
2715
    {
2716
        return (string) $this->_oid;
2717
    }
2718
}