Record.php 49.2 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 45 46
{
    /**
     * STATE CONSTANTS
     */

    /**
     * DIRTY STATE
     * a Doctrine_Record is in dirty state when its properties are changed
     */
    const STATE_DIRTY       = 1;
    /**
     * TDIRTY STATE
zYne's avatar
zYne committed
47 48
     * a Doctrine_Record is in transient dirty state when it is created 
     * and some of its fields are modified but it is NOT yet persisted into database
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
     */
    const STATE_TDIRTY      = 2;
    /**
     * CLEAN STATE
     * a Doctrine_Record is in clean state when all of its properties are loaded from the database
     * and none of its properties are changed
     */
    const STATE_CLEAN       = 3;
    /**
     * PROXY STATE
     * a Doctrine_Record is in proxy state when its properties are not fully loaded
     */
    const STATE_PROXY       = 4;
    /**
     * NEW TCLEAN
     * a Doctrine_Record is in transient clean state when it is created and none of its fields are modified
     */
    const STATE_TCLEAN      = 5;
    /**
68
     * LOCKED STATE
zYne's avatar
zYne committed
69 70 71 72
     * 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
73
     */
74
    const STATE_LOCKED     = 6;
zYne's avatar
zYne committed
75

76
    /**
zYne's avatar
zYne committed
77
     * @var Doctrine_Node_<TreeImpl>        node object
78 79
     */
    protected $_node;
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
    /**
     * @var integer $_id                    the primary keys of this object
     */
    protected $_id           = array();
    /**
     * @var array $_data                    the record data
     */
    protected $_data         = array();
    /**
     * @var array $_values                  the values array, aggregate values and such are mapped into this array
     */
    protected $_values       = array();
    /**
     * @var integer $_state                 the state of this record
     * @see STATE_* constants
     */
    protected $_state;
    /**
     * @var array $_modified                an array containing properties that have been modified
     */
    protected $_modified     = array();
    /**
     * @var Doctrine_Validator_ErrorStack   error stack object
     */
    protected $_errorStack;
    /**
zYne's avatar
zYne committed
106
     * @var array $_references              an array containing all the references
107
     */
zYne's avatar
zYne committed
108
    protected $_references     = array();
109 110 111
    /**
     * @var integer $index                  this index is used for creating object identifiers
     */
zYne's avatar
zYne committed
112
    private static $_index = 1;
113 114 115
    /**
     * @var integer $oid                    object identifier, each Record object has a unique object identifier
     */
zYne's avatar
zYne committed
116
    private $_oid;
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136

    /**
     * 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 {
            $class  = get_class($this);
            // get the table of this class
137
            $this->_table = Doctrine_Manager::getInstance()
138
                            ->getTable($class);
139 140
            $exists = false;
        }
141

142 143 144 145 146
        // Check if the current connection has the records table in its registry
        // If not this record is only used for creating table definition and setting up
        // relations.

        if ($this->_table->getConnection()->hasTable($this->_table->getComponentName())) {
zYne's avatar
zYne committed
147
            $this->_oid = self::$_index;
148

zYne's avatar
zYne committed
149
            self::$_index++;
150

zYne's avatar
zYne committed
151
            $keys = (array) $this->_table->getIdentifier();
152 153 154 155 156 157

            // get the data array
            $this->_data = $this->_table->getData();

            // get the column count
            $count = count($this->_data);
zYne's avatar
zYne committed
158 159

            $this->_values = $this->cleanData($this->_data);
160 161 162 163 164 165 166 167 168 169 170

            $this->prepareIdentifiers($exists);

            if ( ! $exists) {
                if ($count > 0) {
                    $this->_state = Doctrine_Record::STATE_TDIRTY;
                } else {
                    $this->_state = Doctrine_Record::STATE_TCLEAN;
                }

                // set the default values for this record
zYne's avatar
zYne committed
171
                $this->assignDefaultValues();
172 173 174 175 176 177 178 179
            } else {
                $this->_state      = Doctrine_Record::STATE_CLEAN;

                if ($count < $this->_table->getColumnCount()) {
                    $this->_state  = Doctrine_Record::STATE_PROXY;
                }
            }

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

            $repository = $this->_table->getRepository();
zYne's avatar
zYne committed
183 184
            $repository->add($this);
            
185
            $this->construct();
186
        }
187
        
188
    }
zYne's avatar
zYne committed
189 190 191 192 193 194 195 196 197
    /**
     * _index
     *
     * @return integer
     */
    public static function _index()
    {
        return self::$_index;
    }
198 199 200 201 202 203 204 205 206 207 208
    /**
     * setUp
     * this method is used for setting up relations and attributes
     * it should be implemented by child classes
     *
     * @return void
     */
    public function setUp()
    { }
    /**
     * construct
209
     * Empty template method to provide concrete Record classes with the possibility
210 211 212 213 214 215 216
     * to hook into the constructor procedure
     *
     * @return void
     */
    public function construct()
    { }
    /**
zYne's avatar
zYne committed
217
     * getOid
218 219 220 221
     * returns the object identifier
     *
     * @return integer
     */
zYne's avatar
zYne committed
222
    public function getOid()
223
    {
zYne's avatar
zYne committed
224
        return $this->_oid;
225 226 227 228 229 230 231 232
    }
    /**
     * isValid
     *
     * @return boolean                          whether or not this record passes all column validations
     */
    public function isValid()
    {
233
        if ( ! $this->_table->getAttribute(Doctrine::ATTR_VALIDATE)) {
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
            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;
    }
    /**
252
     * Empty template method to provide concrete Record classes with the possibility
253 254 255 256
     * to hook into the validation procedure, doing any custom / specialized
     * validations that are neccessary.
     */
    protected function validate()
zYne's avatar
zYne committed
257
    { }
258
    /**
zYne's avatar
zYne committed
259
     * Empty template method to provide concrete Record classes with the possibility
260 261 262 263
     * to hook into the validation procedure only when the record is going to be
     * updated.
     */
    protected function validateOnUpdate()
zYne's avatar
zYne committed
264
    { }
265
    /**
zYne's avatar
zYne committed
266
     * Empty template method to provide concrete Record classes with the possibility
267 268 269 270
     * 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
271
    { }
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
    /**
     * 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
296 297 298 299
    /**
     * Empty template method to provide concrete Record classes with the possibility
     * to hook into the saving procedure.
     */
zYne's avatar
zYne committed
300
    public function preSave($event)
zYne's avatar
zYne committed
301 302 303 304 305
    { }
    /**
     * Empty template method to provide concrete Record classes with the possibility
     * to hook into the saving procedure.
     */
zYne's avatar
zYne committed
306
    public function postSave($event)
zYne's avatar
zYne committed
307 308 309 310 311
    { }
    /**
     * Empty template method to provide concrete Record classes with the possibility
     * to hook into the deletion procedure.
     */
zYne's avatar
zYne committed
312
    public function preDelete($event)
zYne's avatar
zYne committed
313 314 315 316 317
    { }
    /**
     * Empty template method to provide concrete Record classes with the possibility
     * to hook into the deletion procedure.
     */
zYne's avatar
zYne committed
318
    public function postDelete($event)
zYne's avatar
zYne committed
319 320 321 322 323 324
    { }
    /**
     * 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
325
    public function preUpdate($event)
zYne's avatar
zYne committed
326 327 328 329 330 331
    { }
    /**
     * 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
332
    public function postUpdate($event)
zYne's avatar
zYne committed
333 334 335 336 337 338
    { }
    /**
     * 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
339
    public function preInsert($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
     * inserted into the data store the first time.
     */
zYne's avatar
zYne committed
346
    public function postInsert($event)
zYne's avatar
zYne committed
347
    { }
348 349 350 351 352 353 354 355 356
    /**
     * getErrorStack
     *
     * @return Doctrine_Validator_ErrorStack    returns the errorStack associated with this record
     */
    public function getErrorStack()
    {
        return $this->_errorStack;
    }
zYne's avatar
zYne committed
357 358 359 360 361 362 363 364 365
    /**
     * 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)
    {
366 367
        if ($stack !== null) {
            if ( ! ($stack instanceof Doctrine_Validator_ErrorStack)) {
368 369
               throw new Doctrine_Record_Exception('Argument should be an instance of Doctrine_Validator_ErrorStack.');
            }
zYne's avatar
zYne committed
370
            $this->_errorStack = $stack;
371
        } else {
zYne's avatar
zYne committed
372 373 374
            return $this->_errorStack;
        }
    }
375 376 377 378 379 380 381
    /**
     * 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
382
    public function assignDefaultValues($overwrite = false)
383 384 385 386 387 388 389
    {
        if ( ! $this->_table->hasDefaultValues()) {
            return false;
        }
        foreach ($this->_data as $column => $value) {
            $default = $this->_table->getDefaultValueOf($column);

zYne's avatar
zYne committed
390
            if ($default === null) {
zYne's avatar
zYne committed
391
                $default = self::$_null;
zYne's avatar
zYne committed
392
            }
393

zYne's avatar
zYne committed
394
            if ($value === self::$_null || $overwrite) {
395 396 397 398 399 400
                $this->_data[$column] = $default;
                $this->_modified[]    = $column;
                $this->_state = Doctrine_Record::STATE_TDIRTY;
            }
        }
    }
zYne's avatar
zYne committed
401 402 403 404 405 406 407 408
    /**
     * cleanData
     *
     * @param array $data       data array to be cleaned
     * @return integer
     */
    public function cleanData(&$data)
    {
409
        $tmp = $data;
zYne's avatar
zYne committed
410 411 412 413 414 415 416 417 418 419
        $data = array();

        foreach ($this->getTable()->getColumnNames() as $name) {
            if ( ! isset($tmp[$name])) {
                $data[$name] = self::$_null;
            } else {
                $data[$name] = $tmp[$name];
            }
            unset($tmp[$name]);
        }
zYne's avatar
zYne committed
420

zYne's avatar
zYne committed
421 422
        return $tmp;
    }
zYne's avatar
zYne committed
423 424 425 426 427 428 429 430 431
    /**
     * hydrate
     * hydrates this object from given array
     *
     * @param array $data
     * @return boolean
     */
    public function hydrate(array $data)
    {
zYne's avatar
zYne committed
432
        $this->_values = $this->cleanData($data);
zYne's avatar
zYne committed
433
        $this->_data   = array_merge($this->_data, $data);
zYne's avatar
zYne committed
434

435
        $this->prepareIdentifiers(true);
zYne's avatar
zYne committed
436
    }
437 438 439 440 441 442 443 444 445 446
    /**
     * 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
447 448
            case Doctrine::IDENTIFIER_AUTOINC:
            case Doctrine::IDENTIFIER_SEQUENCE:
zYne's avatar
zYne committed
449
            case Doctrine::IDENTIFIER_NATURAL:
450 451 452
                $name = $this->_table->getIdentifier();

                if ($exists) {
zYne's avatar
zYne committed
453
                    if (isset($this->_data[$name]) && $this->_data[$name] !== self::$_null) {
454 455 456 457
                        $this->_id[$name] = $this->_data[$name];
                    }
                }
                break;
zYne's avatar
zYne committed
458
            case Doctrine::IDENTIFIER_COMPOSITE:
zYne's avatar
zYne committed
459
                $names = $this->_table->getIdentifier();
460 461

                foreach ($names as $name) {
zYne's avatar
zYne committed
462
                    if ($this->_data[$name] === self::$_null) {
463 464 465 466 467 468
                        $this->_id[$name] = null;
                    } else {
                        $this->_id[$name] = $this->_data[$name];
                    }
                }
                break;
zYne's avatar
zYne committed
469
        }
470 471 472 473 474 475 476 477 478
    }
    /**
     * serialize
     * this method is automatically called when this Doctrine_Record is serialized
     *
     * @return array
     */
    public function serialize()
    {
479
        $event = new Doctrine_Event($this, Doctrine_Event::RECORD_SERIALIZE);
480 481

        $this->preSerialize($event);
482 483 484

        $vars = get_object_vars($this);

zYne's avatar
zYne committed
485
        unset($vars['_references']);
486
        unset($vars['_table']);
zYne's avatar
zYne committed
487
        unset($vars['_errorStack']);
zYne's avatar
zYne committed
488 489
        unset($vars['_filter']);
        unset($vars['_node']);
490 491 492 493 494

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

        foreach ($this->_data as $k => $v) {
495
            if ($v instanceof Doctrine_Record && $this->_table->getTypeOf($k) != 'object') {
496
                unset($vars['_data'][$k]);
zYne's avatar
zYne committed
497
            } elseif ($v === self::$_null) {
498 499 500
                unset($vars['_data'][$k]);
            } else {
                switch ($this->_table->getTypeOf($k)) {
501 502
                    case 'array':
                    case 'object':
503 504
                        $vars['_data'][$k] = serialize($vars['_data'][$k]);
                        break;
505 506 507 508 509 510
                    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
511
                }
512 513 514
            }
        }

515 516 517 518 519
        $str = serialize($vars);
        
        $this->postSerialize($event);

        return $str;
520 521 522 523 524 525 526 527 528 529 530
    }
    /**
     * 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)
    {
531
        $event = new Doctrine_Event($this, Doctrine_Event::RECORD_UNSERIALIZE);
zYne's avatar
zYne committed
532

533
        $this->preUnserialize($event);
zYne's avatar
zYne committed
534

535
        $manager    = Doctrine_Manager::getInstance();
zYne's avatar
zYne committed
536
        $connection = $manager->getConnectionForComponent(get_class($this));
537

zYne's avatar
zYne committed
538 539
        $this->_oid = self::$_index;
        self::$_index++;
540 541 542 543 544

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

        $array = unserialize($serialized);

zYne's avatar
zYne committed
545 546
        foreach($array as $k => $v) {
            $this->$k = $v;
547
        }
zYne's avatar
zYne committed
548

549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
        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;
                
            }
        }
        
566 567
        $this->_table->getRepository()->add($this);

zYne's avatar
zYne committed
568
        $this->cleanData($this->_data);
569 570

        $this->prepareIdentifiers($this->exists());
zYne's avatar
zYne committed
571 572
        
        $this->postUnserialize($event);
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
    }
    /**
     * 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;
            }
        } elseif (is_string($state)) {
            $upper = strtoupper($state);
zYne's avatar
zYne committed
598 599 600 601 602 603
            
            $const = 'Doctrine_Record::STATE_' . $upper;
            if (defined($const)) {
                $this->_state = constant($const);  
            } else {
                $err = true;
604 605 606
            }
        }

zYne's avatar
zYne committed
607 608
        if ($this->_state === Doctrine_Record::STATE_TCLEAN ||
            $this->_state === Doctrine_Record::STATE_CLEAN) {
zYne's avatar
zYne committed
609

zYne's avatar
zYne committed
610 611 612 613
            $this->_modified = array();
        }

        if ($err) {
614
            throw new Doctrine_Record_State_Exception('Unknown record state ' . $state);
zYne's avatar
zYne committed
615
        }
616 617 618 619 620 621 622 623 624
    }
    /**
     * refresh
     * refresh internal data from the database
     *
     * @throws Doctrine_Record_Exception        When the refresh operation fails (when the database row
     *                                          this record represents does not exist anymore)
     * @return boolean
     */
zYne's avatar
zYne committed
625
    public function refresh()
626
    {
627
        $id = $this->identifier();
628 629 630 631 632 633 634 635
        if ( ! is_array($id)) {
            $id = array($id);
        }
        if (empty($id)) {
            return false;
        }
        $id = array_values($id);

636 637
        // Use FETCH_ARRAY to avoid clearing object relations
        $record = $this->getTable()->find($id, Doctrine::FETCH_ARRAY);
638

639
        if ($record === false) {
640
            throw new Doctrine_Record_Exception('Failed to refresh. Record does not exist.');
zYne's avatar
zYne committed
641
        }
zYne's avatar
zYne committed
642

643 644
        $this->hydrate($record);

645 646 647 648 649 650
        $this->_modified = array();

        $this->prepareIdentifiers();

        $this->_state    = Doctrine_Record::STATE_CLEAN;

zYne's avatar
zYne committed
651
        return $this;
652
    }
653 654 655 656 657
    
    /**
     * refresh
     * refres data of related objects from the database
     *
zYne's avatar
zYne committed
658 659 660 661
     * @param string $name              name of a related component.
     *                                  if set, this method only refreshes the specified related component
     *
     * @return Doctrine_Record          this object
662 663 664 665 666
     */
    public function refreshRelated($name = null)
    {
        if (is_null($name)) {
            foreach ($this->_table->getRelations() as $rel) {
667
                $this->_references[$rel->getAlias()] = $rel->fetchRelatedFor($this);
668 669 670 671 672 673
            }
        } else {
            $rel = $this->_table->getRelation($name);
            $this->_references[$name] = $rel->fetchRelatedFor($this);
        }
    }
674 675 676 677 678 679 680 681 682 683 684

    /**
     * clearRelated
     * unsets all the relationships this object has
     *
     * (references to related objects still remain on Table objects)
     */
    public function clearRelated()
    {
        $this->_references = array();
    }
685
    
686 687 688 689 690 691
    /**
     * getTable
     * returns the table object for this record
     *
     * @return object Doctrine_Table        a Doctrine_Table object
     */
zYne's avatar
zYne committed
692
    public function getTable()
693 694 695 696 697 698 699 700 701
    {
        return $this->_table;
    }
    /**
     * getData
     * return all the internal data
     *
     * @return array                        an array containing all the properties
     */
zYne's avatar
zYne committed
702
    public function getData()
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
    {
        return $this->_data;
    }
    /**
     * 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
     */

    public function rawGet($name)
    {
        if ( ! isset($this->_data[$name])) {
            throw new Doctrine_Record_Exception('Unknown property '. $name);
        }
zYne's avatar
zYne committed
721
        if ($this->_data[$name] === self::$_null)
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
            return null;

        return $this->_data[$name];
    }

    /**
     * load
     * loads all the unitialized properties from the database
     *
     * @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;
    }
    /**
     * 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
750
     * @param boolean $load                     whether or not to invoke the loading procedure
751 752 753
     * @throws Doctrine_Record_Exception        if trying to get a value of unknown property / related component
     * @return mixed
     */
zYne's avatar
zYne committed
754
    public function get($name, $load = true)
755
    {
zYne's avatar
zYne committed
756 757
        $value = self::$_null;
        $lower = strtolower($name);
758

zYne's avatar
zYne committed
759
        $lower = $this->_table->getColumnName($lower);
zYne's avatar
zYne committed
760

761
        if (isset($this->_data[$lower])) {
zYne's avatar
zYne committed
762
            // check if the property is null (= it is the Doctrine_Null object located in self::$_null)
zYne's avatar
zYne committed
763
            if ($this->_data[$lower] === self::$_null && $load) {
764 765 766
                $this->load();
            }

zYne's avatar
zYne committed
767
            if ($this->_data[$lower] === self::$_null) {
768 769 770 771
                $value = null;
            } else {
                $value = $this->_data[$lower];
            }
772
            return $value;
773 774 775 776 777 778 779
        }

        if (isset($this->_values[$lower])) {
            return $this->_values[$lower];
        }

        try {
zYne's avatar
zYne committed
780 781 782 783 784 785

            if ( ! isset($this->_references[$name]) && $load) {

                $rel = $this->_table->getRelation($name);

                $this->_references[$name] = $rel->fetchRelatedFor($this);
786
            }
zYne's avatar
zYne committed
787
            return $this->_references[$name];
zYne's avatar
zYne committed
788

789
        } catch(Doctrine_Table_Exception $e) { 
790

zYne's avatar
zYne committed
791 792 793 794 795
            foreach ($this->_table->getFilters() as $filter) {
                if (($value = $filter->filterGet($this, $name, $value)) !== null) {
                    return $value;
                }
            }
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
        }
    }
    /**
     * 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)
    {
        $name = strtolower($name);
        $this->_values[$name] = $value;
    }
    /**
     * 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
     */
    public function set($name, $value, $load = true)
    {
        $lower = strtolower($name);

zYne's avatar
zYne committed
831 832
        $lower = $this->_table->getColumnName($lower);

833
        if (isset($this->_data[$lower])) {
zYne's avatar
zYne committed
834 835 836
            if ($value instanceof Doctrine_Record) {
                $type = $this->_table->getTypeOf($name);

837 838
                $id = $value->getIncremented();

zYne's avatar
zYne committed
839
                if ($id !== null && $type !== 'object') {
840
                    $value = $id;
zYne's avatar
zYne committed
841
                }
842 843 844
            }

            if ($load) {
zYne's avatar
zYne committed
845
                $old = $this->get($lower, $load);
846 847 848 849 850
            } else {
                $old = $this->_data[$lower];
            }

            if ($old !== $value) {
851
                if ($value === null) {
zYne's avatar
zYne committed
852
                    $value = self::$_null;
853
                }
zYne's avatar
zYne committed
854

855 856 857 858 859 860 861 862 863
                $this->_data[$lower] = $value;
                $this->_modified[]   = $lower;
                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
864
                }
865 866 867 868 869
            }
        } else {
            try {
                $this->coreSetRelated($name, $value);
            } catch(Doctrine_Table_Exception $e) {
zYne's avatar
zYne committed
870 871 872 873 874
                foreach ($this->_table->getFilters() as $filter) {
                    if (($value = $filter->filterSet($this, $name, $value)) !== null) {
                        return $value;
                    }
                }
875 876 877 878 879 880 881 882 883 884
            }
        }
    }

    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
885
            $rel instanceof Doctrine_Relation_LocalKey) {
886 887 888 889 890
            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
891 892 893 894
                if (isset($this->_references[$name])) {
                    $this->_references[$name]->setData($value->getData());
                    return $this;
                }
895
            } else {
896 897 898 899 900 901
                if ($value !== self::$_null) {
                    // 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) {
902
                        $foreign = $rel->getForeign();
903
                        if ( ! empty($foreign) && $foreign != $value->getTable()->getIdentifier())
904 905 906
                          $this->set($rel->getLocal(), $value->rawGet($foreign), false);
                        else
                          $this->set($rel->getLocal(), $value, false);                          
907 908 909
                    } else {
                        $value->set($rel->getForeign(), $this, false);
                    }                            
910 911 912 913 914 915 916 917 918 919
                }
            }

        } elseif ($rel instanceof Doctrine_Relation_Association) {
            // 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
920
        $this->_references[$name] = $value;
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937
    }
    /**
     * contains
     *
     * @param string $name
     * @return boolean
     */
    public function contains($name)
    {
        $lower = strtolower($name);

        if (isset($this->_data[$lower])) {
            return true;
        }
        if (isset($this->_id[$lower])) {
            return true;
        }
zYne's avatar
zYne committed
938
        if (isset($this->_values[$lower])) {
939
            return true;                                      
zYne's avatar
zYne committed
940
        }
941 942 943
        if (isset($this->_references[$name]) && 
            $this->_references[$name] !== self::$_null) {

944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
            return true;
        }
        return false;
    }
    /**
     * @param string $name
     * @return void
     */
    public function __unset($name)
    {
        if (isset($this->_data[$name])) {
            $this->_data[$name] = array();
        }
        // todo: what to do with references ?
    }
    /**
     * 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
974
        $conn->unitOfWork->saveGraph($this);
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
    }
    /**
     * 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.
     * 
     * @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;
        }
    }
    /**
     * 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
     * @throws PDOException                         if something fails at PDO level
     * @return integer                              number of rows affected
     */
    public function replace(Doctrine_Connection $conn = null)
    {
        if ($conn === null) {
            $conn = $this->_table->getConnection();
        }

        return $conn->replace($this->_table->getTableName(), $this->getPrepared(), $this->id);
    }
    /**
     * returns an array of modified fields and associated values
     * @return array
     */
    public function getModified()
    {
        $a = array();

        foreach ($this->_modified as $k => $v) {
            $a[$v] = $this->_data[$v];
        }
        return $a;
    }
    /**
     * 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
     */
