Record.php 54.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
<?php
/*
 *  $Id$
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.phpdoctrine.com>.
 */
zYne's avatar
zYne committed
21
Doctrine::autoload('Doctrine_Record_Abstract');
22 23 24 25
/**
 * Doctrine_Record
 * All record classes should inherit this super class
 *
26 27
 * @package     Doctrine
 * @subpackage  Record
28 29 30 31 32 33
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link        www.phpdoctrine.com
 * @since       1.0
 * @version     $Revision$
 */
zYne's avatar
zYne committed
34
abstract class Doctrine_Record extends Doctrine_Record_Abstract implements Countable, IteratorAggregate, Serializable
35 36 37 38 39 40 41 42 43 44
{
    /**
     * STATE CONSTANTS
     */

    /**
     * DIRTY STATE
     * a Doctrine_Record is in dirty state when its properties are changed
     */
    const STATE_DIRTY       = 1;
45

46 47
    /**
     * TDIRTY STATE
48
     * a Doctrine_Record is in transient dirty state when it is created
zYne's avatar
zYne committed
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 55 56 57 58
    /**
     * CLEAN STATE
     * a Doctrine_Record is in clean state when all of its properties are loaded from the database
     * and none of its properties are changed
     */
    const STATE_CLEAN       = 3;
59

60 61 62 63 64
    /**
     * PROXY STATE
     * a Doctrine_Record is in proxy state when its properties are not fully loaded
     */
    const STATE_PROXY       = 4;
65

66 67 68 69 70
    /**
     * NEW TCLEAN
     * a Doctrine_Record is in transient clean state when it is created and none of its fields are modified
     */
    const STATE_TCLEAN      = 5;
71

72
    /**
73
     * LOCKED STATE
zYne's avatar
zYne committed
74 75 76 77
     * a Doctrine_Record is temporarily locked during deletes and saves
     *
     * This state is used internally to ensure that circular deletes
     * and saves will not cause infinite loops
78
     */
79
    const STATE_LOCKED     = 6;
zYne's avatar
zYne committed
80

81
    /**
zYne's avatar
zYne committed
82
     * @var Doctrine_Node_<TreeImpl>        node object
83 84
     */
    protected $_node;
85

86 87 88 89
    /**
     * @var integer $_id                    the primary keys of this object
     */
    protected $_id           = array();
90

91 92 93 94
    /**
     * @var array $_data                    the record data
     */
    protected $_data         = array();
95

96 97 98 99
    /**
     * @var array $_values                  the values array, aggregate values and such are mapped into this array
     */
    protected $_values       = array();
100

101 102 103 104 105
    /**
     * @var integer $_state                 the state of this record
     * @see STATE_* constants
     */
    protected $_state;
106

107
    /**
108
     * @var array $_modified                an array containing field names that have been modified
romanb's avatar
romanb committed
109
     * @todo Better name? $_modifiedFields?
110 111
     */
    protected $_modified     = array();
112

113 114 115 116
    /**
     * @var Doctrine_Validator_ErrorStack   error stack object
     */
    protected $_errorStack;
117

118
    /**
zYne's avatar
zYne committed
119
     * @var array $_references              an array containing all the references
120
     */
zYne's avatar
zYne committed
121
    protected $_references     = array();
122

123 124 125
    /**
     * @var integer $index                  this index is used for creating object identifiers
     */
zYne's avatar
zYne committed
126
    private static $_index = 1;
127

128 129 130
    /**
     * @var integer $oid                    object identifier, each Record object has a unique object identifier
     */
zYne's avatar
zYne committed
131
    private $_oid;
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149

    /**
     * constructor
     * @param Doctrine_Table|null $table       a Doctrine_Table object or null,
     *                                         if null the table object is retrieved from current connection
     *
     * @param boolean $isNewEntry              whether or not this record is transient
     *
     * @throws Doctrine_Connection_Exception   if object is created using the new operator and there are no
     *                                         open connections
     * @throws Doctrine_Record_Exception       if the cleanData operation fails somehow
     */
    public function __construct($table = null, $isNewEntry = false)
    {
        if (isset($table) && $table instanceof Doctrine_Table) {
            $this->_table = $table;
            $exists = ( ! $isNewEntry);
        } else {
romanb's avatar
romanb committed
150
            $class = get_class($this);
151
            // get the table of this class
romanb's avatar
romanb committed
152
            $this->_table = Doctrine_Manager::getInstance()->getTable($class);
153 154
            $exists = false;
        }
155

156 157 158
        // Check if the current connection has the records table in its registry
        // If not this record is only used for creating table definition and setting up
        // relations.
159 160 161
        if ( ! $this->_table->getConnection()->hasTable($this->_table->getComponentName())) {
            return;
        }
162

163
        $this->_oid = self::$_index;
164

165
        self::$_index++;
166

167 168
        // get the data array
        $this->_data = $this->_table->getData();
zYne's avatar
zYne committed
169

170 171
        // get the column count
        $count = count($this->_data);
172

173
        $this->_values = $this->cleanData($this->_data);
174

175
        $this->prepareIdentifiers($exists);
176

177 178 179
        if ( ! $exists) {
            if ($count > count($this->_values)) {
                $this->_state = Doctrine_Record::STATE_TDIRTY;
180
            } else {
181
                $this->_state = Doctrine_Record::STATE_TCLEAN;
182 183
            }

184 185 186
            // set the default values for this record
            $this->assignDefaultValues();
        } else {
romanb's avatar
romanb committed
187
            $this->_state = Doctrine_Record::STATE_CLEAN;
188

189 190 191
            if ($count < $this->_table->getColumnCount()) {
                $this->_state  = Doctrine_Record::STATE_PROXY;
            }
192
        }
193 194 195 196 197

        $this->_errorStack = new Doctrine_Validator_ErrorStack(get_class($this));

        $repository = $this->_table->getRepository();
        $repository->add($this);
198

199
        $this->construct();
200

201
    }
202

zYne's avatar
zYne committed
203 204 205 206 207 208 209 210 211
    /**
     * _index
     *
     * @return integer
     */
    public static function _index()
    {
        return self::$_index;
    }
212

213 214 215 216 217 218 219 220 221 222 223
    /**
     * setUp
     * this method is used for setting up relations and attributes
     * it should be implemented by child classes
     *
     * @return void
     */
    public function setUp()
    { }
    /**
     * construct
224
     * Empty template method to provide concrete Record classes with the possibility
225 226 227 228 229 230 231
     * to hook into the constructor procedure
     *
     * @return void
     */
    public function construct()
    { }
    /**
zYne's avatar
zYne committed
232
     * getOid
233 234 235 236
     * returns the object identifier
     *
     * @return integer
     */
zYne's avatar
zYne committed
237
    public function getOid()
238
    {
zYne's avatar
zYne committed
239
        return $this->_oid;
240
    }
zYne's avatar
zYne committed
241 242 243 244
    public function oid()
    {
        return $this->_oid;
    }
245

246 247 248
    /**
     * isValid
     *
romanb's avatar
romanb committed
249
     * @return boolean  whether or not this record is valid
250 251 252
     */
    public function isValid()
    {
253
        if ( ! $this->_table->getAttribute(Doctrine::ATTR_VALIDATE)) {
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
            return true;
        }
        // Clear the stack from any previous errors.
        $this->_errorStack->clear();

        // Run validation process
        $validator = new Doctrine_Validator();
        $validator->validateRecord($this);
        $this->validate();
        if ($this->_state == self::STATE_TDIRTY || $this->_state == self::STATE_TCLEAN) {
            $this->validateOnInsert();
        } else {
            $this->validateOnUpdate();
        }

        return $this->_errorStack->count() == 0 ? true : false;
    }
271

272
    /**
273
     * Empty template method to provide concrete Record classes with the possibility
274 275 276 277
     * to hook into the validation procedure, doing any custom / specialized
     * validations that are neccessary.
     */
    protected function validate()
zYne's avatar
zYne committed
278
    { }
279
    /**
zYne's avatar
zYne committed
280
     * Empty template method to provide concrete Record classes with the possibility
281 282 283 284
     * to hook into the validation procedure only when the record is going to be
     * updated.
     */
    protected function validateOnUpdate()
zYne's avatar
zYne committed
285
    { }
286
    /**
zYne's avatar
zYne committed
287
     * Empty template method to provide concrete Record classes with the possibility
288 289 290 291
     * to hook into the validation procedure only when the record is going to be
     * inserted into the data store the first time.
     */
    protected function validateOnInsert()
zYne's avatar
zYne committed
292
    { }
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
    /**
     * Empty template method to provide concrete Record classes with the possibility
     * to hook into the serializing procedure.
     */
    public function preSerialize($event)
    { }
    /**
     * Empty template method to provide concrete Record classes with the possibility
     * to hook into the serializing procedure.
     */
    public function postSerialize($event)
    { }
    /**
     * Empty template method to provide concrete Record classes with the possibility
     * to hook into the serializing procedure.
     */
    public function preUnserialize($event)
    { }
    /**
     * Empty template method to provide concrete Record classes with the possibility
     * to hook into the serializing procedure.
     */
    public function postUnserialize($event)
    { }
zYne's avatar
zYne committed
317 318 319 320
    /**
     * Empty template method to provide concrete Record classes with the possibility
     * to hook into the saving procedure.
     */
zYne's avatar
zYne committed
321
    public function preSave($event)
zYne's avatar
zYne committed
322 323 324 325 326
    { }
    /**
     * Empty template method to provide concrete Record classes with the possibility
     * to hook into the saving procedure.
     */
zYne's avatar
zYne committed
327
    public function postSave($event)
zYne's avatar
zYne committed
328 329 330 331 332
    { }
    /**
     * Empty template method to provide concrete Record classes with the possibility
     * to hook into the deletion procedure.
     */
zYne's avatar
zYne committed
333
    public function preDelete($event)
zYne's avatar
zYne committed
334 335 336 337 338
    { }
    /**
     * Empty template method to provide concrete Record classes with the possibility
     * to hook into the deletion procedure.
     */
zYne's avatar
zYne committed
339
    public function postDelete($event)
zYne's avatar
zYne committed
340 341 342 343 344 345
    { }
    /**
     * Empty template method to provide concrete Record classes with the possibility
     * to hook into the saving procedure only when the record is going to be
     * updated.
     */
zYne's avatar
zYne committed
346
    public function preUpdate($event)
zYne's avatar
zYne committed
347 348 349 350 351 352
    { }
    /**
     * Empty template method to provide concrete Record classes with the possibility
     * to hook into the saving procedure only when the record is going to be
     * updated.
     */
zYne's avatar
zYne committed
353
    public function postUpdate($event)
zYne's avatar
zYne committed
354 355 356 357 358 359
    { }
    /**
     * Empty template method to provide concrete Record classes with the possibility
     * to hook into the saving procedure only when the record is going to be
     * inserted into the data store the first time.
     */
zYne's avatar
zYne committed
360
    public function preInsert($event)
zYne's avatar
zYne committed
361 362 363 364 365 366
    { }
    /**
     * Empty template method to provide concrete Record classes with the possibility
     * to hook into the saving procedure only when the record is going to be
     * inserted into the data store the first time.
     */
zYne's avatar
zYne committed
367
    public function postInsert($event)
zYne's avatar
zYne committed
368
    { }
369 370 371 372 373 374 375 376 377
    /**
     * getErrorStack
     *
     * @return Doctrine_Validator_ErrorStack    returns the errorStack associated with this record
     */
    public function getErrorStack()
    {
        return $this->_errorStack;
    }
378

zYne's avatar
zYne committed
379 380 381 382 383 384 385 386 387
    /**
     * errorStack
     * assigns / returns record errorStack
     *
     * @param Doctrine_Validator_ErrorStack          errorStack to be assigned for this record
     * @return void|Doctrine_Validator_ErrorStack    returns the errorStack associated with this record
     */
    public function errorStack($stack = null)
    {
388 389
        if ($stack !== null) {
            if ( ! ($stack instanceof Doctrine_Validator_ErrorStack)) {
390 391
               throw new Doctrine_Record_Exception('Argument should be an instance of Doctrine_Validator_ErrorStack.');
            }
zYne's avatar
zYne committed
392
            $this->_errorStack = $stack;
393
        } else {
zYne's avatar
zYne committed
394 395 396
            return $this->_errorStack;
        }
    }
397

398 399 400 401 402 403 404
    /**
     * setDefaultValues
     * sets the default values for records internal data
     *
     * @param boolean $overwrite                whether or not to overwrite the already set values
     * @return boolean
     */
zYne's avatar
zYne committed
405
    public function assignDefaultValues($overwrite = false)
406 407 408 409 410 411 412
    {
        if ( ! $this->_table->hasDefaultValues()) {
            return false;
        }
        foreach ($this->_data as $column => $value) {
            $default = $this->_table->getDefaultValueOf($column);

zYne's avatar
zYne committed
413
            if ($default === null) {
414
                continue;
zYne's avatar
zYne committed
415
            }
416

zYne's avatar
zYne committed
417
            if ($value === self::$_null || $overwrite) {
418 419 420 421 422 423
                $this->_data[$column] = $default;
                $this->_modified[]    = $column;
                $this->_state = Doctrine_Record::STATE_TDIRTY;
            }
        }
    }
424

zYne's avatar
zYne committed
425 426
    /**
     * cleanData
427 428
     * leaves the $data array only with values whose key is a field inside this
     * record and returns the values that where removed from $data.
zYne's avatar
zYne committed
429 430
     *
     * @param array $data       data array to be cleaned
431
     * @return array $tmp       values cleaned from data
zYne's avatar
zYne committed
432 433 434
     */
    public function cleanData(&$data)
    {
435
        $tmp = $data;
zYne's avatar
zYne committed
436 437
        $data = array();

438
        foreach ($this->getTable()->getFieldNames() as $fieldName) {
jackbravo's avatar
jackbravo committed
439
            if (isset($tmp[$fieldName])) {
440
                $data[$fieldName] = $tmp[$fieldName];
jackbravo's avatar
jackbravo committed
441 442
            } else if (!isset($this->_data[$fieldName])) {
                $data[$fieldName] = self::$_null;
zYne's avatar
zYne committed
443
            }
444
            unset($tmp[$fieldName]);
zYne's avatar
zYne committed
445
        }
zYne's avatar
zYne committed
446

zYne's avatar
zYne committed
447 448
        return $tmp;
    }
449

zYne's avatar
zYne committed
450 451 452 453 454 455 456 457 458
    /**
     * hydrate
     * hydrates this object from given array
     *
     * @param array $data
     * @return boolean
     */
    public function hydrate(array $data)
    {
459
        $this->_values = array_merge($this->_values, $this->cleanData($data));
zYne's avatar
zYne committed
460
        $this->_data   = array_merge($this->_data, $data);
461
        $this->prepareIdentifiers(true);
zYne's avatar
zYne committed
462
    }
463

464 465 466 467 468 469 470 471 472 473
    /**
     * prepareIdentifiers
     * prepares identifiers for later use
     *
     * @param boolean $exists               whether or not this record exists in persistent data store
     * @return void
     */
    private function prepareIdentifiers($exists = true)
    {
        switch ($this->_table->getIdentifierType()) {
zYne's avatar
zYne committed
474 475
            case Doctrine::IDENTIFIER_AUTOINC:
            case Doctrine::IDENTIFIER_SEQUENCE:
zYne's avatar
zYne committed
476
            case Doctrine::IDENTIFIER_NATURAL:
477
                $name = $this->_table->getIdentifier();
478 479 480
                if (is_array($name)) {
                    $name = $name[0];
                }
481
                if ($exists) {
zYne's avatar
zYne committed
482
                    if (isset($this->_data[$name]) && $this->_data[$name] !== self::$_null) {
483 484 485 486
                        $this->_id[$name] = $this->_data[$name];
                    }
                }
                break;
zYne's avatar
zYne committed
487
            case Doctrine::IDENTIFIER_COMPOSITE:
zYne's avatar
zYne committed
488
                $names = $this->_table->getIdentifier();
489 490

                foreach ($names as $name) {
zYne's avatar
zYne committed
491
                    if ($this->_data[$name] === self::$_null) {
492 493 494 495 496 497
                        $this->_id[$name] = null;
                    } else {
                        $this->_id[$name] = $this->_data[$name];
                    }
                }
                break;
zYne's avatar
zYne committed
498
        }
499
    }
500

501 502 503 504 505 506 507 508
    /**
     * serialize
     * this method is automatically called when this Doctrine_Record is serialized
     *
     * @return array
     */
    public function serialize()
    {
509
        $event = new Doctrine_Event($this, Doctrine_Event::RECORD_SERIALIZE);
510 511

        $this->preSerialize($event);
512 513 514

        $vars = get_object_vars($this);

zYne's avatar
zYne committed
515
        unset($vars['_references']);
516
        unset($vars['_table']);
zYne's avatar
zYne committed
517
        unset($vars['_errorStack']);
zYne's avatar
zYne committed
518 519
        unset($vars['_filter']);
        unset($vars['_node']);
520 521 522 523 524

        $name = $this->_table->getIdentifier();
        $this->_data = array_merge($this->_data, $this->_id);

        foreach ($this->_data as $k => $v) {
525
            if ($v instanceof Doctrine_Record && $this->_table->getTypeOf($k) != 'object') {
526
                unset($vars['_data'][$k]);
zYne's avatar
zYne committed
527
            } elseif ($v === self::$_null) {
528 529 530
                unset($vars['_data'][$k]);
            } else {
                switch ($this->_table->getTypeOf($k)) {
531 532
                    case 'array':
                    case 'object':
533 534
                        $vars['_data'][$k] = serialize($vars['_data'][$k]);
                        break;
535 536 537 538 539 540
                    case 'gzip':
                        $vars['_data'][$k] = gzcompress($vars['_data'][$k]);
                        break;
                    case 'enum':
                        $vars['_data'][$k] = $this->_table->enumIndex($k, $vars['_data'][$k]);
                        break;
zYne's avatar
zYne committed
541
                }
542 543 544
            }
        }

545
        $str = serialize($vars);
546

547 548 549
        $this->postSerialize($event);

        return $str;
550
    }
551

552 553 554 555 556 557 558 559 560 561
    /**
     * unseralize
     * this method is automatically called everytime a Doctrine_Record object is unserialized
     *
     * @param string $serialized                Doctrine_Record as serialized string
     * @throws Doctrine_Record_Exception        if the cleanData operation fails somehow
     * @return void
     */
    public function unserialize($serialized)
    {
562
        $event = new Doctrine_Event($this, Doctrine_Event::RECORD_UNSERIALIZE);
zYne's avatar
zYne committed
563

564
        $this->preUnserialize($event);
zYne's avatar
zYne committed
565

566
        $manager    = Doctrine_Manager::getInstance();
zYne's avatar
zYne committed
567
        $connection = $manager->getConnectionForComponent(get_class($this));
568

zYne's avatar
zYne committed
569 570
        $this->_oid = self::$_index;
        self::$_index++;
571 572 573 574 575

        $this->_table = $connection->getTable(get_class($this));

        $array = unserialize($serialized);

zYne's avatar
zYne committed
576 577
        foreach($array as $k => $v) {
            $this->$k = $v;
578
        }
zYne's avatar
zYne committed
579

580 581 582 583 584 585 586 587 588 589 590 591 592
        foreach ($this->_data as $k => $v) {

            switch ($this->_table->getTypeOf($k)) {
                case 'array':
                case 'object':
                    $this->_data[$k] = unserialize($this->_data[$k]);
                    break;
                case 'gzip':
                   $this->_data[$k] = gzuncompress($this->_data[$k]);
                    break;
                case 'enum':
                    $this->_data[$k] = $this->_table->enumValue($k, $this->_data[$k]);
                    break;
593

594 595
            }
        }
596

597 598
        $this->_table->getRepository()->add($this);

zYne's avatar
zYne committed
599
        $this->cleanData($this->_data);
600 601

        $this->prepareIdentifiers($this->exists());
602

zYne's avatar
zYne committed
603
        $this->postUnserialize($event);
604
    }
605

606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
    /**
     * state
     * returns / assigns the state of this record
     *
     * @param integer|string $state                 if set, this method tries to set the record state to $state
     * @see Doctrine_Record::STATE_* constants
     *
     * @throws Doctrine_Record_State_Exception      if trying to set an unknown state
     * @return null|integer
     */
    public function state($state = null)
    {
        if ($state == null) {
            return $this->_state;
        }
        $err = false;
        if (is_integer($state)) {
            if ($state >= 1 && $state <= 6) {
                $this->_state = $state;
            } else {
                $err = true;
            }
628
        } else if (is_string($state)) {
629
            $upper = strtoupper($state);
630

zYne's avatar
zYne committed
631 632
            $const = 'Doctrine_Record::STATE_' . $upper;
            if (defined($const)) {
633
                $this->_state = constant($const);
zYne's avatar
zYne committed
634 635
            } else {
                $err = true;
636 637 638
            }
        }

zYne's avatar
zYne committed
639
        if ($this->_state === Doctrine_Record::STATE_TCLEAN ||
romanb's avatar
romanb committed
640
                $this->_state === Doctrine_Record::STATE_CLEAN) {
zYne's avatar
zYne committed
641 642 643 644
            $this->_modified = array();
        }

        if ($err) {
645
            throw new Doctrine_Record_State_Exception('Unknown record state ' . $state);
zYne's avatar
zYne committed
646
        }
647
    }
648

649 650 651 652
    /**
     * refresh
     * refresh internal data from the database
     *
653
     * @param bool $deep                        If true, fetch also current relations. Caution: this deletes
654
     *                                          any aggregated values you may have queried beforee
655
     *
656 657 658 659
     * @throws Doctrine_Record_Exception        When the refresh operation fails (when the database row
     *                                          this record represents does not exist anymore)
     * @return boolean
     */
660
    public function refresh($deep = false)
661
    {
662
        $id = $this->identifier();
663 664 665 666 667 668 669 670
        if ( ! is_array($id)) {
            $id = array($id);
        }
        if (empty($id)) {
            return false;
        }
        $id = array_values($id);

671 672 673 674 675 676 677 678 679 680 681 682 683 684
        if ($deep) {
            $query = $this->getTable()->createQuery();
            foreach (array_keys($this->_references) as $name) {
                $query->leftJoin(get_class($this) . '.' . $name);
            }
            $query->where(implode(' = ? AND ', $this->getTable()->getIdentifierColumnNames()) . ' = ?');
            $record = $query->fetchOne($id);
        } else {
            // Use FETCH_ARRAY to avoid clearing object relations
            $record = $this->getTable()->find($id, Doctrine::HYDRATE_ARRAY);
            if ($record) {
                $this->hydrate($record);
            }
        }
685

686
        if ($record === false) {
687
            throw new Doctrine_Record_Exception('Failed to refresh. Record does not exist.');
zYne's avatar
zYne committed
688
        }
zYne's avatar
zYne committed
689

690 691 692 693
        $this->_modified = array();

        $this->prepareIdentifiers();

694
        $this->_state = Doctrine_Record::STATE_CLEAN;
695

zYne's avatar
zYne committed
696
        return $this;
697
    }
698

699 700 701 702
    /**
     * refresh
     * refres data of related objects from the database
     *
zYne's avatar
zYne committed
703 704 705 706
     * @param string $name              name of a related component.
     *                                  if set, this method only refreshes the specified related component
     *
     * @return Doctrine_Record          this object
707 708 709 710 711
     */
    public function refreshRelated($name = null)
    {
        if (is_null($name)) {
            foreach ($this->_table->getRelations() as $rel) {
712
                $this->_references[$rel->getAlias()] = $rel->fetchRelatedFor($this);
713 714 715 716 717 718
            }
        } else {
            $rel = $this->_table->getRelation($name);
            $this->_references[$name] = $rel->fetchRelatedFor($this);
        }
    }
719 720 721 722 723 724 725 726 727 728 729

    /**
     * clearRelated
     * unsets all the relationships this object has
     *
     * (references to related objects still remain on Table objects)
     */
    public function clearRelated()
    {
        $this->_references = array();
    }
730

731 732 733 734
    /**
     * getTable
     * returns the table object for this record
     *
Jonathan.Wage's avatar
Jonathan.Wage committed
735
     * @return Doctrine_Table        a Doctrine_Table object
736
     */
zYne's avatar
zYne committed
737
    public function getTable()
738 739 740
    {
        return $this->_table;
    }
741

742 743 744 745 746 747
    /**
     * getData
     * return all the internal data
     *
     * @return array                        an array containing all the properties
     */
zYne's avatar
zYne committed
748
    public function getData()
749 750 751
    {
        return $this->_data;
    }
752

753 754 755 756 757 758 759 760 761
    /**
     * rawGet
     * returns the value of a property, if the property is not yet loaded
     * this method does NOT load it
     *
     * @param $name                         name of the property
     * @throws Doctrine_Record_Exception    if trying to get an unknown property
     * @return mixed
     */
762
    public function rawGet($fieldName)
763
    {
764 765
        if ( ! isset($this->_data[$fieldName])) {
            throw new Doctrine_Record_Exception('Unknown property '. $fieldName);
766
        }
767
        if ($this->_data[$fieldName] === self::$_null) {
768
            return null;
769
        }
770

771
        return $this->_data[$fieldName];
772 773 774 775
    }

    /**
     * load
romanb's avatar
romanb committed
776
     * loads all the uninitialized properties from the database
777 778 779 780 781 782 783 784 785 786 787 788 789
     *
     * @return boolean
     */
    public function load()
    {
        // only load the data from database if the Doctrine_Record is in proxy state
        if ($this->_state == Doctrine_Record::STATE_PROXY) {
            $this->refresh();
            $this->_state = Doctrine_Record::STATE_CLEAN;
            return true;
        }
        return false;
    }
790

791 792 793 794 795
    /**
     * get
     * returns a value of a property or a related component
     *
     * @param mixed $name                       name of the property or related component
zYne's avatar
zYne committed
796
     * @param boolean $load                     whether or not to invoke the loading procedure
797 798 799
     * @throws Doctrine_Record_Exception        if trying to get a value of unknown property / related component
     * @return mixed
     */
800
    public function get($fieldName, $load = true)
801
    {
zYne's avatar
zYne committed
802
        $value = self::$_null;
zYne's avatar
zYne committed
803

804
        if (isset($this->_data[$fieldName])) {
romanb's avatar
romanb committed
805
            // check if the value is the Doctrine_Null object located in self::$_null)
806
            if ($this->_data[$fieldName] === self::$_null && $load) {
807 808 809
                $this->load();
            }

810
            if ($this->_data[$fieldName] === self::$_null) {
811 812
                $value = null;
            } else {
813
                $value = $this->_data[$fieldName];
814
            }
815
            return $value;
816 817
        }

818 819
        if (isset($this->_values[$fieldName])) {
            return $this->_values[$fieldName];
820 821 822
        }

        try {
823
            if ( ! isset($this->_references[$fieldName]) && $load) {
824

825
                $rel = $this->_table->getRelation($fieldName);
826

827
                $this->_references[$fieldName] = $rel->fetchRelatedFor($this);
828
            }
829
            return $this->_references[$fieldName];
830

831
        } catch (Doctrine_Table_Exception $e) {
zYne's avatar
zYne committed
832
            foreach ($this->_table->getFilters() as $filter) {
833
                if (($value = $filter->filterGet($this, $fieldName, $value)) !== null) {
zYne's avatar
zYne committed
834 835 836
                    return $value;
                }
            }
837 838
        }
    }
839

840 841 842 843 844 845 846 847 848 849 850 851 852 853
    /**
     * mapValue
     * This simple method is used for mapping values to $values property.
     * Usually this method is used internally by Doctrine for the mapping of
     * aggregate values.
     *
     * @param string $name                  the name of the mapped value
     * @param mixed $value                  mixed value to be mapped
     * @return void
     */
    public function mapValue($name, $value)
    {
        $this->_values[$name] = $value;
    }
854

855 856 857 858 859 860 861 862 863 864 865 866 867 868
    /**
     * set
     * method for altering properties and Doctrine_Record references
     * if the load parameter is set to false this method will not try to load uninitialized record data
     *
     * @param mixed $name                   name of the property or reference
     * @param mixed $value                  value of the property or reference
     * @param boolean $load                 whether or not to refresh / load the uninitialized record data
     *
     * @throws Doctrine_Record_Exception    if trying to set a value for unknown property / related component
     * @throws Doctrine_Record_Exception    if trying to set a value of wrong type for related component
     *
     * @return Doctrine_Record
     */
869
    public function set($fieldName, $value, $load = true)
870
    {
871
        if (isset($this->_data[$fieldName])) {
zYne's avatar
zYne committed
872
            if ($value instanceof Doctrine_Record) {
873
                $type = $this->_table->getTypeOf($fieldName);
zYne's avatar
zYne committed
874

875 876
                $id = $value->getIncremented();

zYne's avatar
zYne committed
877
                if ($id !== null && $type !== 'object') {
878
                    $value = $id;
zYne's avatar
zYne committed
879
                }
880 881 882
            }

            if ($load) {
883
                $old = $this->get($fieldName, $load);
884
            } else {
885
                $old = $this->_data[$fieldName];
886 887 888
            }

            if ($old !== $value) {
889
                if ($value === null) {
zYne's avatar
zYne committed
890
                    $value = self::$_null;
891
                }
zYne's avatar
zYne committed
892

893 894
                $this->_data[$fieldName] = $value;
                $this->_modified[] = $fieldName;
895 896 897 898 899 900 901
                switch ($this->_state) {
                    case Doctrine_Record::STATE_CLEAN:
                        $this->_state = Doctrine_Record::STATE_DIRTY;
                        break;
                    case Doctrine_Record::STATE_TCLEAN:
                        $this->_state = Doctrine_Record::STATE_TDIRTY;
                        break;
zYne's avatar
zYne committed
902
                }
903 904 905
            }
        } else {
            try {
906 907
                $this->coreSetRelated($fieldName, $value);
            } catch (Doctrine_Table_Exception $e) {
zYne's avatar
zYne committed
908
                foreach ($this->_table->getFilters() as $filter) {
909
                    if (($value = $filter->filterSet($this, $fieldName, $value)) !== null) {
zYne's avatar
zYne committed
910 911 912
                        return $value;
                    }
                }
913 914 915
            }
        }
    }
916

917 918 919 920
    /**
     * DESCRIBE WHAT THIS METHOD DOES, PLEASE!
     * @todo Refactor. What about composite keys?
     */
921 922 923 924 925 926
    public function coreSetRelated($name, $value)
    {
        $rel = $this->_table->getRelation($name);

        // one-to-many or one-to-one relation
        if ($rel instanceof Doctrine_Relation_ForeignKey ||
zYne's avatar
zYne committed
927
            $rel instanceof Doctrine_Relation_LocalKey) {
928 929 930 931 932
            if ( ! $rel->isOneToOne()) {
                // one-to-many relation found
                if ( ! ($value instanceof Doctrine_Collection)) {
                    throw new Doctrine_Record_Exception("Couldn't call Doctrine::set(), second argument should be an instance of Doctrine_Collection when setting one-to-many references.");
                }
zYne's avatar
zYne committed
933 934 935 936
                if (isset($this->_references[$name])) {
                    $this->_references[$name]->setData($value->getData());
                    return $this;
                }
937
            } else {
938
                if ($value !== self::$_null) {
939 940 941
                    $relatedTable = $value->getTable();
                    $foreignFieldName = $relatedTable->getFieldName($rel->getForeign());
                    $localFieldName = $this->_table->getFieldName($rel->getLocal());
942

943 944 945 946 947
                    // one-to-one relation found
                    if ( ! ($value instanceof Doctrine_Record)) {
                        throw new Doctrine_Record_Exception("Couldn't call Doctrine::set(), second argument should be an instance of Doctrine_Record or Doctrine_Null when setting one-to-one references.");
                    }
                    if ($rel instanceof Doctrine_Relation_LocalKey) {
948 949 950 951 952
                        if ( ! empty($foreignFieldName) && $foreignFieldName != $value->getTable()->getIdentifier()) {
                            $this->set($localFieldName, $value->rawGet($foreignFieldName), false);
                        } else {
                            $this->set($localFieldName, $value, false);
                        }
953
                    } else {
954 955
                        $value->set($foreignFieldName, $this, false);
                    }
956 957 958
                }
            }

959
        } else if ($rel instanceof Doctrine_Relation_Association) {
960 961 962 963 964 965
            // join table relation found
            if ( ! ($value instanceof Doctrine_Collection)) {
                throw new Doctrine_Record_Exception("Couldn't call Doctrine::set(), second argument should be an instance of Doctrine_Collection when setting many-to-many references.");
            }
        }

zYne's avatar
zYne committed
966
        $this->_references[$name] = $value;
967
    }
968

969 970 971 972 973 974
    /**
     * contains
     *
     * @param string $name
     * @return boolean
     */
975
    public function contains($fieldName)
976
    {
977
        if (isset($this->_data[$fieldName])) {
978 979
            return true;
        }
980
        if (isset($this->_id[$fieldName])) {
981 982
            return true;
        }
983
        if (isset($this->_values[$fieldName])) {
984
            return true;
zYne's avatar
zYne committed
985
        }
986
        if (isset($this->_references[$fieldName]) &&
987
            $this->_references[$fieldName] !== self::$_null) {
988

989 990 991 992
            return true;
        }
        return false;
    }
993

994 995 996 997
    /**
     * @param string $name
     * @return void
     */
998
    public function __unset($fieldName)
999
    {
1000 1001
        if (isset($this->_data[$fieldName])) {
            $this->_data[$fieldName] = array();
1002
        } else if (isset($this->_references[$fieldName])) {
1003 1004 1005 1006 1007 1008 1009
            if ($this->_references[$fieldName] instanceof Doctrine_Record) {
                // todo: delete related record when saving $this
                $this->_references[$fieldName] = self::$_null;
            } elseif ($this->_references[$fieldName] instanceof Doctrine_Collection) {
                $this->_references[$fieldName]->setData(array());
            }
        }
1010
    }
1011

1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
    /**
     * applies the changes made to this object into database
     * this method is smart enough to know if any changes are made
     * and whether to use INSERT or UPDATE statement
     *
     * this method also saves the related components
     *
     * @param Doctrine_Connection $conn                 optional connection parameter
     * @return void
     */
    public function save(Doctrine_Connection $conn = null)
    {
        if ($conn === null) {
            $conn = $this->_table->getConnection();
        }
zYne's avatar
zYne committed
1027
        $conn->unitOfWork->saveGraph($this);
1028
    }
1029

1030 1031 1032 1033 1034
    /**
     * Tries to save the object and all its related components.
     * In contrast to Doctrine_Record::save(), this method does not
     * throw an exception when validation fails but returns TRUE on
     * success or FALSE on failure.
1035
     *
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
     * @param Doctrine_Connection $conn                 optional connection parameter
     * @return TRUE if the record was saved sucessfully without errors, FALSE otherwise.
     */
    public function trySave(Doctrine_Connection $conn = null) {
        try {
            $this->save($conn);
            return true;
        } catch (Doctrine_Validator_Exception $ignored) {
            return false;
        }
    }
1047

1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
    /**
     * replace
     * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
     * query, except that if there is already a row in the table with the same
     * key field values, the REPLACE query just updates its values instead of
     * inserting a new row.
     *
     * The REPLACE type of query does not make part of the SQL standards. Since
     * practically only MySQL and SQLIte implement it natively, this type of
     * query isemulated through this method for other DBMS using standard types
     * of queries inside a transaction to assure the atomicity of the operation.
     *
     * @param Doctrine_Connection $conn             optional connection parameter
     * @throws Doctrine_Connection_Exception        if some of the key values was null
     * @throws Doctrine_Connection_Exception        if there were no key fields
zYne's avatar
zYne committed
1063
     * @throws Doctrine_Connection_Exception        if something fails at database level
1064 1065 1066 1067 1068 1069 1070 1071
     * @return integer                              number of rows affected
     */
    public function replace(Doctrine_Connection $conn = null)
    {
        if ($conn === null) {
            $conn = $this->_table->getConnection();
        }

1072
        return $conn->replace($this->_table, $this->getPrepared(), $this->_id);
1073
    }
1074

1075 1076 1077
    /**
     * returns an array of modified fields and associated values
     * @return array
1078
     * @todo What about a better name? getModifiedFields?
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
     */
    public function getModified()
    {
        $a = array();

        foreach ($this->_modified as $k => $v) {
            $a[$v] = $this->_data[$v];
        }
        return $a;
    }
1089

1090 1091 1092
    /**
     * REDUNDANT?
     */
zYne's avatar
zYne committed
1093 1094 1095 1096 1097 1098 1099 1100 1101
    public function modifiedFields()
    {
        $a = array();

        foreach ($this->_modified as $k => $v) {
            $a[$v] = $this->_data[$v];
        }
        return $a;
    }
1102

1103 1104 1105 1106 1107 1108 1109 1110
    /**
     * getPrepared
     *
     * returns an array of modified fields and values with data preparation
     * adds column aggregation inheritance and converts Records into primary key values
     *
     * @param array $array
     * @return array
1111
     * @todo What about a little bit more expressive name? getPreparedData?
1112
     */
1113
    public function getPrepared(array $array = array())
zYne's avatar
zYne committed
1114
    {
1115 1116 1117
        $a = array();

        if (empty($array)) {
1118
            $modifiedFields = $this->_modified;
1119
        }
zYne's avatar
zYne committed
1120

1121 1122
        foreach ($modifiedFields as $field) {
            $type = $this->_table->getTypeOf($field);
1123

1124 1125
            if ($this->_data[$field] === self::$_null) {
                $a[$field] = null;
1126 1127 1128 1129 1130 1131
                continue;
            }

            switch ($type) {
                case 'array':
                case 'object':
1132
                    $a[$field] = serialize($this->_data[$field]);
1133 1134
                    break;
                case 'gzip':
1135
                    $a[$field] = gzcompress($this->_data[$field],5);
1136 1137
                    break;
                case 'boolean':
1138
                    $a[$field] = $this->getTable()->getConnection()->convertBooleans($this->_data[$field]);
1139 1140
                break;
                case 'enum':
1141
                    $a[$field] = $this->_table->enumIndex($field, $this->_data[$field]);
1142 1143
                    break;
                default:
1144 1145
                    if ($this->_data[$field] instanceof Doctrine_Record) {
                        $this->_data[$field] = $this->_data[$field]->getIncremented();
zYne's avatar
zYne committed
1146
                    }
zYne's avatar
zYne committed
1147
                    /** TODO:
zYne's avatar
zYne committed
1148 1149 1150
                    if ($this->_data[$v] === null) {
                        throw new Doctrine_Record_Exception('Unexpected null value.');
                    }
zYne's avatar
zYne committed
1151
                    */
1152

1153
                    $a[$field] = $this->_data[$field];
1154 1155
            }
        }
zYne's avatar
zYne committed
1156 1157
        $map = $this->_table->inheritanceMap;
        foreach ($map as $k => $v) {
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
            $old = $this->get($k, false);

            if ((string) $old !== (string) $v || $old === null) {
                $a[$k] = $v;
                $this->_data[$k] = $v;
            }
        }

        return $a;
    }
1168

1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
    /**
     * count
     * this class implements countable interface
     *
     * @return integer          the number of columns in this record
     */
    public function count()
    {
        return count($this->_data);
    }
1179

1180 1181 1182 1183 1184 1185 1186 1187 1188
    /**
     * alias for count()
     *
     * @return integer          the number of columns in this record
     */
    public function columnCount()
    {
        return $this->count();
    }
1189

1190 1191 1192 1193
    /**
     * toArray
     * returns the record as an array
     *
1194
     * @param boolean $deep - Return also the relations
1195 1196
     * @return array
     */
1197
    public function toArray($deep = true, $prefixKey = false)
1198 1199 1200 1201
    {
        $a = array();

        foreach ($this as $column => $value) {
1202
            if ($value === self::$_null || is_object($value)) {
zYne's avatar
zYne committed
1203 1204
                $value = null;
            }
1205 1206
            $a[$column] = $value;
        }
1207

1208
        if ($this->_table->getIdentifierType() ==  Doctrine::IDENTIFIER_AUTOINC) {
1209 1210 1211
            $i      = $this->_table->getIdentifier();
            $a[$i]  = $this->getIncremented();
        }
1212

1213 1214
        if ($deep) {
            foreach ($this->_references as $key => $relation) {
1215
                if ( ! $relation instanceof Doctrine_Null) {
1216 1217
                    $a[$key] = $relation->toArray($deep, $prefixKey);
                }
1218 1219
            }
        }
1220

zYne's avatar
zYne committed
1221
        return array_merge($a, $this->_values);
1222
    }
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252

    /**
     * merge
     *
     * merges this record with an array of values
     * or with another existing instance of this object
     *
     * @param  mixed $data Data to merge. Either another instance of this model or an array
     * @param  bool  $deep Bool value for whether or not to merge the data deep
     * @return void
     */
    public function merge($data, $deep = true)
    {
        if ($data instanceof $this) {
            $array = $data->toArray($deep);
        } else if (is_array($data)) {
            $array = $data;
        }

        return $this->fromArray($array, $deep);
    }

    /**
     * fromArray
     *
     * @param   string $array
     * @param   bool  $deep Bool value for whether or not to merge the data deep
     * @return  void
     */
    public function fromArray($array, $deep = true)
1253
    {
1254 1255
        if (is_array($array)) {
            foreach ($array as $key => $value) {
1256 1257
                if ($this->getTable()->hasRelation($key) && $deep) {
                    $this->$key->fromArray($value, $deep);
romanb's avatar
romanb committed
1258
                } else if ($this->getTable()->hasField($key)) {
1259
                    $this->set($key, $value);
1260
                }
1261
            }
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
        }
    }

    /**
     * synchronizeWithArray
     * synchronizes a Doctrine_Record and its relations with data from an array
     *
     * it expects an array representation of a Doctrine_Record similar to the return
     * value of the toArray() method. If the array contains relations it will create
     * those that don't exist, update the ones that do, and delete the ones missing
     * on the array but available on the Doctrine_Record
     *
     * @param array $array representation of a Doctrine_Record
     */
    public function synchronizeWithArray(array $array)
    {
        foreach ($array as $key => $value) {
            if ($this->getTable()->hasRelation($key)) {
                $this->get($key)->synchronizeWithArray($value);
jackbravo's avatar
jackbravo committed
1281
            } else if ($this->getTable()->hasField($key)) {
1282 1283 1284 1285 1286 1287 1288 1289
                $this->set($key, $value);
            }
        }
        // eliminate relationships missing in the $array
        foreach ($this->_references as $name => $obj) {
            if (!isset($array[$name])) {
                unset($this->$name);
            }
1290 1291
        }
    }
1292 1293 1294 1295

    /**
     * exportTo
     *
1296 1297
     * @param string $type
     * @param string $deep
1298 1299 1300
     * @return void
     */
    public function exportTo($type, $deep = true)
1301 1302 1303 1304 1305 1306 1307
    {
        if ($type == 'array') {
            return $this->toArray($deep);
        } else {
            return Doctrine_Parser::dump($this->toArray($deep, true), $type);
        }
    }
1308 1309 1310 1311

    /**
     * importFrom
     *
1312 1313
     * @param string $type
     * @param string $data
1314 1315 1316
     * @return void
     * @author Jonathan H. Wage
     */
1317 1318 1319 1320 1321 1322 1323 1324
    public function importFrom($type, $data)
    {
        if ($type == 'array') {
            return $this->fromArray($data);
        } else {
            return $this->fromArray(Doctrine_Parser::load($data, $type));
        }
    }
1325

1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
    /**
     * exists
     * returns true if this record is persistent, otherwise false
     *
     * @return boolean
     */
    public function exists()
    {
        return ($this->_state !== Doctrine_Record::STATE_TCLEAN &&
                $this->_state !== Doctrine_Record::STATE_TDIRTY);
    }
1337

1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
    /**
     * isModified
     * returns true if this record was modified, otherwise false
     *
     * @return boolean
     */
    public function isModified()
    {
        return ($this->_state === Doctrine_Record::STATE_DIRTY ||
                $this->_state === Doctrine_Record::STATE_TDIRTY);
    }
1349

1350 1351 1352 1353 1354
    /**
     * method for checking existence of properties and Doctrine_Record references
     * @param mixed $name               name of the property or reference
     * @return boolean
     */
1355
    public function hasRelation($fieldName)
1356
    {
1357
        if (isset($this->_data[$fieldName]) || isset($this->_id[$fieldName])) {
1358 1359
            return true;
        }
1360
        return $this->_table->hasRelation($fieldName);
1361
    }
1362

1363 1364 1365 1366 1367 1368 1369 1370
    /**
     * getIterator
     * @return Doctrine_Record_Iterator     a Doctrine_Record_Iterator that iterates through the data
     */
    public function getIterator()
    {
        return new Doctrine_Record_Iterator($this);
    }
1371

1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
    /**
     * deletes this data access object and all the related composites
     * this operation is isolated by a transaction
     *
     * this event can be listened by the onPreDelete and onDelete listeners
     *
     * @return boolean      true on success, false on failure
     */
    public function delete(Doctrine_Connection $conn = null)
    {
        if ($conn == null) {
            $conn = $this->_table->getConnection();
        }
zYne's avatar
zYne committed
1385
        return $conn->unitOfWork->delete($this);
1386
    }
1387

1388 1389 1390 1391 1392 1393
    /**
     * copy
     * returns a copy of this object
     *
     * @return Doctrine_Record
     */
1394
    public function copy($deep = true)
1395
    {
1396
        $data = $this->_data;
zYne's avatar
zYne committed
1397 1398 1399 1400 1401 1402 1403 1404

        if ($this->_table->getIdentifierType() === Doctrine::IDENTIFIER_AUTOINC) {
            $id = $this->_table->getIdentifier();

            unset($data[$id]);
        }

        $ret = $this->_table->create($data);
1405
        $modified = array();
zYne's avatar
zYne committed
1406 1407

        foreach ($data as $key => $val) {
zYne's avatar
zYne committed
1408
            if ( ! ($val instanceof Doctrine_Null)) {
1409 1410
                $ret->_modified[] = $key;
            }
1411
        }
zYne's avatar
zYne committed
1412

1413 1414 1415 1416 1417 1418 1419 1420
        if ($deep) {
            foreach ($this->_references as $key => $value) {
                if ($value instanceof Doctrine_Collection) {
                    foreach ($value as $record) {
                        $rt->{$key}[] = $record->copy($deep);
                    }
                } else {
                    $rt->set($key, $value->copy($deep));
runa's avatar
runa committed
1421 1422 1423
                }
            }
        }
1424 1425

        return $ret;
runa's avatar
runa committed
1426
    }
1427

1428 1429 1430 1431 1432 1433
    /**
     * assignIdentifier
     *
     * @param integer $id
     * @return void
     */
zYne's avatar
zYne committed
1434
    public function assignIdentifier($id = false)
1435 1436 1437
    {
        if ($id === false) {
            $this->_id       = array();
zYne's avatar
zYne committed
1438
            $this->_data     = $this->cleanData($this->_data);
1439 1440 1441
            $this->_state    = Doctrine_Record::STATE_TCLEAN;
            $this->_modified = array();
        } elseif ($id === true) {
zYne's avatar
zYne committed
1442
            $this->prepareIdentifiers(true);
1443 1444 1445
            $this->_state    = Doctrine_Record::STATE_CLEAN;
            $this->_modified = array();
        } else {
1446
            $name = $this->_table->getIdentifier();
1447
            $this->_id[$name] = $id;
zYne's avatar
zYne committed
1448
            $this->_data[$name] = $id;
1449 1450 1451 1452
            $this->_state     = Doctrine_Record::STATE_CLEAN;
            $this->_modified  = array();
        }
    }
1453

1454 1455 1456 1457 1458
    /**
     * returns the primary keys of this object
     *
     * @return array
     */
1459
    public function identifier()
1460 1461 1462
    {
        return $this->_id;
    }
1463

1464 1465 1466 1467
    /**
     * returns the value of autoincremented primary key of this object (if any)
     *
     * @return integer
1468
     * @todo Better name?
1469 1470 1471 1472
     */
    final public function getIncremented()
    {
        $id = current($this->_id);
zYne's avatar
zYne committed
1473
        if ($id === false) {
1474
            return null;
zYne's avatar
zYne committed
1475
        }
1476 1477 1478

        return $id;
    }
1479

1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
    /**
     * getLast
     * this method is used internally be Doctrine_Query
     * it is needed to provide compatibility between
     * records and collections
     *
     * @return Doctrine_Record
     */
    public function getLast()
    {
        return $this;
    }
1492

1493 1494 1495 1496 1497 1498 1499
    /**
     * hasRefence
     * @param string $name
     * @return boolean
     */
    public function hasReference($name)
    {
zYne's avatar
zYne committed
1500
        return isset($this->_references[$name]);
1501
    }
1502

zYne's avatar
zYne committed
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
    /**
     * reference
     *
     * @param string $name
     */
    public function reference($name)
    {
        if (isset($this->_references[$name])) {
            return $this->_references[$name];
        }
    }
1514

1515 1516 1517 1518 1519 1520 1521 1522
    /**
     * obtainReference
     *
     * @param string $name
     * @throws Doctrine_Record_Exception        if trying to get an unknown related component
     */
    public function obtainReference($name)
    {
zYne's avatar
zYne committed
1523 1524
        if (isset($this->_references[$name])) {
            return $this->_references[$name];
1525 1526 1527
        }
        throw new Doctrine_Record_Exception("Unknown reference $name");
    }
1528

1529 1530 1531 1532 1533 1534
    /**
     * getReferences
     * @return array    all references
     */
    public function getReferences()
    {
zYne's avatar
zYne committed
1535
        return $this->_references;
1536
    }
1537

1538 1539 1540 1541 1542 1543 1544 1545
    /**
     * setRelated
     *
     * @param string $alias
     * @param Doctrine_Access $coll
     */
    final public function setRelated($alias, Doctrine_Access $coll)
    {
zYne's avatar
zYne committed
1546
        $this->_references[$alias] = $coll;
1547
    }
1548

1549 1550 1551 1552 1553 1554 1555 1556
    /**
     * loadReference
     * loads a related component
     *
     * @throws Doctrine_Table_Exception             if trying to load an unknown related component
     * @param string $name
     * @return void
     */
1557
    public function loadReference($name)
1558
    {
1559 1560
        $rel = $this->_table->getRelation($name);
        $this->_references[$name] = $rel->fetchRelatedFor($this);
1561
    }
zYne's avatar
zYne committed
1562

1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
    /**
     * call
     *
     * @param string|array $callback    valid callback
     * @param string $column            column name
     * @param mixed arg1 ... argN       optional callback arguments
     * @return Doctrine_Record
     */
    public function call($callback, $column)
    {
        $args = func_get_args();
        array_shift($args);

        if (isset($args[0])) {
1577 1578
            $fieldName = $args[0];
            $args[0] = $this->get($fieldName);
1579 1580 1581

            $newvalue = call_user_func_array($callback, $args);

1582
            $this->_data[$fieldName] = $newvalue;
1583 1584 1585
        }
        return $this;
    }
1586

1587 1588 1589 1590
    /**
     * getter for node assciated with this record
     *
     * @return mixed if tree returns Doctrine_Node otherwise returns false
1591 1592
     */
    public function getNode()
zYne's avatar
zYne committed
1593 1594 1595 1596
    {
        if ( ! $this->_table->isTree()) {
            return false;
        }
1597

zYne's avatar
zYne committed
1598 1599
        if ( ! isset($this->_node)) {
            $this->_node = Doctrine_Node::factory($this,
zYne's avatar
zYne committed
1600 1601 1602
                                              $this->getTable()->getOption('treeImpl'),
                                              $this->getTable()->getOption('treeOptions')
                                              );
zYne's avatar
zYne committed
1603
        }
1604

zYne's avatar
zYne committed
1605
        return $this->_node;
1606
    }
zYne's avatar
zYne committed
1607 1608 1609 1610 1611 1612 1613 1614 1615
    /**
     * revert
     * reverts this record to given version, this method only works if versioning plugin
     * is enabled
     *
     * @throws Doctrine_Record_Exception    if given version does not exist
     * @param integer $version      an integer > 1
     * @return Doctrine_Record      this object
     */
zYne's avatar
zYne committed
1616 1617
    public function revert($version)
    {
zYne's avatar
zYne committed
1618 1619 1620 1621
        $data = $this->_table
                ->getTemplate('Doctrine_Template_Versionable')
                ->getAuditLog()
                ->getVersion($this, $version);
zYne's avatar
zYne committed
1622

zYne's avatar
zYne committed
1623
        if ( ! isset($data[0])) {
zYne's avatar
zYne committed
1624
            throw new Doctrine_Record_Exception('Version ' . $version . ' does not exist!');
zYne's avatar
zYne committed
1625 1626
        }

zYne's avatar
zYne committed
1627
        $this->_data = $data[0];
zYne's avatar
zYne committed
1628 1629

        return $this;
zYne's avatar
zYne committed
1630
    }
zYne's avatar
zYne committed
1631 1632 1633 1634
    public function unshiftFilter(Doctrine_Record_Filter $filter)
    {
        return $this->_table->unshiftFilter($filter);
    }
zYne's avatar
zYne committed
1635
    /**
zYne's avatar
zYne committed
1636
     * unlink
zYne's avatar
zYne committed
1637
     * removes links from this record to given records
jackbravo's avatar
jackbravo committed
1638
     * if no ids are given, it removes all links
zYne's avatar
zYne committed
1639
     *
zYne's avatar
zYne committed
1640 1641 1642
     * @param string $alias     related component alias
     * @param array $ids        the identifiers of the related records
     * @return Doctrine_Record  this object
zYne's avatar
zYne committed
1643
     */
jackbravo's avatar
jackbravo committed
1644
    public function unlink($alias, $ids = array())
zYne's avatar
zYne committed
1645 1646
    {
        $ids = (array) $ids;
1647

zYne's avatar
zYne committed
1648 1649 1650 1651
        $q = new Doctrine_Query();

        $rel = $this->getTable()->getRelation($alias);

zYne's avatar
zYne committed
1652 1653 1654
        if ($rel instanceof Doctrine_Relation_Association) {
            $q->delete()
              ->from($rel->getAssociationTable()->getComponentName())
jackbravo's avatar
jackbravo committed
1655 1656 1657 1658 1659
              ->where($rel->getLocal() . ' = ?', array_values($this->identifier()));

            if (count($ids) > 0) {
                $q->whereIn($rel->getForeign(), $ids);
            }
zYne's avatar
zYne committed
1660 1661 1662

            $q->execute();

1663
        } else if ($rel instanceof Doctrine_Relation_ForeignKey) {
zYne's avatar
zYne committed
1664 1665
            $q->update($rel->getTable()->getComponentName())
              ->set($rel->getForeign(), '?', array(null))
jackbravo's avatar
jackbravo committed
1666 1667 1668 1669 1670
              ->addWhere($rel->getForeign() . ' = ?', array_values($this->identifier()));

            if (count($ids) > 0) {
                $q->whereIn($rel->getTable()->getIdentifier(), $ids);
            }
zYne's avatar
zYne committed
1671 1672 1673 1674 1675 1676 1677

            $q->execute();
        }
        if (isset($this->_references[$alias])) {
            foreach ($this->_references[$alias] as $k => $record) {
                if (in_array(current($record->identifier()), $ids)) {
                    $this->_references[$alias]->remove($k);
zYne's avatar
zYne committed
1678 1679
                }
            }
zYne's avatar
zYne committed
1680
            $this->_references[$alias]->takeSnapshot();
zYne's avatar
zYne committed
1681 1682 1683
        }
        return $this;
    }
1684

1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707

    /**
     * link
     * creates links from this record to given records
     *
     * @param string $alias     related component alias
     * @param array $ids        the identifiers of the related records
     * @return Doctrine_Record  this object
     */
    public function link($alias, array $ids)
    {
        if ( ! count($ids)) {
            return $this;
        }

        $identifier = array_values($this->identifier());
        $identifier = array_shift($identifier);

        $rel = $this->getTable()->getRelation($alias);

        if ($rel instanceof Doctrine_Relation_Association) {

            $modelClassName = $rel->getAssociationTable()->getComponentName();
1708
            $localFieldName = $rel->getLocalFieldName();
1709 1710 1711 1712
            $localFieldDef  = $rel->getAssociationTable()->getColumnDefinition($localFieldName);
            if ($localFieldDef['type'] == 'integer') {
                $identifier = (integer) $identifier;
            }
1713
            $foreignFieldName = $rel->getForeignFieldName();
1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744
            $foreignFieldDef  = $rel->getAssociationTable()->getColumnDefinition($foreignFieldName);
            if ($foreignFieldDef['type'] == 'integer') {
                for ($i = 0; $i < count($ids); $i++) {
                    $ids[$i] = (integer) $ids[$i];
                }
            }
            foreach ($ids as $id) {
                $record = new $modelClassName;
                $record[$localFieldName]   = $identifier;
                $record[$foreignFieldName] = $id;
                $record->save();
            }

        } else if ($rel instanceof Doctrine_Relation_ForeignKey) {

            $q = new Doctrine_Query();

            $q->update($rel->getTable()->getComponentName())
              ->set($rel->getForeign(), '?', array_values($this->identifier()));

            if (count($ids) > 0) {
                $q->whereIn($rel->getTable()->getIdentifier(), $ids);
            }

            $q->execute();

        } else if ($rel instanceof Doctrine_Relation_LocalKey) {

            $q = new Doctrine_Query();

            $q->update($this->getTable()->getComponentName())
1745
              ->set($rel->getLocalFieldName(), '?', $ids);
1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758

            if (count($ids) > 0) {
                $q->whereIn($rel->getTable()->getIdentifier(), array_values($this->identifier()));
            }

            $q->execute();

        }

        return $this;
    }


zYne's avatar
zYne committed
1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771
    /**
     * __call
     * this method is a magic method that is being used for method overloading
     *
     * the function of this method is to try to find given method from the templates
     * this record is using and if it finds given method it will execute it
     *
     * So, in sense, this method replicates the usage of mixins (as seen in some programming languages)
     *
     * @param string $method        name of the method
     * @param array $args           method arguments
     * @return mixed                the return value of the given method
     */
1772
    public function __call($method, $args)
1773
    {
zYne's avatar
zYne committed
1774
        if (($template = $this->_table->getMethodOwner($method)) !== false) {
1775
            $template->setInvoker($this);
zYne's avatar
zYne committed
1776
            return call_user_func_array(array($template, $method), $args);
1777
        }
1778

zYne's avatar
zYne committed
1779
        foreach ($this->_table->getTemplates() as $template) {
1780
            if (method_exists($template, $method)) {
zYne's avatar
zYne committed
1781
                $template->setInvoker($this);
zYne's avatar
zYne committed
1782
                $this->_table->setMethodOwner($method, $template);
1783

1784 1785 1786
                return call_user_func_array(array($template, $method), $args);
            }
        }
1787

1788 1789
        throw new Doctrine_Record_Exception('Unknown method ' . $method);
    }
1790

1791 1792 1793
    /**
     * used to delete node from tree - MUST BE USE TO DELETE RECORD IF TABLE ACTS AS TREE
     *
1794
     */
1795
    public function deleteNode() {
zYne's avatar
zYne committed
1796
        $this->getNode()->delete();
1797
    }
zYne's avatar
zYne committed
1798 1799 1800 1801
    public function toString()
    {
        return Doctrine::dump(get_object_vars($this));
    }
1802

1803 1804 1805 1806 1807
    /**
     * returns a string representation of this object
     */
    public function __toString()
    {
zYne's avatar
zYne committed
1808
        return (string) $this->_oid;
1809
    }
1810
}