zYne's avatar
zYne committed
1041 1042
    public function getPrepared(array $array = array()) 
    {
1043 1044 1045 1046 1047
        $a = array();

        if (empty($array)) {
            $array = $this->_modified;
        }
zYne's avatar
zYne committed
1048

1049 1050 1051
        foreach ($array as $k => $v) {
            $type = $this->_table->getTypeOf($v);

zYne's avatar
zYne committed
1052
            if ($this->_data[$v] === self::$_null) {
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
                $a[$v] = null;
                continue;
            }

            switch ($type) {
                case 'array':
                case 'object':
                    $a[$v] = serialize($this->_data[$v]);
                    break;
                case 'gzip':
                    $a[$v] = gzcompress($this->_data[$v],5);
                    break;
                case 'boolean':
zYne's avatar
zYne committed
1066
                    $a[$v] = $this->getTable()->getConnection()->convertBooleans($this->_data[$v]);
1067 1068
                break;
                case 'enum':
zYne's avatar
zYne committed
1069
                    $a[$v] = $this->_table->enumIndex($v, $this->_data[$v]);
1070 1071
                    break;
                default:
1072
                    if ($this->_data[$v] instanceof Doctrine_Record) {
1073
                        $this->_data[$v] = $this->_data[$v]->getIncremented();
zYne's avatar
zYne committed
1074
                    }
zYne's avatar
zYne committed
1075
                    /** TODO:
zYne's avatar
zYne committed
1076 1077 1078
                    if ($this->_data[$v] === null) {
                        throw new Doctrine_Record_Exception('Unexpected null value.');
                    }
zYne's avatar
zYne committed
1079
                    */
1080 1081 1082 1083

                    $a[$v] = $this->_data[$v];
            }
        }
zYne's avatar
zYne committed
1084 1085
        $map = $this->_table->inheritanceMap;
        foreach ($map as $k => $v) {
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
            $old = $this->get($k, false);

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

        return $a;
    }
    /**
     * count
     * this class implements countable interface
     *
     * @return integer          the number of columns in this record
     */
    public function count()
    {
        return count($this->_data);
    }
    /**
     * alias for count()
     *
     * @return integer          the number of columns in this record
     */
    public function columnCount()
    {
        return $this->count();
    }
    /**
     * toArray
     * returns the record as an array
     *
1119
     * @param boolean $deep - Return also the relations
1120 1121
     * @return array
     */
1122
    public function toArray($deep = false, $prefixKey = false)
1123 1124 1125 1126
    {
        $a = array();

        foreach ($this as $column => $value) {
zYne's avatar
zYne committed
1127 1128 1129
            if ($value === self::$_null) {
                $value = null;
            }
1130 1131
            $a[$column] = $value;
        }
1132
        if ($this->_table->getIdentifierType() ==  Doctrine::IDENTIFIER_AUTOINC) {
1133 1134 1135
            $i      = $this->_table->getIdentifier();
            $a[$i]  = $this->getIncremented();
        }
1136 1137
        if ($deep) {
            foreach ($this->_references as $key => $relation) {
1138 1139 1140
                if (!$relation instanceof Doctrine_Null) {
                    $a[$key] = $relation->toArray($deep, $prefixKey);
                }
1141 1142
            }
        }
zYne's avatar
zYne committed
1143
        return array_merge($a, $this->_values);
1144
    }
1145 1146
    public function fromArray($array)
    {
1147 1148
        if (is_array($array)) {
            foreach ($array as $key => $value) {
1149
                if ($this->getTable()->hasRelation($key) && $value) {
1150
                    $this->$key->fromArray($value);
1151
                } else if($this->getTable()->hasColumn($key) && $value) {
1152 1153
                    $this->$key = $value;
                }
1154 1155 1156
            }
        }
    }
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
    public function exportTo($type, $deep = false)
    {
        if ($type == 'array') {
            return $this->toArray($deep);
        } else {
            return Doctrine_Parser::dump($this->toArray($deep, true), $type);
        }
    }
    public function importFrom($type, $data)
    {
        if ($type == 'array') {
            return $this->fromArray($data);
        } else {
            return $this->fromArray(Doctrine_Parser::load($data, $type));
        }
    }
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
    /**
     * 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);
    }
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
    /**
     * 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);
    }
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
    /**
     * method for checking existence of properties and Doctrine_Record references
     * @param mixed $name               name of the property or reference
     * @return boolean
     */
    public function hasRelation($name)
    {
        if (isset($this->_data[$name]) || isset($this->_id[$name])) {
            return true;
        }
        return $this->_table->hasRelation($name);
    }
    /**
     * getIterator
     * @return Doctrine_Record_Iterator     a Doctrine_Record_Iterator that iterates through the data
     */
    public function getIterator()
    {
        return new Doctrine_Record_Iterator($this);
    }
    /**
     * 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
1228
        return $conn->unitOfWork->delete($this);
1229 1230 1231 1232 1233 1234 1235 1236 1237
    }
    /**
     * copy
     * returns a copy of this object
     *
     * @return Doctrine_Record
     */
    public function copy()
    {
1238
        $data = $this->_data;
zYne's avatar
zYne committed
1239 1240 1241 1242 1243 1244 1245 1246

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

            unset($data[$id]);
        }

        $ret = $this->_table->create($data);
1247
        $modified = array();
zYne's avatar
zYne committed
1248 1249

        foreach ($data as $key => $val) {
zYne's avatar
zYne committed
1250
            if ( ! ($val instanceof Doctrine_Null)) {
1251 1252 1253
                $ret->_modified[] = $key;
            }
        }
zYne's avatar
zYne committed
1254 1255
        

1256 1257
        return $ret;
    }
runa's avatar
runa committed
1258 1259 1260 1261 1262 1263
    /**
     * copyDeep
     * returns a copy of this object and all its related objects
     *
     * @return Doctrine_Record
     */
1264
    public function copyDeep() {
zYne's avatar
zYne committed
1265 1266
        $copy = $this->copy();

zYne's avatar
zYne committed
1267
        foreach ($this->_references as $key => $value) {
zYne's avatar
zYne committed
1268 1269 1270
            if ($value instanceof Doctrine_Collection) {
                foreach ($value as $record) {
                    $copy->{$key}[] = $record->copyDeep();
runa's avatar
runa committed
1271
                }
zYne's avatar
zYne committed
1272 1273
            } else {
                $copy->set($key, $value->copyDeep());
runa's avatar
runa committed
1274 1275
            }
        }
zYne's avatar
zYne committed
1276
        return $copy;
runa's avatar
runa committed
1277 1278
    }
    
1279 1280 1281 1282 1283 1284
    /**
     * assignIdentifier
     *
     * @param integer $id
     * @return void
     */
zYne's avatar
zYne committed
1285
    public function assignIdentifier($id = false)
1286 1287 1288
    {
        if ($id === false) {
            $this->_id       = array();
zYne's avatar
zYne committed
1289
            $this->_data     = $this->cleanData($this->_data);
1290 1291 1292
            $this->_state    = Doctrine_Record::STATE_TCLEAN;
            $this->_modified = array();
        } elseif ($id === true) {
zYne's avatar
zYne committed
1293
            $this->prepareIdentifiers(true);
1294 1295 1296
            $this->_state    = Doctrine_Record::STATE_CLEAN;
            $this->_modified = array();
        } else {
zYne's avatar
zYne committed
1297
            $name             = $this->_table->getIdentifier();   
1298
            $this->_id[$name] = $id;
zYne's avatar
zYne committed
1299
            $this->_data[$name] = $id;
1300 1301 1302 1303 1304 1305 1306 1307 1308
            $this->_state     = Doctrine_Record::STATE_CLEAN;
            $this->_modified  = array();
        }
    }
    /**
     * returns the primary keys of this object
     *
     * @return array
     */
1309
    public function identifier()
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
    {
        return $this->_id;
    }
    /**
     * returns the value of autoincremented primary key of this object (if any)
     *
     * @return integer
     */
    final public function getIncremented()
    {
        $id = current($this->_id);
zYne's avatar
zYne committed
1321
        if ($id === false) {
1322
            return null;
zYne's avatar
zYne committed
1323
        }
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345

        return $id;
    }
    /**
     * 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;
    }
    /**
     * hasRefence
     * @param string $name
     * @return boolean
     */
    public function hasReference($name)
    {
zYne's avatar
zYne committed
1346
        return isset($this->_references[$name]);
1347
    }
zYne's avatar
zYne committed
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
    /**
     * reference
     *
     * @param string $name
     */
    public function reference($name)
    {
        if (isset($this->_references[$name])) {
            return $this->_references[$name];
        }
    }
1359 1360 1361 1362 1363 1364 1365 1366
    /**
     * 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
1367 1368
        if (isset($this->_references[$name])) {
            return $this->_references[$name];
1369 1370 1371 1372 1373 1374 1375 1376 1377
        }
        throw new Doctrine_Record_Exception("Unknown reference $name");
    }
    /**
     * getReferences
     * @return array    all references
     */
    public function getReferences()
    {
zYne's avatar
zYne committed
1378
        return $this->_references;
1379 1380 1381 1382 1383 1384 1385 1386 1387
    }
    /**
     * setRelated
     *
     * @param string $alias
     * @param Doctrine_Access $coll
     */
    final public function setRelated($alias, Doctrine_Access $coll)
    {
zYne's avatar
zYne committed
1388
        $this->_references[$alias] = $coll;
1389 1390 1391 1392 1393 1394 1395 1396 1397
    }
    /**
     * loadReference
     * loads a related component
     *
     * @throws Doctrine_Table_Exception             if trying to load an unknown related component
     * @param string $name
     * @return void
     */
1398
    public function loadReference($name)
1399
    {
1400 1401
        $rel = $this->_table->getRelation($name);
        $this->_references[$name] = $rel->fetchRelatedFor($this);
1402
    }
zYne's avatar
zYne committed
1403

1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
    /**
     * merge
     * merges this record with an array of values
     *
     * @param array $values
     * @return void
     */
    public function merge(array $values)
    {
        foreach ($this->_table->getColumnNames() as $value) {
            try {
                if (isset($values[$value])) {
                    $this->set($value, $values[$value]);
                }
            } catch(Exception $e) {
                // silence all exceptions
            }
        }
    }
zYne's avatar
zYne committed
1423
    
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
    /**
     * 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])) {
            $column = $args[0];
            $args[0] = $this->get($column);

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

            $this->_data[$column] = $newvalue;
        }
        return $this;
    }
1447 1448 1449 1450 1451
    /**
     * getter for node assciated with this record
     *
     * @return mixed if tree returns Doctrine_Node otherwise returns false
     */    
zYne's avatar
zYne committed
1452 1453 1454 1455 1456
    public function getNode() 
    {
        if ( ! $this->_table->isTree()) {
            return false;
        }
1457

zYne's avatar
zYne committed
1458 1459
        if ( ! isset($this->_node)) {
            $this->_node = Doctrine_Node::factory($this,
zYne's avatar
zYne committed
1460 1461 1462
                                              $this->getTable()->getOption('treeImpl'),
                                              $this->getTable()->getOption('treeOptions')
                                              );
zYne's avatar
zYne committed
1463
        }
1464
        
zYne's avatar
zYne committed
1465
        return $this->_node;
1466
    }
zYne's avatar
zYne committed
1467 1468 1469 1470 1471

    public function unshiftFilter(Doctrine_Record_Filter $filter)
    {
        return $this->_table->unshiftFilter($filter);
    }
zYne's avatar
zYne committed
1472 1473 1474 1475 1476 1477 1478 1479 1480
    /**
     * 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
1481 1482
    public function revert($version)
    {
zYne's avatar
zYne committed
1483 1484 1485 1486
        $data = $this->_table
                ->getTemplate('Doctrine_Template_Versionable')
                ->getAuditLog()
                ->getVersion($this, $version);
zYne's avatar
zYne committed
1487

zYne's avatar
zYne committed
1488
        if ( ! isset($data[0])) {
zYne's avatar
zYne committed
1489
            throw new Doctrine_Record_Exception('Version ' . $version . ' does not exist!');
zYne's avatar
zYne committed
1490 1491
        }

zYne's avatar
zYne committed
1492
        $this->_data = $data[0];
zYne's avatar
zYne committed
1493 1494

        return $this;
zYne's avatar
zYne committed
1495
    }
zYne's avatar
zYne committed
1496
    /**
zYne's avatar
zYne committed
1497
     * unlink
zYne's avatar
zYne committed
1498
     * removes links from this record to given records
jackbravo's avatar
jackbravo committed
1499
     * if no ids are given, it removes all links
zYne's avatar
zYne committed
1500
     *
zYne's avatar
zYne committed
1501 1502 1503
     * @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
1504
     */
jackbravo's avatar
jackbravo committed
1505
    public function unlink($alias, $ids = array())
zYne's avatar
zYne committed
1506 1507 1508 1509 1510 1511 1512
    {
        $ids = (array) $ids;
        
        $q = new Doctrine_Query();

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

zYne's avatar
zYne committed
1513 1514 1515
        if ($rel instanceof Doctrine_Relation_Association) {
            $q->delete()
              ->from($rel->getAssociationTable()->getComponentName())
jackbravo's avatar
jackbravo committed
1516 1517 1518 1519 1520
              ->where($rel->getLocal() . ' = ?', array_values($this->identifier()));

            if (count($ids) > 0) {
                $q->whereIn($rel->getForeign(), $ids);
            }
zYne's avatar
zYne committed
1521 1522 1523

            $q->execute();

zYne's avatar
zYne committed
1524 1525 1526 1527

        } elseif ($rel instanceof Doctrine_Relation_ForeignKey) {
            $q->update($rel->getTable()->getComponentName())
              ->set($rel->getForeign(), '?', array(null))
jackbravo's avatar
jackbravo committed
1528 1529 1530 1531 1532
              ->addWhere($rel->getForeign() . ' = ?', array_values($this->identifier()));

            if (count($ids) > 0) {
                $q->whereIn($rel->getTable()->getIdentifier(), $ids);
            }
zYne's avatar
zYne committed
1533 1534 1535 1536 1537 1538 1539

            $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
1540 1541
                }
            }
zYne's avatar
zYne committed
1542
            $this->_references[$alias]->takeSnapshot();
zYne's avatar
zYne committed
1543 1544 1545
        }
        return $this;
    }
zYne's avatar
zYne committed
1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
    /**
     * __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
     */
1559 1560
    public function __call($method, $args) 
    {
zYne's avatar
zYne committed
1561
        if (($template = $this->_table->getMethodOwner($method)) !== false) {
1562
            $template->setInvoker($this);
zYne's avatar
zYne committed
1563
            return call_user_func_array(array($template, $method), $args);
1564
        }
1565
        
zYne's avatar
zYne committed
1566
        foreach ($this->_table->getTemplates() as $template) {
1567
            if (method_exists($template, $method)) {
zYne's avatar
zYne committed
1568
                $template->setInvoker($this);
zYne's avatar
zYne committed
1569
                $this->_table->setMethodOwner($method, $template);
zYne's avatar
zYne committed
1570
                
1571 1572 1573 1574 1575 1576
                return call_user_func_array(array($template, $method), $args);
            }
        }
        
        throw new Doctrine_Record_Exception('Unknown method ' . $method);
    }
1577 1578 1579 1580 1581
    /**
     * used to delete node from tree - MUST BE USE TO DELETE RECORD IF TABLE ACTS AS TREE
     *
     */    
    public function deleteNode() {
zYne's avatar
zYne committed
1582
        $this->getNode()->delete();
1583
    }
zYne's avatar
zYne committed
1584 1585 1586 1587
    public function toString()
    {
        return Doctrine::dump(get_object_vars($this));
    }
1588 1589 1590 1591 1592
    /**
     * returns a string representation of this object
     */
    public function __toString()
    {
zYne's avatar
zYne committed
1593
        return (string) $this->_oid;
1594
    }
1595
}